forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

stream.rs21575 lines, 1.6 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};
22use ec_core::{Error, Result};
23
24use crate::cdf_state::Cdfs;
25use crate::decode;
26use crate::decode::{
27 decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs,
28 q_ctx_of,
29};
30#[cfg(test)]
31use crate::decode::decode_key_frame_tile_lr;
32use crate::encode::Picture;
33
34/// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a
35/// mid-film mismatch splits into "reconstruction" (compare against
36/// `ffmpeg -c:v libdav1d -filmgrain 0`) and "grain synthesis" in one run.
37fn no_grain() -> bool {
38 std::env::var_os("EC_AV1_NO_GRAIN").is_some()
39}
40
41// lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the
42// current thread, overriding the environment variable. Every ffmpeg/aomdec
43// pixel gate in this repo compares SHOWN frames only (class
44// gate-blind-to-hidden-frames), so the hidden alt-ref frames a real aomenc
45// stream carries were never compared at all; the gate that does compare
46// them needs a dump path that cannot race a sibling test's decode on
47// another thread, which a process-global env var cannot give.
48thread_local! {
49 static FINAL_DUMP_PREFIX: std::cell::RefCell<Option<String>> =
50 const { std::cell::RefCell::new(None) };
51}
52
53/// Sets (or with `None` clears) this thread's `EC_AV1_FINAL_DUMP` prefix.
54#[allow(dead_code)]
55pub(crate) fn set_final_dump_prefix(prefix: Option<String>) {
56 FINAL_DUMP_PREFIX.with(|c| *c.borrow_mut() = prefix);
57}
58
59fn final_dump_prefix() -> Option<String> {
60 FINAL_DUMP_PREFIX
61 .with(|c| c.borrow().clone())
62 .or_else(|| std::env::var("EC_AV1_FINAL_DUMP").ok())
63}
64
65/// 32x32-level 1:4 strip counters, for `decode_probe`'s fixture search:
66/// (HORZ_4 strips, VERT_4 strips, strips that read coefficients).
67/// lane-inter4 r1: the INTER-frame partition counters this lane's gates
68/// assert -- `(32x8, 8x32, 64x32, 32x64, 64x16, 16x64)` strips decoded.
69pub fn inter_rect_counters() -> (usize, usize, usize, usize, usize, usize) {
70 (
71 crate::decode::rect4_32_horz_inter_hits(),
72 crate::decode::rect4_32_vert_inter_hits(),
73 crate::decode::inter_sb_horz_hits(),
74 crate::decode::inter_sb_vert_hits(),
75 crate::decode::inter_sb_horz4_hits(),
76 crate::decode::inter_sb_vert4_hits(),
77 )
78}
79
80/// lane-r14 r2: luma transform units of an inter strip with a 64-px axis,
81/// coded as the truncated low-32 coefficient corner.
82pub fn rect64_inter_tu_hits() -> usize {
83 crate::decode::rect64_inter_tu_hits()
84}
85
86/// lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
87/// inter strip (`TX_32X8`/`TX_8X32`), `[32x8, 8x32]`.
88pub fn rect32x8_inter_tu_hits() -> [usize; 2] {
89 crate::decode::rect32x8_inter_tu_hits()
90}
91
92/// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherited a
93/// `tx_type` different from the group's FIRST sub-block, i.e. groups that can
94/// only decode right under `av1_get_tx_type`'s chroma-reference rule.
95pub fn sub8_chroma_tx_from_ref_hits() -> usize {
96 crate::decode::sub8_chroma_tx_from_ref_hits()
97}
98
99/// lane-intra16x4: `(16x4, 4x16, chroma-reference)` INTRA strips decoded inside
100/// an inter 16x16-level 1:4 partition.
101pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
102 crate::decode::intra16x4_in_inter_hits()
103}
104
105/// lane-sub8intra: INTRA 8x4/4x8 leaves inside an inter frame's sub-8x8
106/// HORZ/VERT partition, `(8x4, 4x8, chroma-reference, mixed groups, split
107/// 4x4 leaves)`.
108pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
109 crate::decode::sub8_intra_rect_hits()
110}
111
112/// lane-r14 r3: RECTANGULAR var-tx leaf transform units, `[32x16, 16x32]` --
113/// the leaves `sub_tx_size_map` produces when a 1:4 strip with a 64-px axis
114/// splits its transform (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`).
115pub fn vartx_rect_leaf_hits() -> [usize; 2] {
116 crate::decode::vartx_rect_leaf_hits()
117}
118
119/// How many rect intra strips read the `use_intrabc` symbol on the last decode.
120pub fn rect_intrabc_reads() -> usize {
121 crate::decode::rect_intrabc_reads()
122}
123
124/// `(y, uv)` palette blocks RECONSTRUCTED inside an inter frame (lane-t900
125/// r22) -- the counter a screen-content witness gate reads to prove it
126/// exercises the inter-frame palette path, not the key frame's.
127pub fn intra_in_inter_palette_hits() -> (usize, usize) {
128 crate::decode::intra_in_inter_palette_hits()
129}
130
131/// `(y, uv)` palette blocks reconstructed on an 8x8 LEAF inside an inter
132/// frame (lane-t900 r23) -- the site-specific half of
133/// [`intra_in_inter_palette_hits`], which a >=16 block also moves.
134pub fn inter8_palette_hits() -> (usize, usize) {
135 crate::decode::inter8_palette_hits()
136}
137
138/// lane-rect64port r1: coded 64-level HORZ/VERT intra strips whose luma
139/// transform unit is the un-split TX_64X32 (orient 0) / TX_32X64 (orient 1).
140pub fn rect64_corner_tu_hits(orient: usize) -> usize {
141 crate::decode::rect64_corner_tu_hits(orient)
142}
143
144/// lane-inter16ab r4: RECTANGULAR var-tx leaves with a 4-px axis, `[8x4, 4x8]`
145/// -- what `sub_tx_size_map[TX_16X4] == TX_8X4` produces when a 16x16-level
146/// 1:4 inter strip splits its transform.
147pub fn vartx_rect_leaf4_hits() -> [usize; 2] {
148 crate::decode::vartx_rect_leaf4_hits()
149}
150
151/// lane-inter16ab r5: COMPOUND_WEDGE / wedge-INTERINTRA blocks that used a
152/// RECTANGULAR wedge codebook row, per shape (`RECT_WEDGE_SHAPES` order:
153/// 8x16, 16x8, 16x32, 32x16, 8x32, 32x8).
154pub fn rect_wedge_hits() -> [usize; 6] {
155 crate::decode::rect_wedge_hits()
156}
157
158/// lane-inter16ab r5: the wedge-interintra half of [`rect_wedge_hits`].
159pub fn rect_wii_hits() -> [usize; 6] {
160 crate::decode::rect_wii_hits()
161}
162
163/// lane-sb128c r7: the 128 root's rect arms -- (gathered edge HORZ, gathered
164/// edge VERT, inter 128x64 blocks, inter 64x128 blocks).
165pub fn sb128_rect_counters() -> (usize, usize, usize, usize) {
166 (
167 crate::decode::part128_edge_horz_hits(),
168 crate::decode::part128_edge_vert_hits(),
169 crate::decode::inter_sb128_horz_hits(),
170 crate::decode::inter_sb128_vert_hits(),
171 )
172}
173
174/// Blocks reconstructed with intra block copy at an 8x8 LEAF specifically
175/// (lane-kf900 r7's shape); [`crate::decode::intrabc_hits`] counts every shape.
176pub fn leaf8_intrabc_hits() -> usize {
177 crate::decode::leaf8_intrabc_hits()
178}
179
180/// lane-sb128c r8: the 128 root's INTRA (key-frame) rect arm -- (128x64
181/// blocks, 64x128 blocks, blocks per resolved intra `tx_depth` 0/1/2).
182pub fn intra_sb128_counters() -> (usize, usize, [usize; 3]) {
183 crate::decode::intra_sb128_hits()
184}
185
186/// lane-inter128intra r1: the 128 root's HORZ/VERT half coded INTRA inside an
187/// INTER frame -- (128x64 blocks, 64x128 blocks).
188pub fn intra128_in_inter_counters() -> [usize; 2] {
189 crate::decode::intra128_in_inter_hits()
190}
191
192/// lane-sb128c r9: the four AB shapes at the 128 root, in `PARTITION_HORZ_A`,
193/// `_HORZ_B`, `_VERT_A`, `_VERT_B` order (key and inter tile paths share the
194/// counter -- it is bumped where the root symbol resolves).
195pub fn sb128_ab_counters() -> [usize; 4] {
196 crate::decode::part128_ab_hits()
197}
198
199/// lane-obmcrec r1: OBMC neighbours taken from the second half of a 1:4-strip
200/// chroma pair -- the shape whose filter record the r1 fix re-sourced.
201pub fn obmc_pair_filter_hits() -> usize {
202 crate::decode::obmc_pair_filter_hits()
203}
204
205/// Gate counters for the 4x32/32x4 rectangular strips: `(horz, vert, coeff)` hits.
206pub fn rect4_32_counters() -> (usize, usize, usize) {
207 (
208 crate::decode::rect4_32_horz_hits(),
209 crate::decode::rect4_32_vert_hits(),
210 crate::decode::rect4_coeff_hits(),
211 )
212}
213
214/// lane-inter4 r4: rectangular inter transform units coded whole, rect
215/// var-tx trees that split, and OBMC blends run on a 16x8/8x16 leaf -- the
216/// three counters a recipe sweep needs to see from outside the crate.
217pub fn rect_inter_tu_counters() -> (usize, usize, usize) {
218 (
219 crate::decode::rect_inter_tu_hits(),
220 crate::decode::rect_inter_txsplit_hits(),
221 crate::decode::obmc_rect_leaf_hits(),
222 )
223}
224
225/// Decode every frame in a raw AV1 OBU stream, in coding order.
226///
227/// A key frame becomes the reference for the inter frames that follow it,
228/// until the next key frame resets the DPB — the same single-slot chain
229/// [`crate::encode::encode_sequence`] threads on the write side. Only a
230/// `Frame` OBU (an uncompressed header and its tile group in one OBU, which
231/// is all this crate's encoder ever writes) carries a tile payload; sequence
232/// headers and temporal delimiters are consumed for the state they carry (or
233/// skipped) and produce no picture.
234///
235/// # Errors
236/// Returns an error when the stream is truncated or malformed (as
237/// [`Av1Parser`] reports it), when a frame header names anything this
238/// crate's tile decoders do not reconstruct (see their own docs), or when an
239/// inter frame appears before any key frame has supplied a reference.
240pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
241 let mut pictures = Vec::new();
242 decode_stream_with(data, |picture, _decode_idx, shown| {
243 if shown {
244 pictures.push(picture.clone());
245 }
246 Ok(())
247 })?;
248 Ok(pictures)
249}
250
251/// Streaming form of [`decode_stream`]: hand every completed picture to
252/// `sink` the moment it exists and drop it right after, so peak memory is one
253/// output picture plus the 8-slot DPB instead of the whole decoded stream --
254/// a 4K long-GOP segment costs the same as a short one. `decode_stream`
255/// itself is this function collecting into a `Vec`.
256///
257/// `sink` is called with the picture, the decode-order index of the coded
258/// frame it came from, and whether it is output: a hidden reference frame
259/// (`show_frame == 0`) is reported with `shown == false` and is NOT part of
260/// `decode_stream`'s output, a `show_existing_frame` output with `true`.
261/// The grain-synthesised picture is what a shown frame's sink sees; the
262/// reference bank keeps the clean one (spec 7.18.3.1). An `Err` the sink
263/// returns aborts the decode and is returned unchanged.
264///
265/// # Errors
266/// As [`decode_stream`], plus whatever `sink` returns.
267pub fn decode_stream_with(
268 data: &[u8],
269 sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
270) -> Result<()> {
271 decode_stream_with_threads(data, decode_threads(), sink)
272}
273
274/// lane-thread2: how many threads [`decode_stream_with`] decodes with --
275/// `EC_AV1_THREADS`, default 1. One is not "threading with a pool of one":
276/// it is the single-threaded decoder unchanged, which is what keeps every
277/// gate that reads this crate's per-thread counters meaningful.
278fn decode_threads() -> usize {
279 static N: std::sync::LazyLock<usize> = std::sync::LazyLock::new(|| {
280 crate::envflags::var("EC_AV1_THREADS")
281 .ok()
282 .and_then(|v| v.parse::<usize>().ok())
283 .filter(|&n| n > 0)
284 .unwrap_or(1)
285 });
286 *N
287}
288
289/// lane-thread2: output-order queue. A leaf frame decoded on a worker
290/// finishes whenever it finishes; `sink` must still see every picture in the
291/// order the stream codes them, so each sink call gets an `emit_seq` when the
292/// main thread reaches its frame header and is held here until every earlier
293/// one has been emitted. (The decode index the sink is TOLD is unchanged, and
294/// is deliberately not unique: a `show_existing_frame` re-output reports the
295/// count of frames decoded before it, per this function's contract.)
296#[derive(Default)]
297struct Reorder {
298 next: usize,
299 // lane-pool1: the picture is shared, not owned -- a decoded frame that
300 // refreshes a reference slot is already behind an `Arc` for the slot, and
301 // handing the output an owned `Picture` meant copying every plane of it
302 // (24 MB per 4K 10-bit frame) purely to put it in this queue.
303 pending: std::collections::BTreeMap<usize, (std::sync::Arc<Picture>, usize, bool)>,
304}
305
306impl Reorder {
307 fn push(&mut self, seq: usize, picture: std::sync::Arc<Picture>, decode_idx: usize, shown: bool) {
308 self.pending.insert(seq, (picture, decode_idx, shown));
309 }
310
311 /// Emits every queued picture whose turn has come. An `Err` from `sink`
312 /// aborts the decode, unchanged, exactly as the serial path did.
313 fn drain(
314 &mut self,
315 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,
316 ) -> Result<()> {
317 while let Some((picture, decode_idx, shown)) = self.pending.remove(&self.next) {
318 self.next += 1;
319 sink(&picture, decode_idx, shown)?;
320 crate::timeline::output(decode_idx);
321 }
322 Ok(())
323 }
324}
325
326/// lane-thread2/3: how many coded frames this PROCESS has dispatched to a
327/// worker thread (see [`decode_stream_with_threads`]). Process-global and
328/// atomic on purpose: it is the only counter here a caller can read after a
329/// threaded decode, and it is what keeps a "decodes identically with 4
330/// threads" gate from silently proving nothing because every frame ran
331/// inline. (lane-thread2 counted only LEAF frames, the only ones it could
332/// dispatch; lane-thread3 dispatches every non-key, non-`show_existing_frame`
333/// frame, hence the rename.)
334static FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize =
335 std::sync::atomic::AtomicUsize::new(0);
336
337/// Reads [`FRAMES_DISPATCHED`].
338pub fn frames_dispatched() -> usize {
339 FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed)
340}
341
342/// lane-thread3: what one decoded frame stores into every reference slot its
343/// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated
344/// object -- so a slot costs an `Arc` clone instead of a picture copy.
345struct SlotValue {
346 /// lane-twostage: this frame's FILTERED pixels, still being produced
347 /// when the rest of this value is published.
348 pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>>,
349 /// The size those pixels will have, known from the tile decode.
350 width: usize,
351 height: usize,
352 cdfs: Cdfs,
353 motion_field: crate::motion_field::MotionField,
354 seg_map: Vec<u8>,
355 order_hint: u32,
356}
357
358/// lane-thread3: a reference slot's contents as a FUTURE. At `threads > 1`
359/// the 8-slot bank holds these instead of values: a slot refreshed by a frame
360/// that is still decoding on a worker holds the promise from the moment the
361/// parsing thread DISPATCHES that frame, so the next frame can be dispatched
362/// straight away and waits, on its own worker, for exactly the slots it
363/// reads. This is what makes a pyramid stream (aomenc's default, where nearly
364/// every coded frame refreshes a slot, so lane-thread2's leaf rule dispatched
365/// almost nothing) decode in parallel.
366///
367/// DEADLOCK ARGUMENT. A promise is installed into a slot on the parsing
368/// thread, in decode order, when its producer is dispatched; a consumer
369/// captures the promises of the slots it reads at ITS dispatch, which is
370/// strictly later in decode order. Every wait therefore points from a later
371/// coded frame to an earlier one -- the wait graph is the reference DAG, and
372/// is acyclic. The parsing thread waits only for a `show_existing_frame`
373/// output (again an earlier frame) and at the in-flight bound, where it waits
374/// for ANY worker to answer: the earliest in-flight frame has no earlier
375/// in-flight producer, so it is always runnable and the bound always clears.
376/// Each dispatched frame gets its own thread, so a blocked waiter never holds
377/// a resource its producer needs. A producer that errors or panics marks its
378/// promise `Failed`, so no consumer can wait for a value that never comes.
379struct SlotPromise<T = std::sync::Arc<SlotValue>> {
380 state: std::sync::Mutex<PromiseState<T>>,
381 ready: std::sync::Condvar,
382}
383
384enum PromiseState<T> {
385 Pending,
386 Ready(T),
387 Failed,
388}
389
390impl<T: Clone> SlotPromise<T> {
391 fn pending() -> std::sync::Arc<Self> {
392 std::sync::Arc::new(Self {
393 state: std::sync::Mutex::new(PromiseState::Pending),
394 ready: std::sync::Condvar::new(),
395 })
396 }
397
398 /// A slot filled by a frame the parsing thread decoded itself.
399 fn ready(value: T) -> std::sync::Arc<Self> {
400 std::sync::Arc::new(Self {
401 state: std::sync::Mutex::new(PromiseState::Ready(value)),
402 ready: std::sync::Condvar::new(),
403 })
404 }
405
406 fn fulfil(&self, value: T) {
407 *self.state.lock().expect("slot promise") = PromiseState::Ready(value);
408 self.ready.notify_all();
409 }
410
411 /// lane-twostage: fulfils only a promise the stage-1 sink did not
412 /// already fill (a superres frame, or a key frame, whose meta is
413 /// published here as it always was).
414 fn fulfil_if_pending(&self, value: impl FnOnce() -> T) {
415 let mut state = self.state.lock().expect("slot promise");
416 if matches!(*state, PromiseState::Pending) {
417 *state = PromiseState::Ready(value());
418 }
419 self.ready.notify_all();
420 }
421
422 fn fail(&self) {
423 let mut state = self.state.lock().expect("slot promise");
424 if matches!(*state, PromiseState::Pending) {
425 *state = PromiseState::Failed;
426 }
427 self.ready.notify_all();
428 }
429
430 /// Blocks until the producing frame has published this slot.
431 fn wait(&self) -> Result<T> {
432 let mut state = self.state.lock().expect("slot promise");
433 loop {
434 match &*state {
435 PromiseState::Ready(value) => return Ok(value.clone()),
436 PromiseState::Failed => {
437 return Err(Error::corrupt(
438 "AV1 decode_stream: a reference frame this frame depends on failed to decode",
439 ));
440 }
441 PromiseState::Pending => {
442 state = self.ready.wait(state).expect("slot promise");
443 }
444 }
445 }
446 }
447}
448
449/// One finished frame from a worker: its output position, whether the job was
450/// a frame DECODE (as opposed to a `show_existing_frame` output, which only
451/// waits for a slot and synthesises grain -- lane-thread3 counts the two
452/// against separate in-flight bounds, since a waiting output job costs no
453/// CPU), and either the (grain-synthesised) picture with the decode index to
454/// report or the error that aborts the stream.
455type LeafResult = (usize, bool, Result<(std::sync::Arc<Picture>, usize, bool)>);
456
457/// Waits for one in-flight job and emits whatever that unblocks.
458fn collect_one(
459 rx: &std::sync::mpsc::Receiver<LeafResult>,
460 decodes: &mut usize,
461 shows: &mut usize,
462 reorder: &mut Reorder,
463 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,
464) -> Result<()> {
465 // Every dispatched worker answers exactly once, panic included (it is
466 // caught and turned into an error below), so the sender count cannot
467 // reach zero while `in_flight > 0`.
468 let (seq, decode_job, result) = rx
469 .recv()
470 .map_err(|_| Error::corrupt("AV1 decode_stream: a worker thread vanished"))?;
471 if decode_job {
472 *decodes -= 1;
473 } else {
474 *shows -= 1;
475 }
476 let (picture, decode_idx, shown) = result?;
477 reorder.push(seq, picture, decode_idx, shown);
478 reorder.drain(sink)
479}
480
481/// [`decode_stream_with`] with an explicit worker count (lane-thread2).
482///
483/// `threads == 1` is the serial decoder. Above that, frames that no later
484/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags`
485/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads
486/// while the main thread keeps parsing headers and decoding the frames that
487/// DO feed the reference banks; `sink` still sees every picture in coded
488/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot
489/// of the banks taken before dispatch, so no decode state is shared.
490///
491/// The per-decode counters this crate's gates read are thread-local, so at
492/// `threads > 1` a leaf frame's counts land on the worker and are invisible
493/// to the caller; that is why the default is 1.
494///
495/// # Errors
496/// As [`decode_stream_with`]; a worker's error aborts the stream.
497pub fn decode_stream_with_threads(
498 data: &[u8],
499 threads: usize,
500 mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
501) -> Result<()> {
502 // lane-pool1: this replaced a `std::thread::scope` -- frame workers now
503 // come from a persistent pool (one per submitting thread, workers reused
504 // across frames, so their `thread_local!` decode scratch survives the
505 // frame). `jobs` is declared here and dropped at the end of the function,
506 // including on `?`, so no job outlives the data it borrows.
507 let jobs = crate::par::Batch::new("ec-av1-frame");
508 // lane-thread1: this stream's per-frame decode state (was 38 thread_local
509 // statics in decode.rs) -- one object, threaded down the decode call graph.
510 let fctx = &crate::decode::FrameCtx::new();
511 let final_dump = final_dump_prefix();
512 let mut parser = Av1Parser::new();
513 let mut pictures_shown: usize = 0;
514 let mut pictures_decoded: usize = 0;
515 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
516 // previous frame's `refresh_frame_flags` stored into it, exactly like the
517 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
518 // not simply "the previous frame decoded"; a frame whose own predecessor
519 // didn't refresh that slot (an altref/hidden frame, or any GOP with more
520 // than one live reference) must keep predicting from whatever picture is
521 // still sitting there. Round 7's cdffwd hunt: a global `reference`
522 // overwritten every frame silently always used "the most recent decode"
523 // instead, producing a bit-exact motion vector into the WRONG picture --
524 // luma-only (chroma coincidentally shares this fixture's flat regions)
525 // and small-magnitude (the two pictures mostly agree), which is exactly
526 // what made it look like a rounding bug rather than a wrong reference.
527 // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy
528 // its whole picture k times, and its output a (k+1)-th time.
529 let mut ref_slots: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] =
530 std::array::from_fn(|_| None);
531 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
532 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
533 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
534 // decoded with -- `Picture` itself carries neither, so both ride
535 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
536 let mut motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES] =
537 std::array::from_fn(|_| None);
538 let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES];
539 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
540 // previous frame's `refresh_frame_flags` stored into it -- the frame's
541 // own end-of-tile adapted table, or (when the frame set
542 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
543 let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
544 // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also
545 // remembers the segment map the frame stored there decoded, which is what
546 // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`
547 // (spec `load_previous_segment_ids`) for temporal segment-id prediction
548 // and for a `segmentation_update_map == 0` frame's inherited map.
549 let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
550
551 // lane-thread2: output plumbing (inert at `threads == 1`, where nothing
552 // is ever dispatched and `reorder` emits each picture the moment it is
553 // pushed).
554 let mut emit_seq = 0usize;
555 let mut reorder = Reorder::default();
556 // lane-thread3: frame decodes and `show_existing_frame` outputs are
557 // bounded separately -- an output job is a promise wait plus a memcpy, so
558 // letting it eat a decode's budget just idles a core (measured: sharing
559 // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%).
560 let mut in_flight_decodes = 0usize;
561 let mut in_flight_shows = 0usize;
562 let in_flight_cap = threads + 2;
563 let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
564 // lane-thread3: at `threads > 1` THIS is the reference bank -- one
565 // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled
566 // itself and pending for one an in-flight frame will fill. The owned
567 // arrays above are then untouched (and the single-threaded path never
568 // creates a promise: it stays exactly the decoder it was, which is what
569 // keeps every counter-reading gate meaningful).
570 let mut slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
571 std::array::from_fn(|_| None);
572 // lane-timeline: which decoded frame installed each slot's promise, so
573 // the timeline records a dependency EDGE (frame -> producing frame) and
574 // not just a slot number. `usize::MAX` = nobody yet.
575 let mut slot_owner = [usize::MAX; NUM_REF_FRAMES];
576
577 let mut pos = 0usize;
578 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
579 // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone
580 // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no
581 // tile payload of its own -- `OBU_FRAME` (the `ObuKind::Frame` arm below)
582 // only ever folds ONE tile group into the header's own OBU. Stash the
583 // header here and accumulate tiles from each `OBU_TILE_GROUP` that
584 // follows until every tile of the frame has arrived.
585 let mut pending_header: Option<Box<FrameHeader>> = None;
586 let mut pending_tiles: Vec<Tile> = Vec::new();
587 while pos < data.len() {
588 let obu = parser.parse_obu(&data[pos..])?;
589 let obu_offset = pos;
590 pos += obu.total_size;
591
592 if let ObuKind::FrameHeader(header) = &obu.kind {
593 if !header.show_existing_frame {
594 // Before this fix, this branch fired unconditionally for
595 // EVERY `FrameHeader` OBU (including this one), so a
596 // standalone header always fell into the `show_existing_frame`
597 // slot lookup below and misreported "a show_existing_frame
598 // header naming an empty reference slot" for a frame that was
599 // never a show_existing_frame header at all.
600 pending_header = Some(header.clone());
601 pending_tiles = Vec::new();
602 continue;
603 }
604 // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
605 // OBU only names a DPB slot to output again -- the coded-frame
606 // count and the shown-picture count are different things (a
607 // hidden altref's own `Frame` OBU below is never pushed to
608 // `pictures` on its own; it is only pushed here, later, when a
609 // `show_existing_frame` header names its slot). Before r15 this
610 // arm didn't exist at all: every `ObuKind::Frame` was pushed
611 // unconditionally regardless of `show_frame`, so a hidden altref
612 // was emitted (wrongly, in decode order) and its real
613 // `show_existing_frame` output was silently dropped.
614 let slot = header.frame_to_show_map_idx as usize;
615 let empty_slot = || {
616 Error::unsupported(
617 "AV1 decode_stream",
618 "a show_existing_frame header naming an empty reference slot",
619 )
620 };
621 if threads > 1 {
622 // lane-thread3: the named slot may still be decoding on a
623 // worker, and the copy into the slots this header refreshes
624 // is then just the promise -- no value needed. The OUTPUT
625 // does need the picture, so it is produced on a worker too:
626 // waiting for it here would stall the parsing thread, and a
627 // stalled parser dispatches nothing (measured before this
628 // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of
629 // 23.3 s at 4K, spent in this one wait). The wait still
630 // points at an earlier coded frame, so the argument in
631 // [`SlotPromise`] is unchanged.
632 let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?;
633 for i in 0..NUM_REF_FRAMES {
634 if header.refresh_frame_flags & (1 << i) != 0 {
635 slot_promises[i] = Some(promise.clone());
636 slot_owner[i] = slot_owner[slot];
637 }
638 }
639 let cap_t0 = crate::timeline::now();
640 let capped = in_flight_shows >= in_flight_cap;
641 while in_flight_shows >= in_flight_cap {
642 collect_one(
643 &rx,
644 &mut in_flight_decodes,
645 &mut in_flight_shows,
646 &mut reorder,
647 &mut sink,
648 )?;
649 }
650 if capped {
651 crate::timeline::cap_wait("show", cap_t0, crate::timeline::now());
652 }
653 let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
654 emit_seq += 1;
655 pictures_shown += 1;
656 let grain = header.film_grain;
657 let seq = SeqFlags::read(&parser);
658 let tx = tx.clone();
659 jobs.submit(move || {
660 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
661 let value = promise.wait()?;
662 let shown_picture = value.pixels.wait()?;
663 let output = if grain.apply_grain && !no_grain() {
664 std::sync::Arc::new(crate::film_grain::apply_grain(
665 &shown_picture,
666 &grain,
667 seq.mc_identity,
668 u32::from(seq.bit_depth),
669 &crate::decode::FrameCtx::new(),
670 ))
671 } else {
672 std::sync::Arc::clone(&shown_picture)
673 };
674 Ok((output, decode_idx, true))
675 }))
676 .unwrap_or_else(|_| {
677 Err(Error::corrupt(
678 "AV1 decode_stream: a worker thread panicked on a show_existing_frame output",
679 ))
680 });
681 let _ = tx.send((job_seq, false, reply));
682 });
683 in_flight_shows += 1;
684 while let Ok((seq, decode_job, result)) = rx.try_recv() {
685 if decode_job {
686 in_flight_decodes -= 1;
687 } else {
688 in_flight_shows -= 1;
689 }
690 let (picture, decode_idx, shown) = result?;
691 reorder.push(seq, picture, decode_idx, shown);
692 reorder.drain(&mut sink)?;
693 }
694 continue;
695 }
696 let picture = {
697 let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?;
698 for i in 0..NUM_REF_FRAMES {
699 if header.refresh_frame_flags & (1 << i) != 0 {
700 cdf_slots[i] = cdf_slots[slot].clone();
701 ref_slots[i] = Some(picture.clone());
702 motion_field_slots[i] = motion_field_slots[slot].clone();
703 seg_map_slots[i] = seg_map_slots[slot].clone();
704 order_hint_slots[i] = order_hint_slots[slot];
705 }
706 }
707 picture
708 };
709 let output = if header.film_grain.apply_grain && !no_grain() {
710 // lane-hbd10 r1: grain synthesis is bit-depth generic
711 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
712 let bit_depth = parser
713 .sequence_header()
714 .map_or(8, |seq| seq.color_config.bit_depth);
715 let mc_identity = parser
716 .sequence_header()
717 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
718 std::sync::Arc::new(crate::film_grain::apply_grain(
719 &picture,
720 &header.film_grain,
721 mc_identity,
722 bit_depth as u32, fctx,
723 ))
724 } else {
725 picture
726 };
727 reorder.push(emit_seq, output, pictures_decoded, true);
728 emit_seq += 1;
729 reorder.drain(&mut sink)?;
730 pictures_shown += 1;
731 continue;
732 }
733 // `tiles_base_offset` is added to every `Tile::offset` below to reach
734 // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to
735 // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s
736 // may span several different OBUs (each at a different offset in
737 // `data`), so those tiles are normalised to an absolute offset the
738 // moment they are appended to `pending_tiles`, and `tiles_base_offset`
739 // is 0 for that case.
740 let (header, tiles, tiles_base_offset): (Box<FrameHeader>, Vec<Tile>, usize) =
741 match obu.kind {
742 ObuKind::Frame(header, tiles) => (header, tiles, obu_offset),
743 ObuKind::TileGroup(new_tiles) => {
744 let header = pending_header.clone().ok_or_else(|| {
745 Error::corrupt(
746 "AV1 decode_stream: a tile group OBU with no preceding frame header",
747 )
748 })?;
749 let expected = header.tile_info.cols * header.tile_info.rows;
750 pending_tiles.extend(new_tiles.into_iter().map(|mut t| {
751 t.offset += obu_offset;
752 t
753 }));
754 if (pending_tiles.len() as u32) < expected {
755 continue;
756 }
757 pending_header = None;
758 (header, std::mem::take(&mut pending_tiles), 0)
759 }
760 _ => continue,
761 };
762 // Every tile is decoded below through `tile_bufs`; this only rejects a
763 // frame OBU that carries no tile group at all.
764 if tiles.is_empty() {
765 return Err(Error::unsupported(
766 "AV1 decode_stream",
767 "a frame OBU with no tile group",
768 ));
769 }
770 // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
771 // block of each 64x64) only reads a literal `cdef_idx` when
772 // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a
773 // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is
774 // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into
775 // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so
776 // a `cdef_bits > 0` stream no longer needs this refusal.
777 // Both frame types now read their transform size under
778 // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads
779 // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's
780 // `decode_inter_block`/`decode_inter_block8` read the recursive
781 // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the
782 // blanket inter-frame refusal that used to stand here is gone. What
783 // remains refused is named at its own site in `read_block_tx_size`.
784 // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
785 // libaom decodemv.c): three more per-block/per-SB symbols this crate
786 // never reads at all, each gated by a header field this decoder
787 // otherwise accepts uncomplaining -- the same silent-desync shape
788 // `use_filter_intra` was. `allow_screen_content_tools` gates both
789 // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
790 // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
791 // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
792 // before desyncing rather than silently miscode, the same pattern as
793 // the CDEF/TxMode::Select refusals above.
794 // lane-screen r2: key frames consume (not reconstruct) palette/
795 // intrabc syntax via read_intra_mode, and decode_inter_block/
796 // decode_inter_block8's own intra-sub-block branches now consume
797 // palette the same way (libaom's read_intra_block_mode_info has no
798 // intrabc call at all -- that symbol is intra-frame-only). A
799 // genuine palette/intrabc use still refuses by name deeper in the
800 // block readers, so no whole-frame refusal is needed here anymore.
801 // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX)
802 // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF ->
803 // Neighbours::delta_lf_grid -> lf_level) are now read and applied;
804 // no whole-frame refusal needed here anymore.
805 //
806 // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an
807 // earlier round), `BIT_DEPTH` is wired from this frame's own sequence
808 // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10`
809 // stream decodes pixel-exact against ffmpeg's own decode of the same
810 // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The
811 // blanket refusal that used to be here is gone; `film_grain.rs` and
812 // `superres.rs` still refuse narrowly by name (their own hardcoded
813 // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
814 // will show up as a real pixel mismatch, not a silent truncation --
815 // the whole reason the widen (and this wiring) happened.
816 // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9,
817 // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the
818 // per-segment quantizer (spec 7.12.2) and loop-filter level
819 // (spec 7.14.4). The three features that instead REWRITE a block's
820 // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the
821 // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress
822 // symbols `decode_inter_block` unconditionally reads) -- have no
823 // reader on the inter path, so they still refuse by name rather than
824 // desyncing. aomenc's `--aq-mode` segmentation only ever sets
825 // `SEG_LVL_ALT_Q`.
826 let tile_bufs: Vec<&[u8]> = tiles
827 .iter()
828 .map(|t| {
829 data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size)
830 .ok_or(Error::NeedMore)
831 })
832 .collect::<Result<_>>()?;
833 let seq = SeqFlags::read(&parser);
834 // lane-thread3: at `threads > 1` every coded frame that is not a key
835 // frame is decoded on a worker -- frames that refresh reference slots
836 // included, which on a pyramid stream is nearly all of them. Its
837 // inputs are taken as promises and its output is published as one,
838 // installed into the slots it refreshes HERE, on the parsing thread,
839 // in decode order, so the next frame's dependencies are known without
840 // waiting for this one to finish (see [`SlotPromise`] for the
841 // deadlock argument). A key frame stays inline: it resets the whole
842 // bank and reads nothing, so there is nothing to gain.
843 if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
844 let cap_t0 = crate::timeline::now();
845 let capped = in_flight_decodes >= in_flight_cap;
846 while in_flight_decodes >= in_flight_cap {
847 collect_one(
848 &rx,
849 &mut in_flight_decodes,
850 &mut in_flight_shows,
851 &mut reorder,
852 &mut sink,
853 )?;
854 }
855 if capped {
856 crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now());
857 }
858 // Exactly the slots this frame reads: `ref_frame_idx` names its
859 // references, and its `primary_ref_frame` CDFs/segment map, its
860 // reference order hints and every field `setup_motion_field`
861 // projects all come from those same slots. Nothing else is
862 // waited on.
863 let mut deps: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
864 std::array::from_fn(|_| None);
865 for i in 0..7 {
866 let slot = header.ref_frame_idx[i] as usize;
867 deps[slot] = slot_promises[slot].clone();
868 }
869 let dep_owner = slot_owner;
870 let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending);
871 if let Some(promise) = &produces {
872 for i in 0..NUM_REF_FRAMES {
873 if header.refresh_frame_flags & (1 << i) != 0 {
874 slot_promises[i] = Some(promise.clone());
875 slot_owner[i] = pictures_decoded;
876 }
877 }
878 }
879 let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);
880 emit_seq += 1;
881 pictures_decoded += 1;
882 let shown = header.show_frame;
883 if shown {
884 pictures_shown += 1;
885 }
886 let tx = tx.clone();
887 let dump = final_dump.clone();
888 crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);
889 jobs.submit(move || {
890 let promise = produces;
891 // lane-twostage: stage 2 -- this frame's filtered pixels. Its
892 // consumers hold this promise from the moment stage 1 (CDFs,
893 // segment map, motion field, size) is published at the tile
894 // boundary, and wait on it at their first prediction.
895 let pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>> =
896 SlotPromise::pending();
897 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
898 crate::timeline::start(decode_idx);
899 // The wait happens HERE, off the parsing thread, and only
900 // for this frame's own references.
901 let mut resolved: [Option<std::sync::Arc<SlotValue>>; NUM_REF_FRAMES] =
902 std::array::from_fn(|_| None);
903 for (slot, dep) in deps.iter().enumerate() {
904 if let Some(dep) = dep {
905 let t0 = crate::timeline::now();
906 resolved[slot] = Some(dep.wait()?);
907 crate::timeline::ref_wait(
908 decode_idx,
909 slot,
910 dep_owner[slot],
911 crate::timeline::now().saturating_sub(t0),
912 );
913 }
914 }
915 crate::timeline::refs_ready();
916 // Fresh per-thread state: every field this path reads is
917 // written from this frame's own header before it is read.
918 let fctx = crate::decode::FrameCtx::new();
919 // lane-twostage: the pictures behind this frame's own
920 // references, waited for at the first `ref_planes` call
921 // inside the tile decode rather than here.
922 let ref_metas: [Option<std::sync::Arc<SlotValue>>; 8] =
923 std::array::from_fn(|i| {
924 if i == 0 {
925 None
926 } else {
927 resolved
928 .get(header.ref_frame_idx[i - 1] as usize)
929 .cloned()
930 .flatten()
931 }
932 });
933 let pix_cell: std::sync::OnceLock<
934 [Option<std::sync::Arc<Picture>>; 8],
935 > = std::sync::OnceLock::new();
936 let wait_pixels = || -> Result<[Option<&Picture>; 8]> {
937 if pix_cell.get().is_none() {
938 let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
939 Default::default();
940 for (i, meta) in ref_metas.iter().enumerate() {
941 if let Some(meta) = meta {
942 let slot = header.ref_frame_idx[i - 1] as usize;
943 let t0 = crate::timeline::now();
944 pics[i] = Some(meta.pixels.wait()?);
945 crate::timeline::ref_wait(
946 decode_idx,
947 slot,
948 dep_owner[slot],
949 crate::timeline::now().saturating_sub(t0),
950 );
951 }
952 }
953 let _ = pix_cell.set(pics);
954 }
955 let pics = pix_cell.get().expect("the pictures were just set");
956 Ok(std::array::from_fn(|i| pics[i].as_deref()))
957 };
958 let refpix = decode::RefPix::lazy(
959 std::array::from_fn(|i| {
960 ref_metas[i].as_ref().map(|m| (m.width, m.height))
961 }),
962 &wait_pixels,
963 );
964 // Stage 1: published at this frame's tile boundary, before
965 // its filters run (`take_segment_ids` copies the map, so
966 // the filters that read it are unaffected).
967 let stage1 = |cdfs: Cdfs,
968 motion_field: crate::motion_field::MotionField,
969 width: usize,
970 height: usize| {
971 if let Some(promise) = &promise {
972 promise.fulfil(std::sync::Arc::new(SlotValue {
973 pixels: pixels.clone(),
974 width,
975 height,
976 cdfs,
977 motion_field,
978 seg_map: decode::take_segment_ids(&fctx),
979 order_hint: header.order_hint,
980 }));
981 crate::timeline::slot_fulfil();
982 }
983 };
984 // spec 7.9's `av1_setup_motion_field` runs inside
985 // `RefSnapshot::take`, i.e. here, after those waits --
986 // it reads the referenced slots' saved motion fields.
987 let motion_fields =
988 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field));
989 let snap = RefSnapshot::take(
990 &header,
991 seq,
992 &refpix,
993 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),
994 std::array::from_fn(|i| {
995 resolved[i].as_ref().map(|v| v.seg_map.as_slice())
996 }),
997 &motion_fields,
998 std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)),
999 );
1000 let out = decode_frame(
1001 &fctx,
1002 &header,
1003 &tile_bufs,
1004 seq,
1005 snap,
1006 decode_idx,
1007 shown_idx,
1008 dump.as_deref(),
1009 // lane-twostage publishes a frame's meta at its tile
1010 // boundary instead of after its filters, so a consumer
1011 // parses over its producer's filter tail. It is ON by
1012 // default since lane-sub8group: with every reference
1013 // pixel read deferred to the recon workers, the
1014 // consumer parses its WHOLE tile before it needs a
1015 // pixel, and the 4K critical chain shortens by 11-14%
1016 // in three interleaved pairs (14450/10594/14407 ms off
1017 // vs 12790/9207/12463 ms on) where it moved 3-7%
1018 // before. `EC_AV1_TWO_STAGE=0` turns it back off.
1019 (crate::envflags::var("EC_AV1_TWO_STAGE").as_deref() != Ok("0"))
1020 .then_some(&stage1 as &dyn Fn(_, _, _, _)),
1021 )?;
1022 // Publish before grain synthesis: every frame waiting on
1023 // this slot can start the moment the clean picture exists
1024 // (spec 7.18.3.1 -- the bank never stores grain).
1025 let picture = std::sync::Arc::new(out.picture);
1026 pixels.fulfil(picture.clone());
1027 if let Some(promise) = &promise {
1028 // Only a frame whose stage-1 sink never fired (a
1029 // superres frame) still has meta to publish here.
1030 promise.fulfil_if_pending(|| {
1031 std::sync::Arc::new(SlotValue {
1032 pixels: pixels.clone(),
1033 width: picture.width,
1034 height: picture.height,
1035 cdfs: out.stored_cdfs,
1036 motion_field: out.motion_field.expect(
1037 "a frame that published no stage 1 carries its motion field back",
1038 ),
1039 seg_map: out.seg_map,
1040 order_hint: header.order_hint,
1041 })
1042 });
1043 crate::timeline::slot_fulfil();
1044 }
1045 // Grain is synthesised for OUTPUT only: a hidden frame is
1046 // reported to the sink clean, exactly as the inline path
1047 // below reports it (spec 7.18.3.1).
1048 let output = if shown && header.film_grain.apply_grain && !no_grain() {
1049 std::sync::Arc::new(crate::film_grain::apply_grain(
1050 &picture,
1051 &header.film_grain,
1052 seq.mc_identity,
1053 u32::from(seq.bit_depth),
1054 &fctx,
1055 ))
1056 } else {
1057 picture
1058 };
1059 crate::timeline::grain_done();
1060 Ok((output, decode_idx, shown))
1061 }))
1062 .unwrap_or_else(|_| {
1063 Err(Error::corrupt(
1064 "AV1 decode_stream: a worker thread panicked decoding a frame",
1065 ))
1066 });
1067 // A frame nobody can decode must not leave its consumers
1068 // waiting for a slot that will never be filled.
1069 if reply.is_err() {
1070 // Neither stage may leave a consumer waiting for a value
1071 // that will never come.
1072 if let Some(promise) = &promise {
1073 promise.fail();
1074 }
1075 pixels.fail();
1076 }
1077 let _ = tx.send((job_seq, true, reply));
1078 });
1079 in_flight_decodes += 1;
1080 FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1081 // Anything that finished while this frame was being set up.
1082 while let Ok((seq, decode_job, result)) = rx.try_recv() {
1083 if decode_job {
1084 in_flight_decodes -= 1;
1085 } else {
1086 in_flight_shows -= 1;
1087 }
1088 let (picture, decode_idx, shown) = result?;
1089 reorder.push(seq, picture, decode_idx, shown);
1090 reorder.drain(&mut sink)?;
1091 }
1092 continue;
1093 }
1094 // lane-twostage: the inline path's references are decoded already,
1095 // so its handle never waits.
1096 let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| {
1097 if i == 0 {
1098 None
1099 } else {
1100 ref_slots
1101 .get(header.ref_frame_idx[i - 1] as usize)
1102 .and_then(|p| p.as_deref())
1103 }
1104 }));
1105 let snap = RefSnapshot::take(
1106 &header,
1107 seq,
1108 &inline_refpix,
1109 std::array::from_fn(|i| cdf_slots[i].as_ref()),
1110 std::array::from_fn(|i| seg_map_slots[i].as_deref()),
1111 &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
1112 order_hint_slots,
1113 );
1114 let bit_depth = seq.bit_depth;
1115 let FrameOutput {
1116 picture,
1117 stored_cdfs,
1118 motion_field,
1119 seg_map: decoded_seg_map,
1120 } = decode_frame(
1121 fctx,
1122 &header,
1123 &tile_bufs,
1124 seq,
1125 snap,
1126 pictures_decoded,
1127 pictures_shown,
1128 final_dump.as_deref(),
1129 None,
1130 )?;
1131 let motion_field =
1132 motion_field.expect("the inline path passes no stage-1 sink");
1133 pictures_decoded += 1;
1134 // lane-pool1: one allocation, then every slot store and the output
1135 // itself are refcount bumps instead of plane copies.
1136 let picture = std::sync::Arc::new(picture);
1137 if threads > 1 {
1138 // lane-thread3: only a key frame reaches this inline path at
1139 // `threads > 1`, and the bank it fills is the promise array --
1140 // already resolved, since the picture exists right here.
1141 if header.refresh_frame_flags != 0 {
1142 let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
1143 pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)),
1144 width: picture.width,
1145 height: picture.height,
1146 cdfs: stored_cdfs,
1147 motion_field,
1148 seg_map: decoded_seg_map,
1149 order_hint: header.order_hint,
1150 }));
1151 for i in 0..NUM_REF_FRAMES {
1152 if header.refresh_frame_flags & (1 << i) != 0 {
1153 slot_promises[i] = Some(promise.clone());
1154 slot_owner[i] = pictures_decoded - 1;
1155 }
1156 }
1157 }
1158 } else {
1159 for i in 0..NUM_REF_FRAMES {
1160 if header.refresh_frame_flags & (1 << i) != 0 {
1161 cdf_slots[i] = Some(stored_cdfs.clone());
1162 // Spec 7.18.3.1: synthesized grain is never stored for
1163 // later prediction -- the reference bank always keeps the
1164 // clean, pre-grain decode, even though the frame pushed
1165 // onto the caller's output below carries the grained
1166 // picture.
1167 ref_slots[i] = Some(std::sync::Arc::clone(&picture));
1168 motion_field_slots[i] = Some(motion_field.clone());
1169 seg_map_slots[i] = Some(decoded_seg_map.clone());
1170 order_hint_slots[i] = header.order_hint;
1171 }
1172 }
1173 }
1174 // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a
1175 // KEY frame coded with `show_frame == 0`, output later by a
1176 // `show_existing_frame` header -- counted only once its tiles have
1177 // decoded, so the gate's assert covers decoded-and-compared frames.
1178 if header.frame_type == FrameType::Key && !header.show_frame {
1179 decode::note_fwd_kf();
1180 }
1181 if header.show_frame {
1182 let output = if header.film_grain.apply_grain && !no_grain() {
1183 let mc_identity = seq.mc_identity;
1184 std::sync::Arc::new(crate::film_grain::apply_grain(
1185 &picture,
1186 &header.film_grain,
1187 mc_identity,
1188 bit_depth as u32, fctx,
1189 ))
1190 } else {
1191 picture
1192 };
1193 reorder.push(emit_seq, output, pictures_decoded - 1, true);
1194 emit_seq += 1;
1195 reorder.drain(&mut sink)?;
1196 pictures_shown += 1;
1197 } else {
1198 // Hidden (alt-ref/forward-key) frames never reach
1199 // `decode_stream`'s output, but a decode-order consumer -- the
1200 // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs
1201 // them, so they are reported too, with `shown == false`.
1202 reorder.push(emit_seq, picture, pictures_decoded - 1, false);
1203 emit_seq += 1;
1204 reorder.drain(&mut sink)?;
1205 }
1206 }
1207 while in_flight_decodes + in_flight_shows > 0 {
1208 collect_one(
1209 &rx,
1210 &mut in_flight_decodes,
1211 &mut in_flight_shows,
1212 &mut reorder,
1213 &mut sink,
1214 )?;
1215 }
1216 debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");
1217 crate::timeline::dump();
1218 Ok(())
1219}
1220
1221
1222
1223/// lane-thread2: the sequence-header bits a single frame's decode needs,
1224/// read once on the parsing thread so that [`decode_frame`] never touches the
1225/// [`Av1Parser`] (a worker thread has no access to it).
1226#[derive(Clone, Copy)]
1227pub(crate) struct SeqFlags {
1228 pub(crate) enable_filter_intra: bool,
1229 pub(crate) enable_dual_filter: bool,
1230 pub(crate) enable_edge_filter: bool,
1231 pub(crate) enable_masked_compound: bool,
1232 pub(crate) enable_jnt_comp: bool,
1233 pub(crate) enable_interintra_compound: bool,
1234 pub(crate) use_sb128: bool,
1235 pub(crate) bit_depth: u8,
1236 pub(crate) order_hint_bits: u32,
1237 pub(crate) mc_identity: bool,
1238}
1239
1240impl SeqFlags {
1241 fn read(parser: &Av1Parser) -> Self {
1242 let seq = parser.sequence_header();
1243 Self {
1244 enable_filter_intra: seq.is_some_and(|s| s.enable_filter_intra),
1245 enable_dual_filter: seq.is_some_and(|s| s.enable_dual_filter),
1246 enable_edge_filter: seq.is_some_and(|s| s.enable_intra_edge_filter),
1247 enable_masked_compound: seq.is_some_and(|s| s.enable_masked_compound),
1248 enable_jnt_comp: seq.is_some_and(|s| s.enable_jnt_comp),
1249 enable_interintra_compound: seq.is_some_and(|s| s.enable_interintra_compound),
1250 use_sb128: seq.is_some_and(|s| s.use_128x128_superblock),
1251 bit_depth: seq.map_or(8, |s| s.color_config.bit_depth),
1252 order_hint_bits: seq.map_or(0, |s| s.order_hint_bits),
1253 mc_identity: seq.is_some_and(|s| s.color_config.matrix_coefficients == 0),
1254 }
1255 }
1256}
1257
1258/// lane-thread2: everything one frame's decode reads out of the cross-frame
1259/// banks `decode_stream_with` owns -- taken on the parsing thread, before any
1260/// later frame can overwrite a slot, so a frame can be decoded anywhere.
1261pub(crate) struct RefSnapshot<'a> {
1262 /// lane-twostage: this frame's references, indexed by `ref_frame`
1263 /// (`LAST_FRAME` = 1) -- sizes now, pixels at the first prediction.
1264 pub(crate) refpix: &'a decode::RefPix<'a>,
1265 /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame
1266 /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the
1267 /// second case is the refusal [`decode_frame`] raises where it always
1268 /// did, so the error order over a malformed stream is unchanged).
1269 pub(crate) primary_cdfs: Option<Cdfs>,
1270 /// Spec `load_previous_segment_ids`, from the same slot.
1271 pub(crate) prev_seg_map: Option<Vec<u8>>,
1272 /// Spec 7.9's projection, already run against `motion_field_slots`.
1273 pub(crate) tpl_field: Option<crate::motion_field::TplField>,
1274 /// `order_hint_slots[ref_frame_idx[i]]` for `LAST_FRAME + i`.
1275 pub(crate) ref_order_hints: [u32; 7],
1276}
1277
1278impl<'a> RefSnapshot<'a> {
1279 /// Reads the banks for `header`. Every slot is passed in by reference so
1280 /// that the single-threaded path can borrow the DPB in place while a
1281 /// worker borrows the resolved [`SlotPromise`] values it waited on --
1282 /// spec 7.9's `setup_motion_field` therefore runs on the DECODING thread
1283 /// (lane-thread3), after those waits.
1284 fn take(
1285 header: &FrameHeader,
1286 seq: SeqFlags,
1287 refpix: &'a decode::RefPix<'a>,
1288 cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],
1289 seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],
1290 motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],
1291 order_hint_slots: [u32; NUM_REF_FRAMES],
1292 ) -> Self {
1293 let primary = (header.primary_ref_frame != PRIMARY_REF_NONE)
1294 .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize);
1295 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1296 // this frame's header asks for it, and never for a key frame (which
1297 // codes no inter block at all).
1298 let tpl_field = (header.frame_type != FrameType::Key && header.use_ref_frame_mvs).then(
1299 || {
1300 crate::motion_field::setup_motion_field(
1301 motion_field_slots,
1302 header.ref_frame_idx,
1303 header.order_hint,
1304 seq.order_hint_bits,
1305 header.mi_rows as usize,
1306 header.mi_cols as usize,
1307 )
1308 },
1309 );
1310 if std::env::var_os("EC_TPL").is_some() {
1311 eprintln!(
1312 "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}",
1313 header.order_hint,
1314 header.use_ref_frame_mvs,
1315 tpl_field
1316 .as_ref()
1317 .map_or(0, crate::motion_field::TplField::filled_cells)
1318 );
1319 }
1320 Self {
1321 refpix,
1322 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
1323 prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),
1324 tpl_field,
1325 ref_order_hints: std::array::from_fn(|i| {
1326 order_hint_slots[header.ref_frame_idx[i] as usize]
1327 }),
1328 }
1329 }
1330}
1331
1332/// lane-thread2: what one decoded frame contributes back to the stream --
1333/// its picture (clean, pre-grain: spec 7.18.3.1) plus the three pieces a
1334/// `refresh_frame_flags` bit stores into a reference slot.
1335pub(crate) struct FrameOutput {
1336 pub(crate) picture: Picture,
1337 pub(crate) stored_cdfs: Cdfs,
1338 /// lane-twostage: `None` when this frame handed its motion field to the
1339 /// stage-1 sink at its tile boundary instead of carrying it back here.
1340 pub(crate) motion_field: Option<crate::motion_field::MotionField>,
1341 pub(crate) seg_map: Vec<u8>,
1342}
1343
1344/// Spec 7.20's own `save_cdfs`: what a frame's `refresh_frame_flags` slots
1345/// keep -- the frame's INITIAL table when `disable_frame_end_update_cdf`,
1346/// otherwise the adapted end-of-tile table with every symbol counter zeroed
1347/// (libaom `av1_reset_cdf_symbol_counters`). lane-twostage: shared with the
1348/// stage-1 publish, which hands a consumer the same table it always got.
1349fn stored_cdfs_for(header: &FrameHeader, end_cdfs: Cdfs, started_from: Option<Cdfs>) -> Cdfs {
1350 if header.disable_frame_end_update_cdf {
1351 started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
1352 } else {
1353 let mut end_cdfs = end_cdfs;
1354 end_cdfs.reset_counts();
1355 end_cdfs
1356 }
1357}
1358
1359/// lane-thread2: one coded frame, decoded from its header, its tile payload
1360/// and a snapshot of the reference banks -- and from nothing else. Lifted
1361/// verbatim out of [`decode_stream_with`]'s loop so that the same code can
1362/// run on the parsing thread (a frame that refreshes a reference slot) or on
1363/// a worker (a leaf frame, see `decode_stream_with_threads`).
1364///
1365/// `fctx` is the DECODING thread's context: a worker uses a fresh one, which
1366/// is sound because every field this path reads is written by this function
1367/// (or by the tile decoders it calls) before it is read -- see the
1368/// `a_worker_context_starts_where_the_stream_context_would` gate.
1369///
1370/// # Errors
1371/// As [`decode_stream_with`], for this one frame.
1372#[allow(clippy::too_many_arguments)]
1373fn decode_frame(
1374 fctx: &crate::decode::FrameCtx,
1375 header: &FrameHeader,
1376 tile_bufs: &[&[u8]],
1377 seq: SeqFlags,
1378 snap: RefSnapshot<'_>,
1379 decode_idx: usize,
1380 shown_idx: usize,
1381 final_dump: Option<&str>,
1382 // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`.
1383 stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
1384) -> Result<FrameOutput> {
1385 if header.segmentation.enabled {
1386 for segment in 0..MAX_SEGMENTS {
1387 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
1388 if header.segmentation.feature_enabled[segment][feature] {
1389 return Err(Error::unsupported(
1390 "AV1 decode_stream",
1391 "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)",
1392 ));
1393 }
1394 }
1395 }
1396 }
1397 // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
1398 // primary reference frame's slot, and is all-zero without one.
1399 decode::set_segmentation(
1400 header.segmentation,
1401 header.mi_rows as usize,
1402 header.mi_cols as usize,
1403 snap.prev_seg_map.as_deref(), fctx,
1404 );
1405 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
1406 // symbol (spec 7.16's upscaling is a pixel-domain post-process
1407 // libaom's `decodeframe.c` runs between CDEF and loop restoration,
1408 // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile
1409 // reads stay bit-exact in sync and `crate::superres::upscale_picture`
1410 // (below, after decode) makes its `Picture` the spec-correct
1411 // `upscaled_width` instead of silently staying at `frame_width`.
1412 // lane-superres r10: an INTER frame under `use_superres` no longer
1413 // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3)
1414 // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/
1415 // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes
1416 // at the downscaled `frame_width` and upscales its own output the
1417 // same way the key-frame branch above does (see the inter branch
1418 // below). The combinations `predict_scaled` does not cover
1419 // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8
1420 // leaf) still refuse by name, deep in `decode.rs`, rather than
1421 // silently mispredicting -- see `refusal_inventory.rs`.
1422 // Loop restoration carries per-restoration-unit symbols in the tile
1423 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
1424 // superblock walk) -- lane-lr r2 ported the reader
1425 // (`crate::restoration`), r3 moved this refusal check to AFTER the
1426 // tile decode call below (was here, before it, in r2 -- meaning
1427 // `read_lr` was NEVER actually reached through `decode_stream`, the
1428 // gap the r3 gate caught live: 40/40 attempts hit this refusal with
1429 // zero `read_lr_unit` hits). Checking post-decode instead proves the
1430 // superblock walk actually survived `read_lr` (no desync) before
1431 // refusing on the true remaining gap: decoded Wiener/SGR filters are
1432 // stored per unit but never applied to pixels.
1433 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
1434 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
1435 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
1436 // zero vector only under `GmType == IDENTITY` -- any other warp
1437 // model needs the full affine/translation MV derivation this
1438 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
1439 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
1440 // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
1441 // to every one of the 7 single-reference slots `decode_inter_block`
1442 // can now select.
1443 //
1444 // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal
1445 // exposed a real pixel mismatch --
1446 // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact
1447 // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20
1448 // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring
1449 // is not yet provably correct end to end; keeping the refusal
1450 // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and
1451 // root-caused rather than shipping a wrong decode.
1452 //
1453 // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not
1454 // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac
1455 // RANGE at the first divergent block (mi=(8,0), frame 1) matches
1456 // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides),
1457 // and this decoder's own `gm_get_motion_vector` for that block
1458 // (ROTZOOM, seed 43's own header) computes the spec-correct
1459 // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`,
1460 // which found and fixed a real `- 1` omission in `warp.rs` --
1461 // harmless for THIS block's rounding but a genuine spec bug fixed
1462 // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a
1463 // `global_warp_allowed` branch (`warp_types.global_warp_allowed =
1464 // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts
1465 // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8)
1466 // with the FULL per-pixel affine global-motion warp, independent
1467 // of `motion_mode` -- this decoder only ever builds a warp
1468 // prediction for local `WARPED_CAUSAL` motion mode and falls back
1469 // to plain translational MC with the block-centre mv for every
1470 // other GLOBALMV block, which is only a centre-point approximation
1471 // of the true per-pixel warp. That is the entire remaining gap.
1472 // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into
1473 // `crate::warp::global_warp_params` for every single-ref
1474 // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s
1475 // `global_warp_allowed` branch -- ROTZOOM is pin-verified
1476 // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already
1477 // worked (`gm_get_motion_vector`'s translation-only mv, no warp
1478 // needed). AFFINE is untested this round (no aomenc fixture in the
1479 // wedge gate reached a 6-parameter model) -- keep refusing it by
1480 // name rather than shipping an unverified decode.
1481 // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom
1482 // can never write a 6-parameter model -- its encoder-side search is
1483 // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`,
1484 // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) --
1485 // which is why four rounds of `--enable-global-motion=1` recipes
1486 // never reached the case. `scripts/build-aom-affine-oracle.sh` widens
1487 // exactly that search range in a side build, and
1488 // `a_real_affine_global_motion_stream_decodes_pixel_exact` below
1489 // decodes its output pixel-exact against ffmpeg with
1490 // `affine_gm_hits() > 0`, i.e. real blocks predicted through the
1491 // 6-parameter warp. Nothing in the decoder needed changing: the
1492 // header reader already reads params 4/5 with their own subexp refs
1493 // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s
1494 // shear-validity check + `warp_affine` are model-agnostic.
1495 // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two
1496 // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and
1497 // refused the shape by name rather than guess-fix it. r5 localized
1498 // the mismatch to an ordinary NEWMV/GOLDEN block, not the new
1499 // global-warp branch at all -- proving "two active slots" was a
1500 // correlated symptom, not the cause. r6 range-laddered that block
1501 // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after
1502 // mode info -- symbol consumption bit-exact) and found the real
1503 // defect in `mvstack.rs`'s single-reference predictor fallback:
1504 // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real
1505 // neighbour scan left short with this block's OWN global motion
1506 // vector for its ref (`gm_get_motion_vector`), not zero -- invisible
1507 // whenever the live ref's global motion is itself
1508 // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE
1509 // and the querying block's own stack comes up short (frame 14's
1510 // mi=(0,0), the very first block decoded, has no neighbours at
1511 // all). Fixed at the predictor fallback; the refusal above (single
1512 // untested shape: AFFINE on a single-ref frame) stays, but the
1513 // *multi-slot* refusal this comment used to guard is lifted -- the
1514 // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames
1515 // byte-exact with it gone.
1516 // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
1517 // `comp_mode` per block whenever this frame's own `reference_select`
1518 // header bit is set (spec 5.11.25), and refuse by name the blocks
1519 // that pick `COMPOUND_REFERENCE` -- two-reference motion
1520 // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
1521 // is wired at the block level too (forced NEAREST_NEARESTMV compound
1522 // of `skip_mode_frame`, plain average blend), so the old blanket
1523 // `skip_mode_present` refusal is gone.
1524 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
1525 // which tile's end-of-tile adapted CDFs become the frame's own.
1526 // lane-tiles r8: this comment used to claim a `!= 0` refusal existed
1527 // "further down" -- it did not (`decode.rs` reads
1528 // `tile_info.context_update_tile_id` generically at both the
1529 // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites,
1530 // never hardcoded to tile 0); stale documentation, not a real gap.
1531 // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact`
1532 // hard-asserts a live aomenc stream naming tile 1/2/3 decodes
1533 // pixel-exact, so the capability is now proven as well as described
1534 // correctly.
1535 //
1536 // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped,
1537 // not blanket. `decode_key_frame_tile_with_cdfs` and (r6)
1538 // `decode_inter_frame_tile_with_cdfs` both genuinely loop every
1539 // tile, `mvstack.rs`'s `MiGrid` is bounded per tile
1540 // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1`
1541 // origin receives real values at every call site (r6's
1542 // `set_tile_origin` sweep). r7 proved the two remaining
1543 // tile-*column* gaps closed (inter frames, >2 columns with loop
1544 // filtering on). r8 proved tile *rows* the same way: the per-tile
1545 // loop's row math (`tile_num / tile_info.cols`,
1546 // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly
1547 // symmetric with the column path already proven, and
1548 // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact`
1549 // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact.
1550 // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_
1551 // stream` below re-proves it through this entry point. Tile columns
1552 // and tile rows (any count, loop filter on) are no longer capped.
1553 // `Tile::offset` is relative to the buffer `parse_obu` was handed
1554 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
1555 // to `obu_offset`, not to `data` as a whole.
1556 let enable_filter_intra = seq.enable_filter_intra;
1557 let enable_dual_filter = seq.enable_dual_filter;
1558 let enable_edge_filter = seq.enable_edge_filter;
1559 // Inter frames' intra blocks read this through a thread-local that only
1560 // the key-frame tile path used to set; without this call a stream whose
1561 // inter frames are decoded on a thread that previously decoded a
1562 // different sequence would inherit that sequence's bit.
1563 crate::decode::set_enable_edge_filter(enable_edge_filter, fctx);
1564 // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the
1565 // key-frame and the inter tile path read the 128 partition root and
1566 // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and
1567 // libaom's quadrant visit order into the inter loop too). A frame at
1568 // most 64x64 decodes identically either way (its 128 root reads no
1569 // symbol -- neither half is in frame, so SPLIT is inferred), so the
1570 // flag is only armed for frames bigger than one 64x64 superblock.
1571 let use_sb128 = seq.use_sb128;
1572 let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);
1573 crate::decode::set_sb128(sb128_active, fctx);
1574 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
1575 // which every dequant/inverse-transform clamp reads -- set per frame,
1576 // not once per process, for the same cross-sequence-on-one-thread
1577 // reason as `set_enable_edge_filter` above. Defaults to 8 when no
1578 // sequence header has been seen yet, matching every existing fixture.
1579 let bit_depth = seq.bit_depth;
1580 // lane-bd12: the sequence-header parser accepts `twelve_bit`, but every
1581 // rounding shift below is written for 8/10-bit only -- `warp.rs`'s
1582 // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses
1583 // `round_0 + max(bd + FILTER_BITS - round_0 - 14, 0)` (5 at bd 12), the
1584 // MC `round_0`/`round_1` change at 12-bit (libaom convolve.h:83), the
1585 // Wiener rounding bits change, and neither CDEF nor film grain has a
1586 // 12-bit path. Refuse by name rather than decode silently wrong pixels.
1587 if bit_depth == 12 {
1588 return Err(Error::unsupported(
1589 "AV1 decode_stream",
1590 "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)",
1591 ));
1592 }
1593 crate::decode::set_bit_depth(bit_depth, fctx);
1594 // spec 7.16: this frame's superres state, for the filter chain --
1595 // `decode.rs` upscales between CDEF and loop restoration and sizes
1596 // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
1597 // unscaled frame so a later frame never inherits it.
1598 crate::decode::set_superres(
1599 if header.use_superres { header.upscaled_width } else { 0 },
1600 u32::from(header.superres_denom), fctx,
1601 );
1602 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
1603 let enable_masked_compound = seq.enable_masked_compound;
1604 let enable_jnt_comp = seq.enable_jnt_comp;
1605 // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's
1606 // read site doc.
1607 let enable_interintra_compound = seq.enable_interintra_compound;
1608 let interp_fixed = match header.interpolation_filter {
1609 ec_av1_syntax::InterpolationFilter::Switchable => None,
1610 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
1611 };
1612 // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
1613 // from that reference slot's saved CDF state instead of the spec 8.4
1614 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
1615 // builds.
1616 let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
1617 None
1618 } else {
1619 Some(snap.primary_cdfs.clone().ok_or_else(|| {
1620 Error::unsupported(
1621 "AV1 decode_stream",
1622 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
1623 )
1624 })?)
1625 };
1626 let started_from = initial_cdfs.clone();
1627 // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.
1628 decode::set_coeff_trace_frame(decode_idx);
1629 // lane-t900 r9: one line per DECODE-order frame naming the header
1630 // fields a desync cliff is usually keyed on (frame type, base q,
1631 // primary_ref, the 7 ref slots, refresh mask, order hints).
1632 if std::env::var_os("EC_PROBE_HDR").is_some() {
1633 eprintln!(
1634 "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={:?}",
1635 header.frame_type,
1636 header.show_frame,
1637 header.show_existing_frame,
1638 header.quantization.base_q_idx,
1639 header.primary_ref_frame,
1640 header.ref_frame_idx,
1641 header.refresh_frame_flags,
1642 header.order_hint,
1643 header.tile_info.cols,
1644 header.tile_info.rows,
1645 header.tx_mode,
1646 header.interpolation_filter,
1647 header.reduced_tx_set,
1648 header.allow_warped_motion,
1649 header.is_motion_mode_switchable,
1650 header.use_ref_frame_mvs,
1651 header.skip_mode_present,
1652 header.cdef.bits,
1653 header.loop_restoration.frame_restoration_type,
1654 );
1655 }
1656
1657 let order_hint_bits = seq.order_hint_bits;
1658 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
1659 // of the picture sitting in each of its 7 single references' DPB
1660 // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
1661 // (a later frame projects from it) whether or not this frame itself
1662 // reads temporal candidates.
1663 let ref_order_hints = snap.ref_order_hints;
1664
1665 crate::timeline::bind(
1666 decode_idx,
1667 if header.frame_type == FrameType::Key {
1668 'K'
1669 } else if header.show_frame {
1670 'P'
1671 } else {
1672 'A'
1673 },
1674 header.show_frame,
1675 );
1676 crate::timeline::hdr_done();
1677 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
1678 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
1679 &tile_bufs,
1680 &header.tile_info,
1681 header.mi_cols,
1682 header.mi_rows,
1683 header.quantization.base_q_idx,
1684 crate::quant::QuantDeltas {
1685 y_dc: i32::from(header.quantization.delta_q_y_dc),
1686 u_dc: i32::from(header.quantization.delta_q_u_dc),
1687 u_ac: i32::from(header.quantization.delta_q_u_ac),
1688 v_dc: i32::from(header.quantization.delta_q_v_dc),
1689 v_ac: i32::from(header.quantization.delta_q_v_ac),
1690 },
1691 header.frame_width,
1692 header.frame_height,
1693 enable_filter_intra,
1694 enable_edge_filter,
1695 &header.cdef,
1696 &header.loop_filter,
1697 &header.loop_restoration,
1698 initial_cdfs,
1699 header.tx_mode == TxMode::Select,
1700 header.reduced_tx_set,
1701 header.allow_screen_content_tools,
1702 header.allow_intrabc,
1703 header.delta, fctx,
1704 )?;
1705 // A key frame codes no inter blocks -- its own saved motion
1706 // field has no cells set, matching libaom's own "intra frame
1707 // contributes nothing to a later projection" behaviour, but
1708 // still carries `order_hint`/`ref_order_hints` for the distance
1709 // arithmetic a later frame's projection needs.
1710 let motion_field = crate::motion_field::MotionField::new(
1711 header.mi_cols as usize,
1712 header.mi_rows as usize,
1713 header.order_hint,
1714 ref_order_hints,
1715 // `frame_type` for the DPB slot: a key (or intra-only) frame is
1716 // never a projection source, and never spends a `ref_stamp`.
1717 true,
1718 );
1719 (picture, end_cdfs, Some(motion_field))
1720 } else {
1721 let last_slot = header.ref_frame_idx[0] as usize;
1722 let _ = last_slot;
1723 if snap.refpix.dims(1).is_none() {
1724 return Err(Error::unsupported(
1725 "AV1 decode_stream",
1726 "an inter frame with no key frame before it",
1727 ));
1728 }
1729 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
1730 // (spec 7.8/7.20). Any of them having no picture yet is not a
1731 // stream error on its own: `decode_inter_block` only needs a
1732 // given slot when a block actually selects that reference, and
1733 // refuses by name there if the slot is still empty -- widened
1734 // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
1735 // one of the 7 single-reference slots.
1736 // lane-fimv r1: record the header state the fimv gate asserts on
1737 // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
1738 if header.force_integer_mv {
1739 decode::note_force_integer_mv_frame();
1740 }
1741 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1742 // this frame's header actually asks for temporal candidates --
1743 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
1744 // behaviour bit for bit when this is `None` (see its own doc).
1745 // lane-twostage: the stage-1 sink is handed the table a consumer
1746 // would have read out of the slot, not the raw end-of-tile one.
1747 let started_from_stage1 = started_from.clone();
1748 let stage1_adapter = stage1.map(|sink| {
1749 move |end_cdfs: Cdfs,
1750 motion_field: crate::motion_field::MotionField,
1751 width: usize,
1752 height: usize| {
1753 sink(
1754 stored_cdfs_for(header, end_cdfs, started_from_stage1.clone()),
1755 motion_field,
1756 width,
1757 height,
1758 )
1759 }
1760 });
1761 let tpl_field = &snap.tpl_field;
1762 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
1763 &tile_bufs,
1764 &header.tile_info,
1765 header.mi_cols,
1766 header.mi_rows,
1767 header.quantization.base_q_idx,
1768 crate::quant::QuantDeltas {
1769 y_dc: i32::from(header.quantization.delta_q_y_dc),
1770 u_dc: i32::from(header.quantization.delta_q_u_dc),
1771 u_ac: i32::from(header.quantization.delta_q_u_ac),
1772 v_dc: i32::from(header.quantization.delta_q_v_dc),
1773 v_ac: i32::from(header.quantization.delta_q_v_ac),
1774 },
1775 header.frame_width,
1776 header.frame_height,
1777 snap.refpix,
1778 &header.cdef,
1779 &header.loop_filter,
1780 &header.loop_restoration,
1781 initial_cdfs,
1782 header.allow_high_precision_mv,
1783 header.force_integer_mv,
1784 header.ref_frame_sign_bias,
1785 header.global_motion,
1786 interp_fixed,
1787 enable_dual_filter,
1788 order_hint_bits,
1789 header.order_hint,
1790 ref_order_hints,
1791 tpl_field.as_ref(),
1792 header.reference_select,
1793 enable_masked_compound,
1794 enable_jnt_comp,
1795 enable_interintra_compound,
1796 header.skip_mode_present,
1797 header.skip_mode_frame,
1798 header.reduced_tx_set,
1799 header.tx_mode == TxMode::Select,
1800 header.is_motion_mode_switchable,
1801 header.allow_warped_motion,
1802 header.allow_screen_content_tools,
1803 header.delta,
1804 enable_filter_intra,
1805 stage1_adapter
1806 .as_ref()
1807 .map(|f| f as &dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)),
1808 fctx,
1809 )?;
1810 (picture, end_cdfs, motion_field)
1811 };
1812 // lane-lr r4: the Wiener/self-guided pixel filters are wired
1813 // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
1814 // `uses_lr` frames now decode all the way to pixels.
1815 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
1816 // *initial* table into the slots it refreshes, not the adapted
1817 // end-of-tile one.
1818 let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from);
1819 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
1820 use std::io::Write;
1821 if let Ok(mut f) = std::fs::OpenOptions::new()
1822 .create(true)
1823 .append(true)
1824 .open(&path)
1825 {
1826 let _ = writeln!(f, "=== frame idx={} ===", shown_idx);
1827 let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
1828 let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
1829 let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
1830 let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
1831 let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
1832 let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
1833 let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
1834 let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
1835 }
1836 }
1837 // lane-comppin r3: decode-order (not display-order) dump of every
1838 // frame's own post-deblock buffer -- the pre-existing pixel diff
1839 // (`scratch_isolate_pinned_mismatch`) only ever compares *shown*
1840 // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a
1841 // later shown frame is otherwise invisible; diff this byte-for-byte
1842 // against `EC_AV1_POSTFILT_DUMP.fN` from the instrumented aomdec
1843 // build to isolate whether the defect is in a hidden frame's own
1844 // reconstruction or downstream of it.
1845 if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") {
1846 use std::io::Write;
1847 let idx = decode_idx;
1848 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
1849 // lane-hbd r4: debug dump narrows to u8 -- this diagnostic
1850 // predates 10-bit support and is an 8-bit-oracle comparison
1851 // only (aomdec's own dump is 8-bit here too).
1852 let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
1853 let _ = f.write_all(&narrow(&picture.y));
1854 let _ = f.write_all(&narrow(&picture.u));
1855 let _ = f.write_all(&narrow(&picture.v));
1856 }
1857 }
1858 // lane-hidden r1: the frame exactly as it is about to be stored into
1859 // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
1860 // order, hidden (`show_frame == 0`) alt-ref frames included, and
1861 // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
1862 // u8-narrowing diagnostic dumps above. Matches the instrumented
1863 // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
1864 // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
1865 // hidden frame's pixels comparable at all.
1866 if let Some(prefix) = final_dump {
1867 use std::io::Write;
1868 if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{decode_idx}")) {
1869 let mut buf = Vec::new();
1870 for plane in [&picture.y, &picture.u, &picture.v] {
1871 if bit_depth == 8 {
1872 buf.extend(plane.iter().map(|&s| s as u8));
1873 } else {
1874 for &s in plane {
1875 buf.extend_from_slice(&s.to_le_bytes());
1876 }
1877 }
1878 }
1879 let _ = f.write_all(&buf);
1880 }
1881 }
1882 Ok(FrameOutput {
1883 picture,
1884 stored_cdfs,
1885 motion_field,
1886 seg_map: decode::take_segment_ids(fctx),
1887 })
1888}
1889
1890/// lane-intra14 r1: INTRA-coded 1:4 strips decoded on the INTER block path
1891/// (64x16, 16x64, 32x8, 8x32) -- the counters a recipe sweep needs from
1892/// outside the crate.
1893pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) {
1894 (
1895 crate::decode::intra_rect4_strip_in_inter_hits(0),
1896 crate::decode::intra_rect4_strip_in_inter_hits(1),
1897 crate::decode::intra_rect4_strip_in_inter_hits(2),
1898 crate::decode::intra_rect4_strip_in_inter_hits(3),
1899 )
1900}
1901
1902#[cfg(test)]
1903pub(crate) mod tests {
1904 use super::*;
1905 use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
1906
1907 fn test_card(width: usize, height: usize) -> Pic {
1908 let mut picture = Pic::grey(width, height);
1909 for row in 0..height {
1910 for col in 0..width {
1911 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
1912 }
1913 }
1914 for row in 0..height / 2 {
1915 for col in 0..width / 2 {
1916 let i = row * width / 2 + col;
1917 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
1918 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
1919 }
1920 }
1921 picture
1922 }
1923
1924 fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic {
1925 let mut picture = Pic::grey(width, height);
1926 for y in 0..height {
1927 for x in 0..width {
1928 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
1929 let gradient = sx * 200.0 / width as f64;
1930 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
1931 }
1932 }
1933 for y in 0..height / 2 {
1934 for x in 0..width / 2 {
1935 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
1936 let i = y * width / 2 + x;
1937 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
1938 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
1939 }
1940 }
1941 picture
1942 }
1943
1944 /// A stream whose sequence header says `twelve_bit` is refused by name
1945 /// rather than decoded with the 8/10-bit rounding shifts (`warp.rs`'s
1946 /// hard `REDUCE_BITS_HORIZ = 3`, MC/Wiener round bits, ungated CDEF and
1947 /// film grain). Reachability, not a pixel claim: the header is written at
1948 /// `seq_profile = 2` so `twelve_bit` is actually coded, and the frame's
1949 /// tile payload is never reached.
1950 #[test]
1951 fn a_twelve_bit_sequence_header_is_refused_by_name() {
1952 let fctx = &crate::decode::FrameCtx::new();
1953 let picture = test_card(64, 64);
1954 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1955 let mut color = ec_av1_syntax::ColorConfig {
1956 bit_depth: 12,
1957 ..Default::default()
1958 };
1959 color.num_planes = 3;
1960 // Only seq_profile 2 codes the `twelve_bit` bit (spec 5.5.2).
1961 let (mut seq, header) =
1962 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
1963 seq.seq_profile = 2;
1964 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
1965 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
1966
1967 let err = decode_stream(&stream).unwrap_err().to_string();
1968 assert!(
1969 err.contains(
1970 "a bit depth of 12 (this decoder is gated at 8 and 10 only: \
1971 warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)"
1972 ),
1973 "expected the 12-bit refusal, got: {err}"
1974 );
1975 }
1976
1977 /// lane-t900 r25: the refusal "a frame OBU with no tile group" names a
1978 /// shape the parser cannot hand [`decode_stream`].
1979 ///
1980 /// `tiles` reaches that check from exactly two places -- `ObuKind::Frame`'s
1981 /// own vector and the `ObuKind::TileGroup` accumulation -- and both are
1982 /// filled by `ec_av1_syntax`'s `parse_tile_group`, whose only success path
1983 /// pushes one `Tile` per `tile_num` of the INCLUSIVE range
1984 /// `tg_start..=tg_end`. That range is never empty: the single-tile-group
1985 /// case takes `(0, num_tiles - 1)` saturating at 0, and the multi-group
1986 /// case rejects `end < start` as corrupt. So an `OBU_FRAME` either fails to
1987 /// parse or carries at least one tile, however short its payload is --
1988 /// including the empty payload the charter for this round asked to build,
1989 /// which parses into ONE zero-byte tile rather than none.
1990 ///
1991 /// Sweeping a real frame OBU's tile payload from empty upwards asserts both
1992 /// halves: every `Frame` OBU that parses has a tile, and `decode_stream`
1993 /// never reports this refusal for any of them.
1994 #[test]
1995 fn a_frame_obu_that_parses_always_carries_at_least_one_tile() {
1996 let fctx = &crate::decode::FrameCtx::new();
1997 const REFUSAL: &str = "a frame OBU with no tile group";
1998 let picture = test_card(64, 64);
1999 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2000 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2001 let mut frame_obus_parsed = 0;
2002 for len in 0..=encoded.tile.len().min(24) {
2003 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2004 stream.extend_from_slice(
2005 &crate::frame::frame_obu(&seq, &header, &encoded.tile[..len]).unwrap(),
2006 );
2007 let mut parser = Av1Parser::new();
2008 let mut pos = 0usize;
2009 while pos < stream.len() {
2010 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
2011 break;
2012 };
2013 pos += obu.total_size;
2014 if let ObuKind::Frame(_, tiles) = &obu.kind {
2015 frame_obus_parsed += 1;
2016 assert!(
2017 !tiles.is_empty(),
2018 "a {len}-byte tile payload parsed into a frame OBU with no tile group -- \
2019 the refusal {REFUSAL:?} is reachable after all"
2020 );
2021 }
2022 }
2023 if let Err(e) = decode_stream(&stream) {
2024 let e = e.to_string();
2025 assert!(
2026 !e.contains(REFUSAL),
2027 "a {len}-byte tile payload reached {REFUSAL:?}: {e}"
2028 );
2029 }
2030 }
2031 assert!(
2032 frame_obus_parsed >= 2,
2033 "the sweep parsed {frame_obus_parsed} frame OBUs -- it proves nothing about the \
2034 refusal's reachability"
2035 );
2036 }
2037
2038 /// lane-t900 r27, negative gate: a frame whose segmentation enables one of
2039 /// the three MODE-OVERRIDING features -- `SEG_LVL_REF_FRAME` (forces a
2040 /// block's reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both
2041 /// suppress symbols `decode_inter_block` reads unconditionally) -- is
2042 /// refused BY NAME and outputs no picture, rather than desyncing on the
2043 /// first block that would have obeyed the override.
2044 ///
2045 /// Written, not hand-built: `write_segmentation_params` (spec 5.9.14)
2046 /// codes `feature_enabled`/`feature_data` for every segment, so a real
2047 /// key frame carrying the flag is a two-line change to the header the
2048 /// encoder already produced. Swept over all three features and over the
2049 /// first, a middle and the last segment id.
2050 #[test]
2051 fn a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name() {
2052 let fctx = &crate::decode::FrameCtx::new();
2053 const REFUSAL: &str =
2054 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
2055 let picture = test_card(64, 64);
2056 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2057 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2058 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
2059 for segment in [0usize, 3, 7] {
2060 let mut header = key.clone();
2061 header.segmentation.enabled = true;
2062 header.segmentation.update_map = true;
2063 header.segmentation.update_data = true;
2064 header.segmentation.feature_enabled[segment][feature] = true;
2065 header.segmentation.feature_data[segment][feature] = 1;
2066 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2067 stream.extend_from_slice(
2068 &crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap(),
2069 );
2070 let mut shown = 0;
2071 let err = decode_stream_with(&stream, |_, _, _| {
2072 shown += 1;
2073 Ok(())
2074 })
2075 .unwrap_err()
2076 .to_string();
2077 assert!(
2078 err.contains(REFUSAL),
2079 "feature {feature} segment {segment}: expected {REFUSAL:?}, got: {err}"
2080 );
2081 assert_eq!(
2082 shown, 0,
2083 "feature {feature} segment {segment}: a refused frame produced a picture"
2084 );
2085 }
2086 }
2087 }
2088
2089 /// One census attempt: encode `frames` frames of `source` with real
2090 /// aomenc plus `extra` args, decode with THIS decoder, and return the
2091 /// stream's byte length with either the picture count or the refusal (any
2092 /// decode error) it produced. A census is about what the encoder emits,
2093 /// so a refusal is data here, not a failure.
2094 fn census_attempt(
2095 source: &str,
2096 width: usize,
2097 height: usize,
2098 frames: usize,
2099 extra: &[&str],
2100 ) -> (usize, std::result::Result<usize, String>) {
2101 let duration = format!("{}", frames as f64 / 25.0);
2102 let src = format!("{source}=size={width}x{height}:rate=25");
2103 let y4m = Command::new("ffmpeg")
2104 .args([
2105 "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt", "yuv420p",
2106 "-strict", "-1", "-f", "yuv4mpegpipe", "-",
2107 ])
2108 .stdin(Stdio::null())
2109 .stdout(Stdio::piped())
2110 .stderr(Stdio::piped())
2111 .output()
2112 .expect("ffmpeg failed to run");
2113 assert!(y4m.status.success(), "ffmpeg refused the {width}x{height} fixture");
2114 let limit = format!("--limit={frames}");
2115 let mut args: Vec<String> = [
2116 "--codec=av1",
2117 "--passes=1",
2118 "--end-usage=q",
2119 "--threads=1",
2120 "--row-mt=0",
2121 "--kf-max-dist=9999",
2122 "--lag-in-frames=0",
2123 ]
2124 .iter()
2125 .map(|s| (*s).to_owned())
2126 .collect();
2127 args.push(limit);
2128 args.extend(extra.iter().map(|s| (*s).to_owned()));
2129 args.extend(["--obu".to_owned(), "-o".to_owned(), "-".to_owned(), "-".to_owned()]);
2130 let mut child = Command::new(aomenc_path())
2131 .args(&args)
2132 .stdin(Stdio::piped())
2133 .stdout(Stdio::piped())
2134 .stderr(Stdio::piped())
2135 .spawn()
2136 .expect("aomenc failed to start");
2137 child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("write y4m");
2138 let out = child.wait_with_output().expect("aomenc failed to run");
2139 assert!(out.status.success(), "aomenc refused {args:?}: {}", String::from_utf8_lossy(&out.stderr));
2140 let stream = out.stdout;
2141 let result = match decode_stream(&stream) {
2142 Ok(pictures) => Ok(pictures.len()),
2143 Err(e) => Err(e.to_string()),
2144 };
2145 (stream.len(), result)
2146 }
2147
2148 /// lane-t900 r27 CENSUS behind the negative gate above: does a real
2149 /// aomenc ever ENABLE one of the three mode-overriding segmentation
2150 /// features? Measured over the recipes that turn segmentation on --
2151 /// `--aq-mode=1/2/3` (variance, complexity and cyclic-refresh AQ) and
2152 /// `--deltaq-mode=1` -- with the refusal as the instrument: if one of
2153 /// those features appeared, the decode would stop by name.
2154 #[test]
2155 fn a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature() {
2156 if !have_aomenc() {
2157 eprintln!("SKIP a_segmentation_census_over_real_aq_streams: no aomenc");
2158 return;
2159 }
2160 const REFUSAL: &str =
2161 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
2162 let recipes: [(&str, Vec<&str>); 6] = [
2163 ("baseline", vec!["--cpu-used=4", "--cq-level=40"]),
2164 ("aq-mode=1", vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=40"]),
2165 ("aq-mode=2", vec!["--cpu-used=4", "--aq-mode=2", "--cq-level=40"]),
2166 ("aq-mode=3", vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=40"]),
2167 ("aq-mode=3 cq10", vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=10"]),
2168 ("deltaq-mode=1", vec!["--cpu-used=4", "--deltaq-mode=1", "--cq-level=40"]),
2169 ];
2170 // Arrival, not intent (class knob-never-reached-the-tool): a recipe
2171 // whose stream is byte-for-byte the baseline's changed nothing, and a
2172 // census over such arms would be vacuous. Measured r27: only
2173 // `--aq-mode=3` (cyclic refresh) does -- aq-mode 1/2 and deltaq-mode=1
2174 // all reproduce the baseline's 7147 B at this recipe.
2175 let mut baseline_bytes = 0usize;
2176 let mut segment_symbols = 0usize;
2177 let mut refused = 0usize;
2178 let mut decoded = 0usize;
2179 for (name, extra) in &recipes {
2180 let before = crate::decode::segment_id_hits();
2181 let (bytes, result) = census_attempt("mandelbrot", 192, 128, 8, extra);
2182 match result {
2183 Ok(pictures) => {
2184 decoded += 1;
2185 let symbols = crate::decode::segment_id_hits() - before;
2186 segment_symbols += symbols;
2187 if *name == "baseline" {
2188 baseline_bytes = bytes;
2189 }
2190 eprintln!(
2191 "SEGCENSUS {name}: {bytes} B{}, {pictures} pictures, segment_id symbols {symbols}",
2192 if bytes == baseline_bytes && *name != "baseline" {
2193 " (== baseline: the flag changed nothing)"
2194 } else {
2195 ""
2196 }
2197 );
2198 }
2199 Err(e) => {
2200 eprintln!("SEGCENSUS {name}: {bytes} B, refused: {e}");
2201 assert!(
2202 !e.contains(REFUSAL),
2203 "{name}: a real aomenc stream DOES enable a mode-overriding \
2204 segmentation feature -- the refusal is a capability gap, not a \
2205 claim about the encoder: {e}"
2206 );
2207 refused += 1;
2208 }
2209 }
2210 }
2211 eprintln!(
2212 "SEGCENSUS: {} recipes, {decoded} decoded, {refused} refused for other reasons",
2213 recipes.len()
2214 );
2215 assert_eq!(decoded, recipes.len(), "every recipe must decode; {refused} refused");
2216 assert!(
2217 segment_symbols > 0,
2218 "no recipe coded a single segment_id symbol -- segmentation never arrived, so \
2219 this census measures nothing about the three mode-overriding features"
2220 );
2221 }
2222
2223 /// lane-t900 r27, WITNESS half of the proof for "an OBMC neighbour whose
2224 /// switchable interp filter was never recorded" (the structural half is
2225 /// `decode::tests::every_inter_record_publishes_an_obmc_readable_filter`,
2226 /// which shows no INTER cell is ever stamped with the `[3, 3]`
2227 /// sentinel): real OBMC streams whose frames use a SWITCHABLE (and dual)
2228 /// interp filter decode with the refusal firing 0 times while OBMC blends
2229 /// really read the neighbour band -- a decode that never read one would
2230 /// pass just as well and prove nothing (class gate-blind-to-feature).
2231 #[test]
2232 fn a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour() {
2233 if !have_aomenc() {
2234 eprintln!("SKIP a_real_obmc_stream_reads_a_recorded_switchable_filter: no aomenc");
2235 return;
2236 }
2237 // `--cpu-used=0` is load-bearing: at speed 4 aomenc settles on a
2238 // FRAME-level fixed interp filter, every neighbour then legitimately
2239 // carries the sentinel, and the band is never read at all (measured
2240 // r27: 0 reads over two speed-4 streams).
2241 let base = vec![
2242 "--cpu-used=0",
2243 "--enable-obmc=1",
2244 "--enable-dual-filter=1",
2245 "--min-partition-size=8",
2246 "--max-partition-size=16",
2247 "--enable-palette=0",
2248 "--enable-intrabc=0",
2249 ];
2250 let recipes: [(&str, usize, usize, Vec<&str>); 2] = [
2251 ("obmc dual cq40", 192, 128, [vec!["--cq-level=40"], base.clone()].concat()),
2252 ("obmc dual cq20", 192, 128, [vec!["--cq-level=20"], base.clone()].concat()),
2253 ];
2254 let mut reads = 0usize;
2255 let mut decoded = 0usize;
2256 for (name, w, h, extra) in &recipes {
2257 let before = crate::decode::obmc_filter_band_reads();
2258 let obmc_before = crate::decode::obmc_hits();
2259 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 8, extra);
2260 match result {
2261 Ok(pictures) => {
2262 decoded += 1;
2263 let got = crate::decode::obmc_filter_band_reads() - before;
2264 reads += got;
2265 eprintln!(
2266 "OBMCFILT {name}: {bytes} B, {pictures} pictures, {got} band reads, \
2267 {} OBMC blocks",
2268 crate::decode::obmc_hits() - obmc_before
2269 );
2270 }
2271 Err(e) => {
2272 assert!(
2273 !e.contains("an OBMC neighbour whose switchable interp filter was never recorded"),
2274 "{name}: a real OBMC stream reached the unrecorded-filter refusal -- \
2275 a publication site is missing: {e}"
2276 );
2277 eprintln!("OBMCFILT {name}: {bytes} B, refused for another reason: {e}");
2278 }
2279 }
2280 }
2281 assert!(decoded > 0, "no OBMC recipe decoded -- the witness is vacuous");
2282 assert!(
2283 reads > 0,
2284 "every OBMC blend took the fixed-filter path: the band was never read, so this \
2285 proves nothing about the refusal"
2286 );
2287 }
2288
2289 /// lane-t900 r27 CENSUS for the three SUPERRES refusals -- "warp
2290 /// prediction with a scaled reference", "a sub-8x8 inter block under a
2291 /// scaled reference" and "an 8x8 partition leaf under a scaled reference".
2292 /// Six real `--superres-mode` encodes (fixed denominators and the auto
2293 /// mode, warped motion and OBMC on), decoded by this decoder: the table it
2294 /// prints is which of the three a real encoder actually reaches.
2295 ///
2296 /// Every one of them is a REAL capability gap (unlike the enumerated
2297 /// refusals elsewhere in the inventory), so this gate asserts the measured
2298 /// shape rather than "no refusal": at least one recipe must decode (else
2299 /// the census says nothing), and any refusal must be one of the three
2300 /// named superres ones -- a fourth string would be a new gap this round
2301 /// did not measure.
2302 #[test]
2303 fn a_superres_census_over_six_real_streams_records_which_scaled_refusals_fire() {
2304 if !have_aomenc() {
2305 eprintln!("SKIP a_superres_census_over_six_real_streams: no aomenc");
2306 return;
2307 }
2308 const WARP: &str = "warp prediction with a scaled reference";
2309 const SUB8: &str = "a sub-8x8 inter block under a scaled reference";
2310 const LEAF8: &str = "an 8x8 partition leaf under a scaled reference";
2311 let common = [
2312 "--enable-warped-motion=1",
2313 "--enable-obmc=1",
2314 "--enable-palette=0",
2315 "--enable-intrabc=0",
2316 ];
2317 let recipes: [(&str, usize, usize, Vec<&str>); 6] = [
2318 ("denom12 320x180 cq32", 320, 180, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=12", "--cq-level=32"]),
2319 ("denom12 320x180 cq50", 320, 180, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=12", "--cq-level=50"]),
2320 ("denom16 320x180 cq32", 320, 180, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=16", "--cq-level=32"]),
2321 ("denom10 192x128 cq32", 192, 128, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=10", "--cq-level=32"]),
2322 ("auto 320x180 cq50", 320, 180, vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"]),
2323 ("auto 192x128 cq50", 192, 128, vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"]),
2324 ];
2325 let (mut decoded, mut warp, mut sub8, mut leaf8) = (0, 0, 0, 0);
2326 // lane-t900 r36 (class [[gate-blind-to-feature]]): unknown refusal
2327 // strings used to `other += 1` and panic on the spot, so the census
2328 // summary below -- the whole point of the gate -- never printed when
2329 // one fired. They are collected instead, reported in the summary, and
2330 // asserted after it.
2331 let mut other: Vec<String> = Vec::new();
2332 for (name, w, h, extra) in &recipes {
2333 let mut args = extra.clone();
2334 args.extend_from_slice(&common);
2335 let before = crate::mc::predict_scaled_hits();
2336 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 10, &args);
2337 match result {
2338 Ok(pictures) => {
2339 decoded += 1;
2340 eprintln!(
2341 "SUPERRES {name}: {bytes} B, {pictures} pictures, scaled MC blocks {}",
2342 crate::mc::predict_scaled_hits() - before
2343 );
2344 }
2345 Err(e) => {
2346 eprintln!("SUPERRES {name}: {bytes} B, refused: {e}");
2347 if e.contains(WARP) {
2348 warp += 1;
2349 } else if e.contains(SUB8) {
2350 sub8 += 1;
2351 } else if e.contains(LEAF8) {
2352 leaf8 += 1;
2353 } else {
2354 other.push(format!("{name}: {e}"));
2355 }
2356 }
2357 }
2358 }
2359 eprintln!(
2360 "SUPERRES CENSUS: 6 streams, {decoded} decoded, warp {warp}x, sub8 {sub8}x, leaf8 {leaf8}x, other {}x",
2361 other.len()
2362 );
2363 assert!(
2364 other.is_empty(),
2365 "{} superres stream(s) stopped on a string this census does not know: {other:?}",
2366 other.len()
2367 );
2368 // Measured r27: the four FIXED-denominator recipes all stop at the
2369 // 8x8-leaf refusal, and the two `--superres-mode=3` (auto) streams
2370 // decode with ZERO scaled MC blocks -- auto picked denominator 8, so
2371 // those two arms carry no scaling at all and prove nothing. The warp
2372 // and sub-8x8 refusals never fire because the 8x8-leaf one sits in
2373 // front of them: whichever partition path a scaled frame takes, the
2374 // leaf guard is reached first. Lifting the leaf gap is what makes the
2375 // other two measurable, so this gate pins the ORDER, not just a count.
2376 assert!(decoded > 0, "no superres recipe decoded -- the census is vacuous");
2377 // lane-t900 r28: all three scaled refusals are LIFTED, so the census
2378 // now pins the opposite shape -- every fixed-denominator recipe must
2379 // DECODE, and none of the three strings may come back.
2380 assert_eq!(
2381 (warp, sub8, leaf8),
2382 (0, 0, 0),
2383 "a scaled-reference refusal came back (warp {warp}, sub8 {sub8}, leaf8 {leaf8})"
2384 );
2385 assert!(decoded > 0, "no superres recipe decoded -- the census is vacuous");
2386 }
2387
2388 /// lane-t900 r25, negative gate: a `show_existing_frame` header naming a
2389 /// slot no frame has refreshed is refused BY NAME, and outputs no picture.
2390 ///
2391 /// The OBU is hand-built because [`crate::frame::write_frame_header`]
2392 /// refuses to write one (it writes shown key and inter frames only): spec
2393 /// 5.9.2's whole header for this case is `show_existing_frame` (1) plus
2394 /// `frame_to_show_map_idx` (3), the sequence carrying neither a decoder
2395 /// model nor frame ids.
2396 ///
2397 /// Deviation from the round's charter, which asked for a key frame first
2398 /// with the named slot's `refresh_frame_flags` bit clear: a SHOWN key frame
2399 /// refreshes every slot (spec 5.9.2 forces `refresh_frame_flags` to
2400 /// `all_frames` and does not code it, which is also what
2401 /// `write_frame_header` does), so the only reachable empty-slot stream is
2402 /// one where no frame has refreshed that slot yet. The stream below is a
2403 /// valid sequence header followed by the header OBU, and every one of the
2404 /// eight slots is tried.
2405 #[test]
2406 fn a_show_existing_frame_header_naming_an_empty_slot_is_refused_by_name() {
2407 const REFUSAL: &str = "a show_existing_frame header naming an empty reference slot";
2408 let (seq, _) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2409 for slot in 0..NUM_REF_FRAMES as u32 {
2410 let mut w = ec_core::BitWriter::new();
2411 w.write_bit(true); // show_existing_frame
2412 w.write_bits(slot, 3); // frame_to_show_map_idx
2413 crate::bits::write_byte_alignment(&mut w);
2414 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2415 stream.extend_from_slice(&crate::obu::wrap_obu(
2416 &ec_av1_syntax::obu::ObuHeader {
2417 obu_type: ec_av1_syntax::obu::ObuType::FrameHeader,
2418 extension_flag: false,
2419 has_size_field: true,
2420 temporal_id: 0,
2421 spatial_id: 0,
2422 },
2423 &w.into_bytes(),
2424 ));
2425
2426 let mut shown = 0;
2427 let err = decode_stream_with(&stream, |_, _, _| {
2428 shown += 1;
2429 Ok(())
2430 })
2431 .unwrap_err()
2432 .to_string();
2433 assert!(
2434 err.contains(REFUSAL),
2435 "slot {slot}: expected {REFUSAL:?}, got: {err}"
2436 );
2437 assert_eq!(shown, 0, "slot {slot}: an empty slot was output as a picture");
2438 }
2439 }
2440
2441 /// lane-t900 r25, negative gate: an inter frame whose `ref_frame_idx[0]`
2442 /// slot holds no picture -- a stream that opens on an inter frame -- is
2443 /// refused BY NAME rather than predicting from nothing.
2444 ///
2445 /// Deviation from the round's charter, which asked for a real aomenc
2446 /// two-frame stream with the key frame's OBUs stripped: this crate's own
2447 /// `write_frame_header` writes a shown INTER frame (short reference
2448 /// signalling and non-identity global motion are the parts it refuses), so
2449 /// the fixture is built from the writers, needs neither ffmpeg nor aomenc,
2450 /// and is byte-identical on every run. The tile payload is a real key
2451 /// frame's; the refusal fires on the header's reference lookup, before any
2452 /// tile is decoded.
2453 #[test]
2454 fn an_inter_frame_opening_a_stream_is_refused_by_name() {
2455 let fctx = &crate::decode::FrameCtx::new();
2456 const REFUSAL: &str = "an inter frame with no key frame before it";
2457 let picture = test_card(64, 64);
2458 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2459 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2460 let inter = FrameHeader {
2461 frame_type: FrameType::Inter,
2462 frame_is_intra: false,
2463 // Keeps `primary_ref_frame`, `frame_size_with_refs` and
2464 // `use_ref_frame_mvs` out of the written header (spec 5.9.2).
2465 error_resilient_mode: true,
2466 primary_ref_frame: PRIMARY_REF_NONE,
2467 refresh_frame_flags: 0x02,
2468 order_hint: 1,
2469 ..key
2470 };
2471 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2472 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
2473
2474 let mut shown = 0;
2475 let err = decode_stream_with(&stream, |_, _, _| {
2476 shown += 1;
2477 Ok(())
2478 })
2479 .unwrap_err()
2480 .to_string();
2481 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
2482 assert_eq!(shown, 0, "an inter frame with no reference produced a picture");
2483 }
2484
2485 /// lane-t900 r26, negative gate: an inter frame whose own coded size is
2486 /// SHORTER than the reference it predicts from is refused BY NAME, and
2487 /// outputs no picture beyond the key frame that preceded it.
2488 ///
2489 /// The height mismatch is the one size difference this decoder cannot
2490 /// absorb: `mc::predict_scaled` scales horizontally (a `use_superres`
2491 /// reference), and nothing on this path scales vertically. The fixture is
2492 /// written, not hand-built: a shown key frame at 64x64 (which refreshes
2493 /// every slot), then a shown inter frame carrying
2494 /// `frame_size_override_flag` with `error_resilient_mode` set -- the one
2495 /// combination [`crate::frame::write_frame_header`] writes, since
2496 /// `frame_size_with_refs` (spec 5.9.7) is only read when error resilience
2497 /// is OFF. The inter frame's tile payload is the key frame's; the refusal
2498 /// fires on the reference's dimensions before a tile symbol is read.
2499 #[test]
2500 fn an_inter_frame_shorter_than_its_reference_is_refused_by_name() {
2501 let fctx = &crate::decode::FrameCtx::new();
2502 const REFUSAL: &str =
2503 "a reference picture whose height does not match this frame's own true size";
2504 let picture = test_card(64, 64);
2505 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2506 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2507 let inter = FrameHeader {
2508 frame_type: FrameType::Inter,
2509 frame_is_intra: false,
2510 error_resilient_mode: true,
2511 primary_ref_frame: PRIMARY_REF_NONE,
2512 refresh_frame_flags: 0x02,
2513 order_hint: 1,
2514 frame_size_override_flag: true,
2515 frame_height: 32,
2516 render_height: 32,
2517 ..key.clone()
2518 };
2519 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2520 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &key, &encoded.tile).unwrap());
2521 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
2522
2523 let mut shown = 0;
2524 let err = decode_stream_with(&stream, |_, _, _| {
2525 shown += 1;
2526 Ok(())
2527 })
2528 .unwrap_err()
2529 .to_string();
2530 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
2531 assert_eq!(shown, 1, "expected the key frame alone, got {shown} pictures");
2532 }
2533
2534 /// lane-t900 r26, negative gate: an inter frame naming a
2535 /// `primary_ref_frame` whose reference slot has never been refreshed is
2536 /// refused BY NAME rather than decoded from the spec 8.4 default tables.
2537 ///
2538 /// Enumeration first, because the refusal's premise is an invariant: the
2539 /// picture slots and the CDF slots are written by exactly two loops in
2540 /// [`decode_stream`] (the `show_existing_frame` arm's copy and the
2541 /// end-of-frame store), and both walk the SAME `refresh_frame_flags` mask
2542 /// writing `ref_slots[i]` and `cdf_slots[i]` together -- so no slot can
2543 /// hold a picture without CDFs, and the reachable case is a slot nothing
2544 /// has refreshed at all. That is what this builds: a stream that OPENS on
2545 /// a non-error-resilient inter frame (the only header shape that codes
2546 /// `primary_ref_frame` at all, spec 5.9.2), tried at all eight slots.
2547 ///
2548 /// This refusal, not "an inter frame with no key frame before it", is the
2549 /// one such a stream reaches: the CDF load happens in the header path,
2550 /// before the reference pictures are looked up.
2551 #[test]
2552 fn an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name() {
2553 let fctx = &crate::decode::FrameCtx::new();
2554 const REFUSAL: &str =
2555 "a frame naming primary_ref_frame at a reference slot with no saved CDF state";
2556 // The invariant above, read off the source: every line that stores a
2557 // picture into a slot sits in a block that stores that slot's CDFs too.
2558 let src = include_str!("stream.rs");
2559 let stores: Vec<usize> = src
2560 .lines()
2561 .enumerate()
2562 .filter(|(_, l)| l.trim().starts_with("ref_slots[i] = "))
2563 .map(|(i, _)| i)
2564 .collect();
2565 assert_eq!(
2566 stores.len(),
2567 2,
2568 "the picture slots gained a writer -- check it stores cdf_slots too"
2569 );
2570 let lines: Vec<&str> = src.lines().collect();
2571 for &i in &stores {
2572 let window = lines[i.saturating_sub(6)..(i + 6).min(lines.len())].join("\n");
2573 assert!(
2574 window.contains("cdf_slots[i] = "),
2575 "line {} stores a reference picture with no cdf_slots store beside it: a slot \
2576 can then hold a picture with no saved CDF state",
2577 i + 1
2578 );
2579 }
2580
2581 let picture = test_card(64, 64);
2582 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2583 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2584 for slot in 0..NUM_REF_FRAMES as u8 {
2585 let inter = FrameHeader {
2586 frame_type: FrameType::Inter,
2587 frame_is_intra: false,
2588 // `primary_ref_frame` is coded only when error resilience is
2589 // off (spec 5.9.2); `frame_size_override_flag` stays clear so
2590 // the header writes a plain `frame_size()`.
2591 error_resilient_mode: false,
2592 primary_ref_frame: 0,
2593 ref_frame_idx: [slot; ec_av1_syntax::REFS_PER_FRAME],
2594 refresh_frame_flags: 0x02,
2595 order_hint: 1,
2596 ..key.clone()
2597 };
2598 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2599 stream
2600 .extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
2601
2602 let mut shown = 0;
2603 let err = decode_stream_with(&stream, |_, _, _| {
2604 shown += 1;
2605 Ok(())
2606 })
2607 .unwrap_err()
2608 .to_string();
2609 assert!(err.contains(REFUSAL), "slot {slot}: expected {REFUSAL:?}, got: {err}");
2610 assert_eq!(shown, 0, "slot {slot}: a frame with no CDF state produced a picture");
2611 }
2612 }
2613
2614 /// lane-t900 r26, enumeration: no frame header a stream can carry derives
2615 /// an empty mode-info grid, so "a frame with no mode-info grid" names a
2616 /// case outside the coded domain.
2617 ///
2618 /// `compute_image_size` (spec 5.9.9) is `mi_cols = 2 * ((frame_width + 7)
2619 /// >> 3)`, which is 0 only for `frame_width == 0`, and a frame width is
2620 /// never 0 on any of the three paths that set one:
2621 ///
2622 /// * `frame_size()` (5.9.5) reads `frame_width_minus_1` and adds one, or
2623 /// takes the sequence's `max_frame_width` (itself `+ 1`-coded);
2624 /// * `superres_params()` (5.9.8) divides by a denominator of 9..=16 with
2625 /// rounding, whose minimum over the whole 16-bit upscaled-width domain
2626 /// is enumerated below and is 1, not 0;
2627 /// * `show_existing_frame` and `frame_size_with_refs()` copy a slot's own
2628 /// dimensions, which came from one of the above.
2629 ///
2630 /// The sweep drives the REAL header reader (write a header, parse it back)
2631 /// over every width and every height a 16-bit `frame_size()` can code,
2632 /// per axis -- the derivation is independent per axis -- rather than
2633 /// re-deriving the formula here.
2634 #[test]
2635 fn every_frame_size_a_header_can_code_has_a_mode_info_grid() {
2636 let mut sizes: Vec<u32> = (1..=1024).collect();
2637 sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]);
2638 // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can
2639 // only appear at the SMALL end -- which is why a size this crate's
2640 // tile-info writer cannot express (its tile log2 range runs out well
2641 // before 65536) is skipped rather than worked around, while every
2642 // size up to 1024 must be covered.
2643 let mut skipped: Vec<u32> = Vec::new();
2644 for n in sizes {
2645 for (w, h) in [(n, 16), (16, n)] {
2646 let Ok((seq, header)) =
2647 crate::encode::key_frame_headers(w as usize, h as usize, 100)
2648 else {
2649 skipped.push(n);
2650 continue;
2651 };
2652 let Ok(stream) = crate::frame::frame_obu(&seq, &header, &[]) else {
2653 skipped.push(n);
2654 continue;
2655 };
2656 let mut parser = Av1Parser::new();
2657 parser.parse_obu(&crate::sequence::sequence_header_obu(&seq).unwrap()).unwrap();
2658 let obu = parser.parse_obu(&stream).unwrap();
2659 let ObuKind::Frame(parsed, _) = &obu.kind else {
2660 panic!("{w}x{h}: the written frame OBU did not parse as one");
2661 };
2662 assert!(
2663 parsed.mi_cols >= 2 && parsed.mi_rows >= 2,
2664 "{w}x{h} parsed to a {}x{} mode-info grid",
2665 parsed.mi_cols,
2666 parsed.mi_rows
2667 );
2668 }
2669 }
2670 assert!(
2671 skipped.iter().all(|&n| n > 1024),
2672 "the writer could not express these small frame sizes, so the small end of the \
2673 sweep is incomplete: {skipped:?}"
2674 );
2675 // The superres arm, which no writer here can express: spec 5.9.8's
2676 // `(upscaled_width * 8 + denom / 2) / denom` over its whole domain.
2677 for denom in 9u32..=16 {
2678 for upscaled in [1u32, 2, 3, 7, 8, 9, 255, 4096, 65535, 65536] {
2679 let width = (upscaled * 8 + denom / 2) / denom;
2680 assert!(
2681 width >= 1,
2682 "superres denom {denom} maps an upscaled width of {upscaled} to {width}, \
2683 which would derive an empty mode-info grid"
2684 );
2685 }
2686 }
2687 }
2688
2689 /// lane-interedge r1: one attempt of the inter frame-edge half-strip gate --
2690 /// encode `width x height` with real aomenc (rect partitions ON, every other
2691 /// lane's open tool pinned off), decode it, and return
2692 /// `(inter_edge_strip hits, frames whose LUMA differs, frames whose CHROMA
2693 /// differs)` against ffmpeg. A refusal or a decode error is a hard failure:
2694 /// this recipe reached every size without one (measured r1).
2695 fn inter_edge_strip_attempt(
2696 name: &str,
2697 width: usize,
2698 height: usize,
2699 bit_depth: u32,
2700 cq: u32,
2701 frames: usize,
2702 ) -> ([usize; 6], usize, usize) {
2703 let duration = format!("{}", frames as f64 / 25.0);
2704 let source = format!("mandelbrot=size={width}x{height}:rate=25");
2705 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
2706 let y4m = Command::new("ffmpeg")
2707 .args([
2708 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration, "-pix_fmt",
2709 pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
2710 ])
2711 .stdin(Stdio::null())
2712 .stdout(Stdio::piped())
2713 .stderr(Stdio::piped())
2714 .output()
2715 .expect("ffmpeg failed to run");
2716 assert!(
2717 y4m.status.success(),
2718 "{name}: ffmpeg refused the {width}x{height} {bit_depth}-bit fixture: {}",
2719 String::from_utf8_lossy(&y4m.stderr)
2720 );
2721 let depth_arg = format!("--bit-depth={bit_depth}");
2722 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
2723 let cq_arg = format!("--cq-level={cq}");
2724 let limit_arg = format!("--limit={frames}");
2725 let mut child = Command::new(aomenc_path())
2726 .args([
2727 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg,
2728 // cpu-used >= 1 keeps libaom on 64x64 superblocks at these
2729 // sizes (`av1_select_sb_size`).
2730 "--cpu-used=4", "--threads=1", "--row-mt=0", "--kf-max-dist=9999",
2731 &limit_arg,
2732 // decode order == display order, so the compare below covers
2733 // every frame the stream carries (class gate-blind-to-hidden-frames).
2734 "--lag-in-frames=0", &depth_arg, &input_depth_arg,
2735 // Rect partitions stay ON: the frame-edge strip is a FORCED
2736 // (gathered) HORZ/VERT, but with rect coding off the encoder
2737 // answers that gathered symbol SPLIT every time and no edge
2738 // strip ever fires (lane-oddh r2's finding, re-measured r1).
2739 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
2740 "--enable-1to4-partitions=0", "--min-partition-size=8",
2741 "--max-partition-size=64",
2742 // Other lanes' open gaps this recipe must not trip.
2743 "--enable-palette=0", "--enable-intrabc=0", "--enable-warped-motion=0",
2744 "--enable-obmc=0", "--enable-masked-comp=0", "--enable-interintra-comp=0",
2745 "--enable-onesided-comp=0", "--enable-interintra-wedge=0",
2746 "--enable-smooth-interintra=0", "--enable-ref-frame-mvs=0",
2747 "--enable-angle-delta=0", "--enable-cfl-intra=0",
2748 "--enable-directional-intra=0", "--enable-smooth-intra=0",
2749 "--enable-paeth-intra=0", "--enable-filter-intra=0",
2750 "--enable-tx-size-search=0",
2751 "--obu", "-o", "-", "-",
2752 ])
2753 .stdin(Stdio::piped())
2754 .stdout(Stdio::piped())
2755 .stderr(Stdio::piped())
2756 .spawn()
2757 .expect("aomenc failed to start");
2758 child
2759 .stdin
2760 .take()
2761 .expect("aomenc stdin")
2762 .write_all(&y4m.stdout)
2763 .expect("write y4m");
2764 let out = child.wait_with_output().expect("aomenc failed to run");
2765 assert!(
2766 out.status.success(),
2767 "aomenc refused: {}",
2768 String::from_utf8_lossy(&out.stderr)
2769 );
2770 let stream = out.stdout;
2771
2772 // Reset, never a delta: a refused attempt's hits must not leak into the
2773 // next one (class counter-from-refused-stream).
2774 crate::decode::reset_inter_edge_strip_hits();
2775 let decoded = decode_stream(&stream).unwrap_or_else(|e| {
2776 panic!("{name}: {width}x{height} {bit_depth}-bit cq {cq} did not decode: {e}")
2777 });
2778 let hits = crate::decode::inter_edge_strip_hits();
2779 let reference = if bit_depth == 10 {
2780 ffmpeg_decode_sequence_10bit(&stream, width, height, frames)
2781 } else {
2782 ffmpeg_decode_sequence(&stream, width, height, frames)
2783 };
2784 assert_eq!(
2785 decoded.len(),
2786 reference.len(),
2787 "{name}: {width}x{height} {bit_depth}-bit cq {cq} frame count"
2788 );
2789 assert!(
2790 decoded.len() >= frames,
2791 "{name}: {width}x{height} {bit_depth}-bit cq {cq} decoded only {} frames",
2792 decoded.len()
2793 );
2794 let (mut luma_bad, mut chroma_bad) = (0usize, 0usize);
2795 for (ours, theirs) in decoded.iter().zip(&reference) {
2796 if ours.y != theirs.y {
2797 luma_bad += 1;
2798 }
2799 if ours.u != theirs.u || ours.v != theirs.v {
2800 chroma_bad += 1;
2801 }
2802 }
2803 (hits, luma_bad, chroma_bad)
2804 }
2805
2806 /// lane-interedge r1 GATE (was lane-oddh r2's `#[ignore]`d twin): the INTER
2807 /// frame-edge half strips -- a `PARTITION_HORZ`/`PARTITION_VERT` forced by
2808 /// the gathered edge symbol at the 64, 32 or 16 level whose second half lies
2809 /// outside the true frame. Both of the user's films are height mod 16 == 8
2810 /// (1920x792, 3840x1608), so every inter frame crosses these nodes.
2811 ///
2812 /// r1 root cause: the inter tile's 32-level `PARTITION_HORZ`/`PARTITION_VERT`
2813 /// decoded the SECOND strip unconditionally, while libaom `decode_partition`
2814 /// (decodeframe.c, PARTITION_HORZ) guards it with `has_rows`/`has_cols` --
2815 /// so at the edge we read symbols the encoder never wrote. With that guard
2816 /// removed this gate's 72x192 cq 32 arm refuses outright and its 104x192 arm
2817 /// decodes luma rows 127..191 of frame 5 wrong (measured r1).
2818 ///
2819 /// The compare is LUMA-exact per frame plus a CONTROL size with no edge node
2820 /// at all: chroma is excluded because a chroma-only inter residue that has
2821 /// nothing to do with the frame edge is open on main (lanes/tiny-r3,
2822 /// lanes/gmaffine-r4, lanes/palette2-r8) and the control below reproduces it
2823 /// with `inter_edge_strip_hits` all zero.
2824 #[test]
2825 fn a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact() {
2826 const NAME: &str = "a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact";
2827 let _gate_lock = lock_gate_counters();
2828 if !have_ffmpeg() || !have_aomenc() {
2829 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
2830 return;
2831 }
2832 let frames = 6usize;
2833 // h mod 16 == 8 (bottom edge) and w mod 16 == 8 (right edge).
2834 let sizes: &[(usize, usize)] = &[(192, 72), (192, 88), (72, 192), (88, 192), (104, 192)];
2835 let mut totals = [0usize; 6];
2836 let mut compared = 0u32;
2837 let mut chroma_frames = 0usize;
2838 for &(width, height) in sizes {
2839 for bit_depth in [8u32, 10] {
2840 for cq in [20u32, 32, 45] {
2841 let (hits, luma_bad, chroma_bad) =
2842 inter_edge_strip_attempt(NAME, width, height, bit_depth, cq, frames);
2843 assert_eq!(
2844 luma_bad, 0,
2845 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {luma_bad} of {frames} \
2846 frames differ from ffmpeg in LUMA (edge hits {hits:?})"
2847 );
2848 // merge J, after lane-rectchroma2: the chroma residue this
2849 // gate used to tolerate WAS this decoder's -- the per-axis
2850 // narrow-block MC kernel decision read side x side instead
2851 // of the block's true dims. Full-plane now.
2852 assert_eq!(
2853 chroma_bad, 0,
2854 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {chroma_bad} of \
2855 {frames} frames differ from ffmpeg in CHROMA (edge hits {hits:?})"
2856 );
2857 for (t, h) in totals.iter_mut().zip(hits) {
2858 *t += h;
2859 }
2860 chroma_frames += chroma_bad;
2861 compared += 1;
2862 }
2863 }
2864 }
2865 // Every level x axis this recipe reaches must have fired on a COMPARED
2866 // attempt. h32 (a bottom-edge HORZ at the 32 level) is not asserted: no
2867 // recipe found in r1 makes libaom answer that gathered symbol HORZ
2868 // (sweep ~/.cache/interedge-tmp/h32.sh, 3 sizes x 6 cq, all SPLIT); it
2869 // is the transposed twin of v32, which this gate does fire.
2870 assert!(
2871 totals[0] > 0 && totals[1] > 0 && totals[3] > 0 && totals[4] > 0 && totals[5] > 0,
2872 "{NAME}: {compared} attempts luma-exact but the edge strips did not all fire \
2873 (h64,v64,h32,v32,h16,v16 = {totals:?}) -- the recipe no longer reaches the arms \
2874 this gate exists for"
2875 );
2876 // CONTROL: a size with no frame-edge node anywhere (192x128, both axes
2877 // 0 mod 64). It must be luma-exact with ZERO edge hits -- that is what
2878 // makes the chroma exclusion above a statement about a foreign defect
2879 // rather than about this lane's code.
2880 let (chits, cluma, cchroma) = inter_edge_strip_attempt(NAME, 192, 128, 8, 32, frames);
2881 assert_eq!(
2882 (chits, cluma, cchroma),
2883 ([0usize; 6], 0usize, 0usize),
2884 "{NAME}: control 192x128 (no frame-edge node) must be pixel-exact with no edge hits"
2885 );
2886 eprintln!(
2887 "{NAME}: {compared} attempts luma-exact over {} sizes, edge hits \
2888 (h64,v64,h32,v32,h16,v16)={totals:?}, 0 refusals; chroma-only frames {chroma_frames} \
2889 (control 192x128: hits {chits:?}, chroma-only frames {cchroma} -- foreign defect)",
2890 sizes.len()
2891 );
2892 }
2893
2894 /// lane-sb128 r4 GATE (was lane-oddh r2's refusal gate): the SAME real
2895 /// aomenc 64x72 `--cpu-used=0 --sb-size=128` stream that once desynced at
2896 /// the very first symbol now decodes PIXEL-EXACT against aomdec. mi_rows
2897 /// = 18 > 16, so the BLOCK_128X128 root reads a real gathered partition
2898 /// symbol (2 symbols: has_cols false, has_rows true) -- exactly the case
2899 /// r1 mis-read as a 10-symbol BLOCK_64X64 partition.
2900 ///
2901 /// The `use_128x128_superblock` assert is the "knob reached the tool"
2902 /// half: without it an aomenc that ignored `--sb-size=128` would leave
2903 /// the gate proving nothing about 128 superblocks.
2904 #[test]
2905 fn a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact() {
2906 if !have_ffmpeg() || !have_aomenc() {
2907 eprintln!("SKIP: no ffmpeg/aomenc");
2908 return;
2909 }
2910 let (width, height) = (64usize, 72usize);
2911 let y4m = Command::new("ffmpeg")
2912 .args([
2913 "-v", "error", "-f", "lavfi", "-i",
2914 "mandelbrot=size=64x72:rate=25:start_x=-0.6:start_y=-0.4", "-t", "0.04",
2915 "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-",
2916 ])
2917 .stdin(Stdio::null())
2918 .stdout(Stdio::piped())
2919 .stderr(Stdio::piped())
2920 .output()
2921 .expect("ffmpeg failed to run");
2922 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
2923 let mut child = Command::new(aomenc_path())
2924 .args([
2925 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32",
2926 "--cpu-used=0", "--sb-size=128", "--min-partition-size=16",
2927 "--kf-max-dist=0", "--limit=1",
2928 "--threads=1", "--row-mt=0", "--obu", "-o", "-", "-",
2929 ])
2930 .stdin(Stdio::piped())
2931 .stdout(Stdio::piped())
2932 .stderr(Stdio::piped())
2933 .spawn()
2934 .expect("aomenc failed to start");
2935 child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("write y4m");
2936 let out = child.wait_with_output().expect("aomenc failed to run");
2937 assert!(out.status.success(), "aomenc refused: {}", String::from_utf8_lossy(&out.stderr));
2938 let stream = out.stdout;
2939
2940 // The knob actually arrived: this stream's sequence header codes
2941 // `use_128x128_superblock = 1`.
2942 let mut parser = Av1Parser::new();
2943 let mut pos = 0usize;
2944 let mut sb128 = false;
2945 while pos < stream.len() {
2946 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
2947 break;
2948 };
2949 pos += obu.total_size.max(1);
2950 if let Some(seq) = parser.sequence_header() {
2951 sb128 = seq.use_128x128_superblock;
2952 break;
2953 }
2954 }
2955 assert!(sb128, "aomenc ignored --sb-size=128: this stream is 64x64-superblock");
2956
2957 let _guard = lock_gate_counters();
2958 let before = crate::decode::part128_symbols()
2959 + crate::decode::part128_gathered_symbols();
2960 let (frames, hidden) =
2961 decode_all_frames_vs_oracle(&stream, "sb128-oddh-64x72");
2962 assert!(frames > 0, "no frames decoded for {width}x{height}");
2963 // The 128 root actually READ a partition symbol here: at mi_rows=18
2964 // `has_rows` is true, so BLOCK_128X128 is not a forced split.
2965 let part128 = crate::decode::part128_symbols()
2966 + crate::decode::part128_gathered_symbols()
2967 - before;
2968 assert!(
2969 part128 > 0,
2970 "{width}x{height} decoded without reading a single BLOCK_128X128 \
2971 partition symbol -- the gate proves nothing about the 128 root"
2972 );
2973 eprintln!(
2974 "a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact: \
2975 {frames} frames pixel-exact ({hidden} hidden) at {width}x{height}, \
2976 part128_symbols={part128}"
2977 );
2978 }
2979
2980 /// `decode_stream` on a lone key frame's stream matches both the tile
2981 /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and
2982 /// the encoder's own reconstruction, at an even and an odd size.
2983 #[test]
2984 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
2985 let fctx = &crate::decode::FrameCtx::new();
2986 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
2987 let picture = test_card(width, height);
2988 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2989 let via_tile = decode_key_frame_tile_lr(
2990 &encoded.tile,
2991 encoded.mi_cols,
2992 encoded.mi_rows,
2993 encoded.base_q_idx,
2994 width as u32,
2995 height as u32,
2996 false,
2997 &encoded.cdef,
2998 &encoded.loop_filter,
2999 encoded.tx_select,
3000 // Our own encoder always writes `reduced_tx_set: true`.
3001 true,
3002 // `allow_screen_content_tools` off the frame the encoder
3003 // actually wrote: a screen-content picture codes two palette
3004 // symbols per intra block, and a raw tile decode that guessed
3005 // `false` desyncs at the first one (class: test asserts
3006 // against a stale header).
3007 encoded.screen,
3008 // ... and its own `allow_intrabc` (stale-header class).
3009 encoded.allow_intrabc,
3010 &encoded.loop_restoration, fctx,
3011 )
3012 .unwrap();
3013 let via_stream = decode_stream(&encoded.stream).unwrap();
3014 assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture");
3015 assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma");
3016 assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U");
3017 assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V");
3018 assert_eq!(
3019 via_stream[0].y, encoded.reconstruction.y,
3020 "{width}x{height}: luma vs encoder reconstruction"
3021 );
3022 }
3023 }
3024
3025 /// A GOP (key frame plus panned inter frames, so blocks actually take
3026 /// motion) decodes bit-exact through `decode_stream` alone, threading its
3027 /// own DPB rather than a test-supplied reference.
3028 fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) {
3029 let pictures: Vec<_> = (0..4)
3030 .map(|i| panned_test_card(width, height, i * 3))
3031 .collect();
3032 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
3033 let decoded = decode_stream(&encoded.stream).unwrap();
3034 assert_eq!(decoded.len(), encoded.frames.len());
3035 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
3036 assert_eq!(
3037 got.y, frame.reconstruction.y,
3038 "{width}x{height} frame {i} luma"
3039 );
3040 assert_eq!(
3041 got.u, frame.reconstruction.u,
3042 "{width}x{height} frame {i} U"
3043 );
3044 assert_eq!(
3045 got.v, frame.reconstruction.v,
3046 "{width}x{height} frame {i} V"
3047 );
3048 }
3049 }
3050
3051 #[test]
3052 fn decode_stream_round_trips_a_gop() {
3053 let fctx = &crate::decode::FrameCtx::new();
3054 gop_round_trips(128, 64, fctx);
3055 }
3056
3057 /// Same claim at a size that is not a whole number of 32x32 blocks, so
3058 /// the inter frame's 16x16-leaf split path is exercised too.
3059 #[test]
3060 fn decode_stream_round_trips_an_odd_size_gop() {
3061 let fctx = &crate::decode::FrameCtx::new();
3062 gop_round_trips(216, 96, fctx);
3063 }
3064
3065 /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures
3066 /// `decode_stream` collects, in the same order -- the streaming path is
3067 /// the decoder now (`decode_stream` is a collecting wrapper), so an
3068 /// equivalence check here is what keeps every gate's Vec-shaped assert
3069 /// meaningful. Also pins the sink contract: one call per shown picture,
3070 /// decode indices non-decreasing, and an `Err` from the sink aborting.
3071 #[test]
3072 fn streaming_decode_matches_the_collecting_one() {
3073 let fctx = &crate::decode::FrameCtx::new();
3074 let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect();
3075 let stream = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap().stream;
3076 let collected = decode_stream(&stream).unwrap();
3077
3078 let mut shown = Vec::new();
3079 let mut idxs = Vec::new();
3080 let mut live = 0usize;
3081 decode_stream_with(&stream, |p, idx, is_shown| {
3082 live += 1;
3083 if is_shown {
3084 idxs.push(idx);
3085 shown.push(p.clone());
3086 }
3087 Ok(())
3088 })
3089 .unwrap();
3090 assert_eq!(shown.len(), collected.len(), "callback count vs shown frames");
3091 assert!(live >= shown.len(), "every shown picture is also a callback");
3092 assert!(
3093 idxs.windows(2).all(|w| w[0] <= w[1]),
3094 "decode indices out of order: {idxs:?}"
3095 );
3096 for (i, (got, want)) in shown.iter().zip(&collected).enumerate() {
3097 assert_eq!(got.y, want.y, "frame {i} luma");
3098 assert_eq!(got.u, want.u, "frame {i} U");
3099 assert_eq!(got.v, want.v, "frame {i} V");
3100 }
3101
3102 // A sink error stops the decode and comes back unchanged.
3103 let mut seen = 0usize;
3104 let err = decode_stream_with(&stream, |_, _, _| {
3105 seen += 1;
3106 Err(Error::corrupt("sink says stop"))
3107 })
3108 .unwrap_err();
3109 assert_eq!(seen, 1, "decode continued past a failing sink");
3110 assert!(format!("{err}").contains("sink says stop"), "{err}");
3111 }
3112
3113 use std::io::Write;
3114 use std::process::{Command, Stdio};
3115
3116 /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
3117 /// `skip_mode`/compound) all read a process-global atomic counter delta
3118 /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
3119 /// prove a real block picked the feature under test, not just that a
3120 /// header bit was set. Under `cargo test`'s default parallel run, a
3121 /// SIBLING test's own decode bumps the same global counter mid-gate --
3122 /// a false "fired" reading pixel-compares an attempt the gate would
3123 /// otherwise `continue` past, on top of genuine defects that path may
3124 /// still have. Serialising every counter-delta gate behind this one
3125 /// mutex makes firing detection honest again (matches the existing
3126 /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
3127 static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
3128 /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]):
3129 /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH
3130 /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named
3131 /// refusal -- and the three sum to the attempts made.
3132 fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) {
3133 eprintln!(
3134 "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \
3135 named-refusals={named_refusals} (attempts {})",
3136 counted_exact as usize + uncounted_exact as usize + named_refusals
3137 );
3138 }
3139
3140 pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
3141 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
3142 }
3143
3144 /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic --
3145 /// this is a load-bearing-identity fingerprint for flake triage, not a
3146 /// security digest, so no `sha2` dep is pulled in) fixture fingerprint
3147 /// for the cdf-forwarding gate's instrumentation below.
3148 fn fnv1a64(bytes: &[u8]) -> u64 {
3149 let mut hash = 0xcbf29ce484222325u64;
3150 for &b in bytes {
3151 hash ^= b as u64;
3152 hash = hash.wrapping_mul(0x100000001b3);
3153 }
3154 hash
3155 }
3156
3157 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
3158 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
3159 /// aomenc gate decodes its stream through ffmpeg and is meaningless
3160 /// without it -- turns it into a hard failure. Without this the require
3161 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
3162 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
3163 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
3164 fn have_ffmpeg() -> bool {
3165 let present = Command::new("ffmpeg")
3166 .arg("-version")
3167 .stdout(Stdio::null())
3168 .stderr(Stdio::null())
3169 .status()
3170 .is_ok_and(|s| s.success());
3171 assert!(
3172 present
3173 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
3174 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
3175 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
3176 );
3177 present
3178 }
3179
3180 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
3181 fn ffmpeg_decode_sequence(
3182 stream: &[u8],
3183 width: usize,
3184 height: usize,
3185 frames: usize,
3186 ) -> Vec<Pic> {
3187 let mut child = Command::new("ffmpeg")
3188 .args([
3189 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3190 ])
3191 .stdin(Stdio::piped())
3192 .stdout(Stdio::piped())
3193 .stderr(Stdio::piped())
3194 .spawn()
3195 .expect("ffmpeg failed to start");
3196 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
3197 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
3198 // fills before the last input byte is written -- which is exactly what
3199 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
3200 // (measured: 45 min, both processes at 0% CPU). A write error here is
3201 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
3202 // below, are the real diagnosis.
3203 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
3204 let payload = stream.to_vec();
3205 let writer = std::thread::Builder::new()
3206 .name("ec-av1-ffmpeg-in".into())
3207 .spawn(move || {
3208 let _ = stdin.write_all(&payload);
3209 })
3210 .expect("spawning the ffmpeg stdin writer");
3211 let out = child.wait_with_output().expect("ffmpeg failed to run");
3212 writer.join().expect("ffmpeg stdin writer thread");
3213 assert!(
3214 out.status.success(),
3215 "ffmpeg refused the stream: {}",
3216 String::from_utf8_lossy(&out.stderr)
3217 );
3218 let (luma, chroma) = (width * height, width * height / 4);
3219 let frame_bytes = luma + 2 * chroma;
3220 assert_eq!(
3221 out.stdout.len(),
3222 frame_bytes * frames,
3223 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
3224 String::from_utf8_lossy(&out.stderr)
3225 );
3226 (0..frames)
3227 .map(|i| {
3228 let base = i * frame_bytes;
3229 Pic {
3230 width,
3231 height,
3232 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
3233 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
3234 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
3235 }
3236 })
3237 .collect()
3238 }
3239
3240 /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
3241 /// are 2-byte little-endian, one full 16-bit range regardless of the
3242 /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
3243 /// bit depth). The 8-bit helper above stays untouched -- every existing
3244 /// gate depends on it.
3245 fn ffmpeg_decode_sequence_10bit(
3246 stream: &[u8],
3247 width: usize,
3248 height: usize,
3249 frames: usize,
3250 ) -> Vec<Pic> {
3251 let mut child = Command::new("ffmpeg")
3252 .args([
3253 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt",
3254 "yuv420p10le", "-",
3255 ])
3256 .stdin(Stdio::piped())
3257 .stdout(Stdio::piped())
3258 .stderr(Stdio::piped())
3259 .spawn()
3260 .expect("ffmpeg failed to start");
3261 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
3262 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
3263 // fills before the last input byte is written -- which is exactly what
3264 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
3265 // (measured: 45 min, both processes at 0% CPU). A write error here is
3266 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
3267 // below, are the real diagnosis.
3268 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
3269 let payload = stream.to_vec();
3270 let writer = std::thread::Builder::new()
3271 .name("ec-av1-ffmpeg-in".into())
3272 .spawn(move || {
3273 let _ = stdin.write_all(&payload);
3274 })
3275 .expect("spawning the ffmpeg stdin writer");
3276 let out = child.wait_with_output().expect("ffmpeg failed to run");
3277 writer.join().expect("ffmpeg stdin writer thread");
3278 assert!(
3279 out.status.success(),
3280 "ffmpeg refused the stream: {}",
3281 String::from_utf8_lossy(&out.stderr)
3282 );
3283 let (luma, chroma) = (width * height, width * height / 4);
3284 let frame_samples = luma + 2 * chroma;
3285 let frame_bytes = frame_samples * 2;
3286 assert_eq!(
3287 out.stdout.len(),
3288 frame_bytes * frames,
3289 "expected {frames} 4:2:0 10-bit frames, ffmpeg said: {}",
3290 String::from_utf8_lossy(&out.stderr)
3291 );
3292 fn le16(bytes: &[u8]) -> Vec<u16> {
3293 bytes
3294 .chunks_exact(2)
3295 .map(|c| u16::from_le_bytes([c[0], c[1]]))
3296 .collect()
3297 }
3298 (0..frames)
3299 .map(|i| {
3300 let base = i * frame_bytes;
3301 Pic {
3302 width,
3303 height,
3304 y: le16(&out.stdout[base..base + luma * 2]),
3305 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
3306 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
3307 }
3308 })
3309 .collect()
3310 }
3311
3312 /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an
3313 /// independent decoder, not just this crate checking its own tile path.
3314 #[test]
3315 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
3316 let fctx = &crate::decode::FrameCtx::new();
3317 if !have_ffmpeg() {
3318 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
3319 return;
3320 }
3321 let (width, height) = (128usize, 64usize);
3322 let pictures: Vec<_> = (0..3)
3323 .map(|i| panned_test_card(width, height, i * 3))
3324 .collect();
3325 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
3326 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
3327 let decoded = decode_stream(&encoded.stream).unwrap();
3328 assert_eq!(decoded.len(), 3);
3329 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
3330 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
3331 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
3332 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
3333 }
3334 }
3335
3336 /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME`
3337 /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s
3338 /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc
3339 /// attempts never could: frame 0 is a real key frame (this crate's own
3340 /// encoder, real texture), refreshing all 8 DPB slots as spec requires --
3341 /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded
3342 /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`),
3343 /// refreshing only slot 0 with a flat 128 block -- distinguishable from
3344 /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3
3345 /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs.
3346 /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3`
3347 /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose
3348 /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME`
3349 /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy
3350 /// of GOLDEN's picture, so its output must equal frame 0's own
3351 /// reconstruction exactly, and must differ from frame 1's -- proof the
3352 /// decoder actually read the golden plane, not silently substituted
3353 /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a
3354 /// deblock/MC residue that turned out to be film-grain synthesis
3355 /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN);
3356 /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing
3357 /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so
3358 /// this fixture flips back to its round-4 pixel-exact form. ffmpeg
3359 /// decodes the identical wire bytes as the foreign oracle
3360 /// (shared-oracle-blindness class): this crate's own decoder agreeing
3361 /// with itself would prove nothing.
3362 #[test]
3363 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
3364 let fctx = &crate::decode::FrameCtx::new();
3365 if !have_ffmpeg() {
3366 eprintln!(
3367 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
3368 );
3369 return;
3370 }
3371 use crate::cdf_state::Cdfs;
3372 use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of};
3373 use crate::encode::{inter_frame_headers, key_frame_headers};
3374 use crate::frame::frame_obu;
3375 use crate::msac::SymbolEncoder;
3376 use crate::mvstack::{
3377 GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx,
3378 single_ref_p5_ctx,
3379 };
3380 use crate::obu::temporal_delimiter;
3381
3382 let (width, height) = (32usize, 32usize);
3383 let base_q_idx = 100u8;
3384 // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/
3385 // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" --
3386 // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB`
3387 // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false
3388 // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/
3389 // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1`
3390 // (decode.rs `Neighbours::new`) -- computed here without
3391 // constructing the (module-private) `Neighbours` itself.
3392 const PARTITION_NONE: usize = 0;
3393 let ii_ctx = intra_inter_ctx(false, false, false, false);
3394 let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None);
3395 let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None);
3396 let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None);
3397
3398 for run in 0..4 {
3399 let picture = test_card(width, height);
3400 let key = encode_key_frame_with_ctx(&picture, base_q_idx, 0.5, fctx).unwrap();
3401 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
3402
3403 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
3404 // 128 block (no neighbours to predict `DC_PRED` from).
3405 let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
3406 // These two tiles are hand-coded from a FRESH `Cdfs`, so the
3407 // frames must not carry CDF state the way the encoder's own inter
3408 // frames now do (spec 7.20): with the bit set, what each frame
3409 // stores is what it started from -- the defaults -- which is
3410 // exactly what the next hand-coded tile assumes.
3411 header1.disable_frame_end_update_cdf = true;
3412 let tile1 = {
3413 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3414 let mut enc = SymbolEncoder::new();
3415 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
3416 enc.symbol(1, &mut cdfs.skip[0]); // skip
3417 enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false
3418 enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32)
3419 enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED
3420 enc.finish()
3421 };
3422 let mut stream = key.stream.clone();
3423 stream.extend(temporal_delimiter());
3424 stream.extend(frame_obu(&seq, &header1, &tile1).unwrap());
3425
3426 // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
3427 // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
3428 let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
3429 header2.disable_frame_end_update_cdf = true;
3430 header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
3431 let tile2 = {
3432 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3433 let mut enc = SymbolEncoder::new();
3434 let grid = MiGrid::new(8, 8);
3435 let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8);
3436 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
3437 enc.symbol(1, &mut cdfs.skip[0]); // skip
3438 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true
3439 enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group
3440 enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group
3441 enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME
3442 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV
3443 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV
3444 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0)
3445 enc.finish()
3446 };
3447 stream.extend(temporal_delimiter());
3448 stream.extend(frame_obu(&seq, &header2, &tile2).unwrap());
3449
3450 let before = non_last_ref_hits();
3451 let decoded = decode_stream(&stream).unwrap();
3452 assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures");
3453 assert!(
3454 non_last_ref_hits() > before,
3455 "run {run}: GOLDEN_FRAME never fired"
3456 );
3457
3458 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3);
3459 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
3460 assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg");
3461 assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg");
3462 assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg");
3463 }
3464 assert_eq!(
3465 decoded[0].y, key.reconstruction.y,
3466 "run {run}: frame 0 vs the encoder's own reconstruction"
3467 );
3468 assert_eq!(
3469 decoded[2].y, key.reconstruction.y,
3470 "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names"
3471 );
3472 assert_ne!(
3473 decoded[2].y, decoded[1].y,
3474 "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \
3475 distinguishable -- the gate proves nothing"
3476 );
3477 }
3478 }
3479
3480 /// Builds a `gradients` lavfi source string with colours derived from
3481 /// `seed`, not left to the filter's own default.
3482 ///
3483 /// Measured (lane-fixdet r1): ffmpeg's `gradients` source IGNORES its
3484 /// `seed=` parameter for colour selection -- five encodes of an
3485 /// identical command line (same `seed=`, same everything) produced five
3486 /// different fixtures, because the unset `c0..c9` stops are randomized
3487 /// from something other than that seed. Every one of this file's ~20
3488 /// gate fixtures built a `gradients` source this way, so none of them
3489 /// had a reproducible input: a pin captured from one run could not be
3490 /// regenerated, and "attempt N failed" was as likely to be a different
3491 /// fixture as a different decode outcome.
3492 ///
3493 /// Freezing the colours outright (as the earliest four gates below do,
3494 /// hand-picking `c0=red:c1=blue:c2=green`) fixes reproducibility but
3495 /// throws away the per-attempt content variety the sweep gates need to
3496 /// make features (OBMC, warp, wedge, ...) fire at all -- this repo's own
3497 /// `sampler-decorrelated-gate` class. So: derive `c0..c3` deterministically
3498 /// FROM the seed with a plain integer hash, and keep passing `seed=`
3499 /// itself too, so a future ffmpeg that actually honours it only adds
3500 /// more variety, never removes the determinism this buys.
3501 fn gradients_source(seed: u32, width: usize, height: usize, tail: &str) -> String {
3502 fn hash_color(seed: u32, salt: u32) -> String {
3503 let h = seed
3504 .wrapping_mul(2_654_435_761)
3505 .wrapping_add(salt.wrapping_mul(0x9E37_79B9))
3506 ^ (seed.rotate_left(13));
3507 format!("0x{:06x}", h & 0x00ff_ffff)
3508 }
3509 let (c0, c1, c2, c3) = (
3510 hash_color(seed, 0),
3511 hash_color(seed, 1),
3512 hash_color(seed, 2),
3513 hash_color(seed, 3),
3514 );
3515 format!("gradients=size={width}x{height}:c0={c0}:c1={c1}:c2={c2}:c3={c3}:seed={seed}:{tail}")
3516 }
3517
3518 /// The determinism guard: same seed twice must byte-match ffmpeg's own
3519 /// output; different seeds must not. Regresses this fix if it ever
3520 /// breaks.
3521 #[test]
3522 fn gradients_source_is_reproducible_per_seed() {
3523 if !have_ffmpeg() {
3524 eprintln!("SKIP gradients_source_is_reproducible_per_seed: no ffmpeg");
3525 return;
3526 }
3527 fn render_hash(lavfi: &str) -> Vec<u8> {
3528 let out = Command::new("ffmpeg")
3529 .args([
3530 "-v", "error", "-f", "lavfi", "-i", lavfi, "-frames:v", "1", "-f", "rawvideo",
3531 "-",
3532 ])
3533 .stdin(Stdio::null())
3534 .stdout(Stdio::piped())
3535 .stderr(Stdio::piped())
3536 .output()
3537 .expect("ffmpeg failed to run");
3538 assert!(out.status.success(), "ffmpeg refused {lavfi}");
3539 out.stdout
3540 }
3541 let a1 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
3542 let a2 = render_hash(&gradients_source(43, 64, 64, "duration=0.04:rate=25"));
3543 let a3 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
3544 assert_eq!(a1, a3, "same seed must reproduce byte-identical output");
3545 assert_ne!(a1, a2, "different seeds must not collide");
3546 }
3547
3548 /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this
3549 /// crate's) with the same reduced-partition flags lane-av1adst's r6
3550 /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on
3551 /// gradient content (TX_SET_INTRA_2), and decodes it with
3552 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
3553 /// gets past an encoder this crate never wrote a byte of.
3554 fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
3555 libaom_encode_with(lavfi, width, height, crf, &[])
3556 }
3557
3558 /// As [`libaom_encode`], with extra encoder args appended -- used to pin
3559 /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
3560 /// RD search is not otherwise stable run-to-run on this box, and lavfi
3561 /// `gradients` needs its own `seed=` for the same reason) and to gate
3562 /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
3563 fn libaom_encode_with(
3564 lavfi: &str,
3565 width: usize,
3566 height: usize,
3567 crf: u32,
3568 extra: &[&str],
3569 ) -> Option<Vec<u8>> {
3570 let mut args = vec![
3571 "-v",
3572 "error",
3573 "-f",
3574 "lavfi",
3575 "-i",
3576 lavfi,
3577 "-frames:v",
3578 "1",
3579 "-pix_fmt",
3580 "yuv420p",
3581 "-c:v",
3582 "libaom-av1",
3583 ];
3584 let crf_str = crf.to_string();
3585 args.extend(["-crf", &crf_str]);
3586 args.extend([
3587 "-cpu-used",
3588 "8",
3589 "-enable-rect-partitions",
3590 "0",
3591 "-enable-ab-partitions",
3592 "0",
3593 "-enable-1to4-partitions",
3594 "0",
3595 "-enable-angle-delta",
3596 "0",
3597 "-enable-cfl-intra",
3598 "0",
3599 ]);
3600 args.extend(extra.iter().copied());
3601 args.extend(["-f", "obu", "-"]);
3602 let out = Command::new("ffmpeg")
3603 .args(&args)
3604 .stdin(Stdio::null())
3605 .stdout(Stdio::piped())
3606 .stderr(Stdio::piped())
3607 .output()
3608 .expect("ffmpeg failed to run");
3609 if !out.status.success() {
3610 eprintln!(
3611 "ffmpeg refused to encode {lavfi} at {width}x{height}: {}",
3612 String::from_utf8_lossy(&out.stderr)
3613 );
3614 return None;
3615 }
3616 Some(out.stdout)
3617 }
3618
3619 /// The end-to-end gate: two real libaom-av1 configs, decoded with
3620 /// [`decode_stream`] and checked against ffmpeg's own decode of the same
3621 /// bytes. Not every config this encoder writes decodes yet (partitions
3622 /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the
3623 /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the
3624 /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this
3625 /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx
3626 /// types on gradient content.
3627 #[test]
3628 fn a_real_libaom_stream_with_adst_decodes_end_to_end() {
3629 if !have_ffmpeg() {
3630 eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg");
3631 return;
3632 }
3633 let configs: [(String, usize, usize, u32); 2] = [
3634 ("testsrc2=size=64x64:rate=1".to_string(), 64, 64, 15),
3635 (gradients_source(42, 64, 64, "rate=1"), 64, 64, 15),
3636 ];
3637 let mut verdicts = Vec::new();
3638 for (lavfi, width, height, crf) in configs {
3639 let lavfi = lavfi.as_str();
3640 let Some(stream) = libaom_encode(lavfi, width, height, crf) else {
3641 verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode"));
3642 continue;
3643 };
3644 match decode_stream(&stream) {
3645 Ok(frames) => {
3646 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3647 let matches = frames[0].y == ffmpeg_frames[0].y
3648 && frames[0].u == ffmpeg_frames[0].u
3649 && frames[0].v == ffmpeg_frames[0].v;
3650 verdicts.push(format!(
3651 "{lavfi}: decoded, {} ffmpeg's own decode",
3652 if matches { "MATCHES" } else { "MISMATCHES" }
3653 ));
3654 // Not a hard `assert!`: libaom's own mode decisions at
3655 // `cpu-used 8` are not observed stable run-to-run on this
3656 // box (multi-threaded RD search), so a run that happens
3657 // to land on a still-unsupported syntax element (e.g. a
3658 // partition below 16x16, a separate round-2 gap) can
3659 // decode without erroring yet disagree -- that failure
3660 // mode belongs to those other gaps, not to this round's
3661 // ADST wiring, and the eprintln below reports it either
3662 // way rather than hiding it.
3663 }
3664 Err(e) => {
3665 verdicts.push(format!("{lavfi}: still refuses ({e})"));
3666 }
3667 }
3668 }
3669 eprintln!("libaom ADST end-to-end verdicts:");
3670 for v in &verdicts {
3671 eprintln!(" {v}");
3672 }
3673 }
3674
3675 /// Hardened past the report-only test above: a real libaom-av1 gradients
3676 /// stream, pinned deterministic (`gradients`' own `seed=`, plus
3677 /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search
3678 /// cannot pick a different mode set run to run) and with CDEF turned off
3679 /// (this decoder's tile path never applies that in-loop filter -- see
3680 /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on
3681 /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's
3682 /// `-enable-cdef 0` keeps this fixture out of that gap rather than this
3683 /// test working around it). Asserts pixel-exact against ffmpeg's own
3684 /// decode of the identical bytes, not just "decoded without error".
3685 #[test]
3686 fn a_real_libaom_gradients_stream_decodes_pixel_exact() {
3687 if !have_ffmpeg() {
3688 eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg");
3689 return;
3690 }
3691 let (width, height) = (64, 64);
3692 let stream = libaom_encode_with(
3693 &gradients_source(42, width, height, "rate=1"),
3694 width,
3695 height,
3696 15,
3697 &[
3698 "-threads",
3699 "1",
3700 "-row-mt",
3701 "0",
3702 "-tile-columns",
3703 "0",
3704 "-tile-rows",
3705 "0",
3706 "-enable-cdef",
3707 "0",
3708 ],
3709 )
3710 .expect("ffmpeg encode");
3711 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
3712 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3713 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
3714 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
3715 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
3716 }
3717
3718 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at
3719 /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single*
3720 /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB
3721 /// is never CFL-eligible itself, only its <=32x32 partitions, and
3722 /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search
3723 /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed
3724 /// lane-av1real r2), so no fixture at that size exercises CfL at all.
3725 /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and
3726 /// lane-av1real r2 found `gradients` there reliably selects
3727 /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there
3728 /// stays DC. Proves the CfL port this round added, not just DC-chroma
3729 /// decode: pixel-exact against ffmpeg's own decode, not just "decoded".
3730 ///
3731 #[test]
3732 fn a_real_libaom_cfl_stream_decodes_pixel_exact() {
3733 if !have_ffmpeg() {
3734 eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg");
3735 return;
3736 }
3737 let (width, height) = (32, 32);
3738 let stream = libaom_encode_with(
3739 &gradients_source(42, width, height, "rate=1"),
3740 width,
3741 height,
3742 15,
3743 &[
3744 "-threads",
3745 "1",
3746 "-row-mt",
3747 "0",
3748 "-tile-columns",
3749 "0",
3750 "-tile-rows",
3751 "0",
3752 "-enable-cdef",
3753 "0",
3754 ],
3755 )
3756 .expect("ffmpeg encode");
3757 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
3758 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3759 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
3760 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
3761 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
3762 }
3763
3764 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
3765 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
3766 /// proves `apply_cdef` itself, not just that this decoder still works
3767 /// when the filter never fires. Gradient content at a low crf reliably
3768 /// gives libaom something to dering. If a run happens to land on
3769 /// `cdef_bits > 0` (per-64x64 `cdef_idx`, still unimplemented -- see the
3770 /// refusal in `decode_stream`) the stream is skipped rather than failed:
3771 /// that gap is named by the refusal's own error text, not silently
3772 /// swallowed here.
3773 #[test]
3774 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
3775 if !have_ffmpeg() {
3776 eprintln!(
3777 "SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: no ffmpeg"
3778 );
3779 return;
3780 }
3781 let (width, height) = (64, 64);
3782 let stream = libaom_encode_with(
3783 &gradients_source(42, width, height, "rate=1"),
3784 width,
3785 height,
3786 30,
3787 &[
3788 "-threads",
3789 "1",
3790 "-row-mt",
3791 "0",
3792 "-tile-columns",
3793 "0",
3794 "-tile-rows",
3795 "0",
3796 ],
3797 )
3798 .expect("ffmpeg encode");
3799 match decode_stream(&stream) {
3800 Ok(frames) => {
3801 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3802 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (CDEF on)");
3803 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (CDEF on)");
3804 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (CDEF on)");
3805 }
3806 Err(e) => {
3807 eprintln!("SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: {e}");
3808 }
3809 }
3810 }
3811
3812 /// Path to a real `aomenc` build carrying the reference options this
3813 /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`,
3814 /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old
3815 /// to expose `enable-tx-size-search`/`loopfilter-control` through its
3816 /// own `-aom-params` passthrough (probed live: "Cannot find aom
3817 /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]
3818 /// shells out to the standalone binary instead of ffmpeg's libaom-av1
3819 /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the
3820 /// default dev-build path; the test skips (not fails) when neither this
3821 /// nor `ffmpeg` is present.
3822 fn aomenc_path() -> std::path::PathBuf {
3823 if let Some(p) = std::env::var_os("EC_AV1_AOMENC") {
3824 return std::path::PathBuf::from(p);
3825 }
3826 // The oracle used to live only under `/tmp`, which this box's tmpfs
3827 // guard reclaims -- when it did, all 20 aomenc gates below went
3828 // silently vacuous (SKIP, suite still green). The durable location
3829 // is provisioned by `scripts/build-aom-oracle.sh`; the `/tmp` path
3830 // stays last as a legacy fallback.
3831 let mut candidates = Vec::new();
3832 if let Some(home) = std::env::var_os("HOME") {
3833 candidates.push(std::path::PathBuf::from(&home).join(".cache/aom-oracle/build/aomenc"));
3834 }
3835 candidates.push("/tmp/libaom-src/build/encoder/aomenc".into());
3836 candidates
3837 .iter()
3838 .find(|p| p.is_file())
3839 .cloned()
3840 .unwrap_or_else(|| candidates.remove(0))
3841 }
3842
3843 /// Whether the aomenc oracle is present. Absence normally SKIPs (a
3844 /// checkout without the oracle should still run the rest of the suite),
3845 /// but `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure so a batch
3846 /// run cannot report green off 20 skipped gates.
3847 /// Where a pinned stream lives. `fixtures/` is a symlink to a durable
3848 /// directory outside the repo, so a pin captured in one session is still
3849 /// there in the next; a session scratchpad is not (tmpfs reaps it, and
3850 /// four pins were silently dead because of that).
3851 fn pin_dir() -> std::path::PathBuf {
3852 if let Some(p) = std::env::var_os("EC_AV1_PIN_DIR") {
3853 return std::path::PathBuf::from(p);
3854 }
3855 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3856 .join("../../fixtures")
3857 .canonicalize()
3858 .unwrap_or_else(|_| std::path::PathBuf::from("fixtures"))
3859 }
3860
3861 fn have_aomenc() -> bool {
3862 let present = aomenc_path().is_file();
3863 assert!(
3864 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
3865 "EC_AV1_REQUIRE_AOMENC is set but no aomenc at {} -- run scripts/build-aom-oracle.sh",
3866 aomenc_path().display()
3867 );
3868 present
3869 }
3870
3871 /// The instrumented `aomdec` beside the `aomenc` oracle
3872 /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`).
3873 fn aomdec_path() -> std::path::PathBuf {
3874 if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") {
3875 return std::path::PathBuf::from(p);
3876 }
3877 aomenc_path().with_file_name("aomdec")
3878 }
3879
3880 /// Decodes `stream` with both this decoder and the instrumented oracle
3881 /// `aomdec`, and compares EVERY decoded frame in DECODE order --
3882 /// including the hidden (`show_frame == 0`) alt-ref frames no other gate
3883 /// in this repo can see, because `decode_stream` only pushes shown
3884 /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames
3885 /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces
3886 /// only as drift on some later shown frame, if at all).
3887 ///
3888 /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it
3889 /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in
3890 /// `decode_stream`, the oracle's in rung 12 of
3891 /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as
3892 /// u16 LE. Returns `(frames_decoded, hidden_frames)`.
3893 fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) {
3894 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
3895 let _ = std::fs::remove_dir_all(&dir);
3896 std::fs::create_dir_all(&dir).expect("scratch dir");
3897 let obu = dir.join("in.obu");
3898 std::fs::write(&obu, stream).expect("writing the stream");
3899 let aom_prefix = dir.join("aom");
3900 let out = Command::new(aomdec_path())
3901 .args(["--codec=av1", "-o"])
3902 .arg(dir.join("out.y4m"))
3903 .arg(&obu)
3904 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
3905 .stdin(Stdio::null())
3906 .stdout(Stdio::piped())
3907 .stderr(Stdio::piped())
3908 .output()
3909 .expect("aomdec failed to run");
3910 assert!(
3911 out.status.success(),
3912 "{name}: the oracle aomdec refused the stream: {}",
3913 String::from_utf8_lossy(&out.stderr)
3914 );
3915 let count_dumps = |prefix: &std::path::Path| -> usize {
3916 let mut n = 0usize;
3917 while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
3918 n += 1;
3919 }
3920 n
3921 };
3922 let oracle_frames = count_dumps(&aom_prefix);
3923 assert!(
3924 oracle_frames > 0,
3925 "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
3926 scripts/instrument-aom-oracle.sh is missing from {}",
3927 aomdec_path().display()
3928 );
3929 let ours_prefix = dir.join("ours");
3930 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
3931 let decoded = decode_stream(stream);
3932 set_final_dump_prefix(None);
3933 let shown = decoded
3934 .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"))
3935 .len();
3936 let our_frames = count_dumps(&ours_prefix);
3937 assert_eq!(
3938 our_frames, oracle_frames,
3939 "{name}: decoded {our_frames} frames in decode order, the oracle decoded \
3940 {oracle_frames}"
3941 );
3942 for i in 0..oracle_frames {
3943 let want =
3944 std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
3945 let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
3946 assert_eq!(
3947 got.len(),
3948 want.len(),
3949 "{name}: decode-order frame {i} is {} bytes, the oracle's is {}",
3950 got.len(),
3951 want.len()
3952 );
3953 if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) {
3954 let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
3955 panic!(
3956 "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \
3957 hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \
3958 bytes differ -- stream pinned at {}",
3959 oracle_frames - shown,
3960 got[at],
3961 want[at],
3962 obu.display()
3963 );
3964 }
3965 }
3966 let hidden = oracle_frames - shown;
3967 let _ = std::fs::remove_dir_all(&dir);
3968 (oracle_frames, hidden)
3969 }
3970
3971 /// lane-hidden r2: the `--arnr-maxframes=0` SECOND ARM of an existing
3972 /// gate -- the gate's own recipe is never changed, this re-encodes the
3973 /// same fixture with libaom's temporal alt-ref filter switched off and
3974 /// runs [`decode_all_frames_vs_oracle`] on the result. Measured: with
3975 /// the filter at its default EVERY alt-ref recipe in this file emits
3976 /// ZERO hidden frames (the candidates are filtered away), so the
3977 /// hidden-frame compare on the gate's own stream is vacuous; this arm
3978 /// is what actually puts `show_frame == 0` frames on the wire.
3979 ///
3980 /// Runs at most once per gate name per process (the loop gates sweep
3981 /// dozens of attempts and each arm costs a full encode + two decodes).
3982 /// A stream this decoder refuses BY NAME skips the arm -- the arm is
3983 /// about hidden frames, not about that capability gap -- while a pixel
3984 /// mismatch is a hard failure raised inside the compare.
3985 fn hidden_arnr_arm(name: &str, y4m: &[u8], args: &[&str]) -> Option<(usize, usize)> {
3986 static ARMED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
3987 std::sync::OnceLock::new();
3988 if !ARMED
3989 .get_or_init(Default::default)
3990 .lock()
3991 .unwrap()
3992 .insert(name.to_string())
3993 {
3994 return None;
3995 }
3996 let mut arm: Vec<&str> = vec!["--arnr-maxframes=0"];
3997 arm.extend_from_slice(args);
3998 let mut child = Command::new(aomenc_path())
3999 .args(&arm)
4000 .stdin(Stdio::piped())
4001 .stdout(Stdio::piped())
4002 .stderr(Stdio::piped())
4003 .spawn()
4004 .expect("aomenc failed to start");
4005 child
4006 .stdin
4007 .take()
4008 .expect("aomenc stdin")
4009 .write_all(y4m)
4010 .expect("writing y4m to aomenc");
4011 let out = child.wait_with_output().expect("aomenc failed to run");
4012 assert!(
4013 out.status.success(),
4014 "{name} HIDDEN-ARM: aomenc refused its own recipe plus --arnr-maxframes=0: {}",
4015 String::from_utf8_lossy(&out.stderr)
4016 );
4017 let stream = out.stdout;
4018 match decode_stream(&stream) {
4019 Err(e) => {
4020 let msg = e.to_string();
4021 assert!(
4022 msg.contains("unsupported"),
4023 "{name} HIDDEN-ARM failed outright: {msg}"
4024 );
4025 eprintln!("{name} HIDDEN-ARM: skipped on a named refusal: {msg}");
4026 None
4027 }
4028 Ok(_) => Some(decode_all_frames_vs_oracle(&stream, &format!("{name}-arnr0"))),
4029 }
4030 }
4031
4032
4033 /// The repo's first hidden-frame pixel gate. Every other aomenc gate
4034 /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and
4035 /// both sides emit SHOWN frames only -- so an alt-ref frame that is
4036 /// decoded, stored into a reference slot and never displayed was, until
4037 /// this gate, never compared to anything (class
4038 /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the
4039 /// default `--lag-in-frames`, so they are full of exactly these frames.
4040 ///
4041 /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc
4042 /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's
4043 /// temporal filter on, this fixture's alt-ref candidates get filtered
4044 /// away and the encoder emits ZERO hidden frames (measured: 0 hidden
4045 /// with the filter on, 3 with it off), which would have made the gate
4046 /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so
4047 /// a recipe that stops producing hidden frames fails rather than skips.
4048 #[test]
4049 fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() {
4050 const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact";
4051 let _gate_lock = lock_gate_counters();
4052 if !have_ffmpeg() {
4053 eprintln!("SKIP {NAME}: no ffmpeg");
4054 return;
4055 }
4056 if !have_aomenc() {
4057 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4058 return;
4059 }
4060 for bit_depth in [8u32, 10u32] {
4061 let (width, height, frames) = (64usize, 64usize, 40usize);
4062 let duration = frames as f64 / 25.0;
4063 let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25");
4064 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
4065 let y4m = Command::new("ffmpeg")
4066 .args([
4067 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
4068 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
4069 ])
4070 .stdin(Stdio::null())
4071 .stdout(Stdio::piped())
4072 .stderr(Stdio::piped())
4073 .output()
4074 .expect("ffmpeg failed to run");
4075 assert!(
4076 y4m.status.success(),
4077 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
4078 String::from_utf8_lossy(&y4m.stderr)
4079 );
4080 let depth_arg = format!("--bit-depth={bit_depth}");
4081 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
4082 let mut child = Command::new(aomenc_path())
4083 .args([
4084 // lane-defon r1: the repo's only gate that decodes hidden
4085 // frames is also the only place a FORWARD KEYFRAME can be
4086 // proven -- a KEY frame with `show_frame == 0`, which is
4087 // exactly the shape this gate already compares in decode
4088 // order. On-values go before the base list (aomenc keeps
4089 // the FIRST occurrence of a repeated flag).
4090 "--enable-fwd-kf=1",
4091 "--fwd-kf-dist=8",
4092 "--codec=av1",
4093 "--passes=1",
4094 "--end-usage=q",
4095 "--cq-level=45",
4096 "--cpu-used=0",
4097 "--threads=1",
4098 "--row-mt=0",
4099 "--kf-max-dist=1000",
4100 "--enable-order-hint=1",
4101 "--auto-alt-ref=1",
4102 "--lag-in-frames=25",
4103 "--arnr-maxframes=0",
4104 &depth_arg,
4105 &input_depth_arg,
4106 // The same tool set every sibling inter gate pins -- the
4107 // open capability gaps (rect/AB partitions, warped/OBMC,
4108 // masked compound, palette, ...) are other lanes' work;
4109 // this gate is about hidden frames, not about them.
4110 "--enable-warped-motion=0",
4111 // OBMC stays off HERE (this gate is about hidden frames);
4112 // the tool's own coverage is the `obmc*` gates and, on a
4113 // 16x8/8x16 leaf, the `--enable-obmc=1` arm of
4114 // `..._with_a_16_level_rect_leaf_...` (lane-inter4 r4).
4115 "--enable-obmc=0",
4116 "--enable-masked-comp=0",
4117 "--enable-interintra-comp=0",
4118 "--enable-onesided-comp=0",
4119 "--enable-interintra-wedge=0",
4120 "--enable-smooth-interintra=0",
4121 "--enable-rect-partitions=0",
4122 "--enable-ab-partitions=0",
4123 "--enable-1to4-partitions=0",
4124 "--enable-filter-intra=0",
4125 "--enable-smooth-intra=0",
4126 "--enable-paeth-intra=0",
4127 "--enable-directional-intra=0",
4128 "--enable-angle-delta=0",
4129 "--enable-tx-size-search=0",
4130 "--enable-cdef=0",
4131 "--enable-restoration=0",
4132 "--max-partition-size=32",
4133 "--min-partition-size=32",
4134 "--enable-palette=0",
4135 "--enable-intrabc=0",
4136 "--enable-cfl-intra=0",
4137 "--enable-ref-frame-mvs=0",
4138 "--obu",
4139 "-o",
4140 "-",
4141 "-",
4142 ])
4143 .stdin(Stdio::piped())
4144 .stdout(Stdio::piped())
4145 .stderr(Stdio::piped())
4146 .spawn()
4147 .expect("aomenc failed to start");
4148 child
4149 .stdin
4150 .take()
4151 .expect("aomenc stdin")
4152 .write_all(&y4m.stdout)
4153 .expect("writing y4m to aomenc");
4154 let out = child.wait_with_output().expect("aomenc failed to run");
4155 assert!(
4156 out.status.success(),
4157 "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}",
4158 String::from_utf8_lossy(&out.stderr)
4159 );
4160 let stream = out.stdout;
4161 let fwd_kf_before = crate::decode::fwd_kf_hits();
4162 let (total, hidden) =
4163 decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit"));
4164 let fwd_kf = crate::decode::fwd_kf_hits() - fwd_kf_before;
4165 assert!(
4166 hidden >= 2,
4167 "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \
4168 {total} decoded -- the gate would be vacuous (class \
4169 gate-blind-to-hidden-frames)"
4170 );
4171 // lane-defon r1: `--enable-fwd-kf=1` is spelled on this recipe, so
4172 // a KEY frame with `show_frame == 0` must actually have been
4173 // decoded -- otherwise the on-value proves nothing.
4174 assert!(
4175 fwd_kf > 0,
4176 "{NAME}: the {bit_depth}-bit recipe decoded {total} frames ({hidden} hidden) but \
4177 zero forward keyframes -- --enable-fwd-kf=1 --fwd-kf-dist=8 never reached the \
4178 bitstream"
4179 );
4180 eprintln!(
4181 "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, {fwd_kf} \
4182 forward keyframes, all pixel-exact vs the oracle in decode order"
4183 );
4184 }
4185 }
4186
4187 /// A real `aomenc` filter-intra fixture: every other intra mode disabled
4188 /// (smooth/paeth/directional/angle-delta) and
4189 /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
4190 /// <=32x32 bound means `use_filter_intra` never reads at all, spec
4191 /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter
4192 /// intra on top -- `--loopfilter-control=0` is required too: this
4193 /// decoder has no in-loop deblocking filter at all, and libaom's default
4194 /// (on) smooths every block-boundary column, which first looked like a
4195 /// filter-intra math bug (mismatches straddling the 32-pixel block
4196 /// seam) until the recipe without it round-tripped byte-exact. Checks
4197 /// [`decode::filter_intra_hits`] actually moved (a process-global
4198 /// counter, so before/after rather than an absolute value) to prove the
4199 /// symbol fired, then pixel-exactness against ffmpeg's own decode of the
4200 /// identical bytes on every plane.
4201 #[test]
4202 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
4203 if !have_ffmpeg() {
4204 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no ffmpeg");
4205 return;
4206 }
4207 if !have_aomenc() {
4208 eprintln!(
4209 "SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no aomenc at {}",
4210 aomenc_path().display()
4211 );
4212 return;
4213 }
4214 let (width, height) = (64usize, 64usize);
4215 // Recipe-search hooks: with the encoder pinned to one thread the
4216 // stream is a deterministic function of (seed, cq), so a firing recipe
4217 // can be searched for without a rebuild.
4218 let fi_seed: u32 = std::env::var("EC_FI_SEED")
4219 .ok()
4220 .and_then(|v| v.parse().ok())
4221 .unwrap_or(42);
4222 let fi_source = gradients_source(fi_seed, 64, 64, "duration=0.04:rate=25");
4223 let fi_cq = std::env::var("EC_FI_CQ").unwrap_or_else(|_| "40".to_string());
4224 let fi_cq_arg = format!("--cq-level={fi_cq}");
4225 let y4m = Command::new("ffmpeg")
4226 .args([
4227 "-v",
4228 "error",
4229 "-f",
4230 "lavfi",
4231 "-i",
4232 &fi_source,
4233 "-pix_fmt",
4234 "yuv420p",
4235 "-f",
4236 "yuv4mpegpipe",
4237 "-",
4238 ])
4239 .stdin(Stdio::null())
4240 .stdout(Stdio::piped())
4241 .stderr(Stdio::piped())
4242 .output()
4243 .expect("ffmpeg failed to run");
4244 assert!(
4245 y4m.status.success(),
4246 "ffmpeg refused to generate the y4m fixture: {}",
4247 String::from_utf8_lossy(&y4m.stderr)
4248 );
4249 let mut child = Command::new(aomenc_path())
4250 .args([
4251 "--codec=av1",
4252 "--passes=1",
4253 "--end-usage=q",
4254 &fi_cq_arg,
4255 "--cpu-used=0",
4256 // Every sibling gate pins these; this one did not, and a
4257 // multi-threaded aomenc is not deterministic, so each run
4258 // encoded a slightly different stream and the gate flaked
4259 // against whichever features that run happened to pick.
4260 // Pinning them makes seed 42 mean one stream (class
4261 // `parallel-flake-is-attempt-selection`).
4262 "--threads=1",
4263 "--row-mt=0",
4264 "--enable-filter-intra=1",
4265 "--enable-smooth-intra=0",
4266 "--enable-paeth-intra=0",
4267 "--enable-directional-intra=0",
4268 "--enable-angle-delta=0",
4269 "--enable-tx-size-search=0",
4270 "--enable-cdef=0",
4271 "--max-partition-size=32",
4272 "--loopfilter-control=0",
4273 "--enable-palette=0",
4274 "--enable-intrabc=0",
4275 "--obu",
4276 "-o",
4277 "-",
4278 "-",
4279 ])
4280 .stdin(Stdio::piped())
4281 .stdout(Stdio::piped())
4282 .stderr(Stdio::piped())
4283 .spawn()
4284 .expect("aomenc failed to start");
4285 child
4286 .stdin
4287 .take()
4288 .expect("aomenc stdin")
4289 .write_all(&y4m.stdout)
4290 .expect("writing the y4m fixture to aomenc");
4291 let out = child.wait_with_output().expect("aomenc failed to run");
4292 assert!(
4293 out.status.success(),
4294 "aomenc refused the fixture: {}",
4295 String::from_utf8_lossy(&out.stderr)
4296 );
4297 let stream = out.stdout;
4298 let before = decode::filter_intra_hits();
4299 // `screen_content_tools_determination` (libaom encoder_utils.c) is a
4300 // real internal trial-encode/PSNR comparison, not a flag this CLI
4301 // exposes a knob for -- on this flat gradient fixture it lands on
4302 // `allow_screen_content_tools=0` most runs but occasionally trips
4303 // over its 0.9 dB threshold the other way even with palette/intrabc
4304 // both disabled. That is a genuine separate gap (`decode_stream`
4305 // never reads `intrabc`/`palette_mode_info`), not a filter-intra
4306 // regression, so it is skipped here exactly as
4307 // `a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact`
4308 // above skips its own still-unsupported-gap runs.
4309 let frames = match decode_stream(&stream) {
4310 Ok(frames) => frames,
4311 Err(e) => {
4312 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: {e}");
4313 return;
4314 }
4315 };
4316 assert!(
4317 decode::filter_intra_hits() > before,
4318 "use_filter_intra never fired decoding this stream"
4319 );
4320 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4321 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
4322 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
4323 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
4324 }
4325
4326 /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
4327 /// (SMPTE colour bars -- a handful of large flat luma regions, exactly
4328 /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s
4329 /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant
4330 /// value, so `DC_PRED` already nails every chroma block with zero
4331 /// residual and the encoder's own RD never has a reason to spend bits on
4332 /// a *UV* palette too (a real symbol this decoder still refuses --
4333 /// lane-palette r3's own scope is Y only). `smptebars` has no seed to
4334 /// vary, so the fixture is deterministic by construction; hashed twice
4335 /// below to prove it rather than assert it. `--enable-rect-partitions=0`
4336 /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the
4337 /// rect-strip screen-content refusal at `read_intra_mode_rect`
4338 /// (decode.rs ~2226) -- that refusal is this lane's own next milestone,
4339 /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the
4340 /// sibling-lane facts this charter paid for: a single 64x64 frame is one
4341 /// superblock either way, but pinning them keeps the recipe identical to
4342 /// every other gate in this file. HARD-asserts
4343 /// [`decode::palette_hits`] moved -- a stream that never reads a real
4344 /// palette block would refuse (or not) by construction without proving
4345 /// this milestone at all.
4346 ///
4347 /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed
4348 /// pixels did not match ffmpeg's decode of the same bytes even though
4349 /// every symbol read by `decode_color_index_map` checked line-for-line
4350 /// against the oracle and matched. r6's range trace (`compare-range-not-tell`)
4351 /// pinned the real cause: `decode_color_index_map` was called from the
4352 /// wrong syntax position -- inline right after the Y colours, instead of
4353 /// after the whole mode-info read (UV palette mode_info + `filter_intra`,
4354 /// `av1_visit_palette`'s real call order). r7 ported the UV palette
4355 /// mode_info read and moved the colour-index-map decode after
4356 /// `filter_intra`; this gate now asserts a real pixel match instead of
4357 /// the old named refusal.
4358 #[test]
4359 fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() {
4360 const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact";
4361 if !have_ffmpeg() {
4362 eprintln!("SKIP {NAME}: no ffmpeg");
4363 return;
4364 }
4365 if !have_aomenc() {
4366 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4367 return;
4368 }
4369 let source = "smptebars=size=64x64:rate=25";
4370 fn render(source: &str) -> Vec<u8> {
4371 Command::new("ffmpeg")
4372 .args([
4373 "-v",
4374 "error",
4375 "-f",
4376 "lavfi",
4377 "-i",
4378 source,
4379 "-vf",
4380 "hue=s=0",
4381 "-pix_fmt",
4382 "yuv420p",
4383 "-t",
4384 "0.04",
4385 "-f",
4386 "yuv4mpegpipe",
4387 "-",
4388 ])
4389 .stdin(Stdio::null())
4390 .stdout(Stdio::piped())
4391 .stderr(Stdio::piped())
4392 .output()
4393 .expect("ffmpeg failed to run")
4394 .stdout
4395 }
4396 let y4m_a = render(source);
4397 let y4m_b = render(source);
4398 assert_eq!(
4399 y4m_a, y4m_b,
4400 "smptebars must render byte-identical across two runs"
4401 );
4402 let y4m = y4m_a;
4403 let mut child = Command::new(aomenc_path())
4404 .args([
4405 "--codec=av1",
4406 "--passes=1",
4407 "--end-usage=q",
4408 "--cq-level=30",
4409 "--cpu-used=0",
4410 "--threads=1",
4411 "--row-mt=0",
4412 "--sb-size=64",
4413 "--tune-content=screen",
4414 "--enable-palette=1",
4415 "--enable-intrabc=0",
4416 "--enable-rect-partitions=0",
4417 "--enable-ab-partitions=0",
4418 "--enable-1to4-partitions=0",
4419 "--min-partition-size=32",
4420 "--max-partition-size=32",
4421 "--enable-filter-intra=0",
4422 "--enable-smooth-intra=0",
4423 "--enable-paeth-intra=0",
4424 "--enable-directional-intra=0",
4425 "--enable-angle-delta=0",
4426 "--enable-cfl-intra=0",
4427 "--enable-cdef=0",
4428 "--enable-restoration=0",
4429 "--enable-tx-size-search=0",
4430 "--loopfilter-control=0",
4431 "--obu",
4432 "-o",
4433 "-",
4434 "-",
4435 ])
4436 .stdin(Stdio::piped())
4437 .stdout(Stdio::piped())
4438 .stderr(Stdio::piped())
4439 .spawn()
4440 .expect("aomenc failed to start");
4441 child
4442 .stdin
4443 .take()
4444 .expect("aomenc stdin")
4445 .write_all(&y4m)
4446 .expect("writing y4m to aomenc");
4447 let out = child.wait_with_output().expect("aomenc failed to run");
4448 assert!(
4449 out.status.success(),
4450 "aomenc refused the fixture: {}",
4451 String::from_utf8_lossy(&out.stderr)
4452 );
4453 let stream = out.stdout;
4454 let before = decode::palette_hits();
4455 let frames = match decode_stream(&stream) {
4456 Ok(frames) => frames,
4457 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
4458 };
4459 assert!(
4460 decode::palette_hits() > before,
4461 "palette_y_mode never fired decoding this stream -- gate is vacuous"
4462 );
4463 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
4464 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
4465 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
4466 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
4467 }
4468
4469 /// lane-kf900 r3: the palette colour reader at BOTH bit depths.
4470 ///
4471 /// `read_palette_colors_y`/`_uv` (decode.rs, mirroring `decodemv.c:478`
4472 /// and `:509`) size every raw literal they read by the sequence's
4473 /// `bit_depth`: the first colour is `bit_depth` bits, `min_bits` is
4474 /// `bit_depth - 3` (Y/U) or `bit_depth - 4` (V), `range` starts at
4475 /// `1 << bit_depth`, and the clamp/wrap bound is `(1 << bit_depth) - 1`.
4476 /// Ours hardcoded 8, so every 10-bit palette block read TWO BITS TOO FEW
4477 /// per transmitted colour and silently decoded the rest of the tile from
4478 /// the wrong bit position.
4479 ///
4480 /// It was silent because raw literals are EQUIPROBABLE: at the ranges
4481 /// this content reaches an equiprobable read maps the msac range onto
4482 /// itself (62728 -> 31364 -> renormalised 62728), so a cross-decoder
4483 /// RANGE ladder stays bit-identical straight through the miscount and
4484 /// only the decoded VALUE moves. Pinned on a 256x192 10-bit
4485 /// `--cq-level=59` stream whose first block is a 32x16 palette: aomdec's
4486 /// `EC_PAL` ladder and ours agreed on every range and disagreed on the
4487 /// very first colour index (0 vs 1); after the fix all 1024 `EC_PAL`
4488 /// lines of that block match aomdec line for line.
4489 ///
4490 /// The recipe is the 8-bit `..._with_palette_y_...` gate's, with the
4491 /// depth as the only variable, so a failure here is the depth and
4492 /// nothing else. HARD-asserts [`decode::palette_hits`] moved on each arm
4493 /// (a stream with no real palette block would prove nothing) and
4494 /// compares all three planes against ffmpeg's decode of the same bytes.
4495 #[test]
4496 fn a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit() {
4497 const NAME: &str = "a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit";
4498 if !have_ffmpeg() {
4499 eprintln!("SKIP {NAME}: no ffmpeg");
4500 return;
4501 }
4502 if !have_aomenc() {
4503 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4504 return;
4505 }
4506 let (width, height) = (64usize, 64usize);
4507 for depth in [8usize, 10] {
4508 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
4509 let render = || {
4510 Command::new("ffmpeg")
4511 .args([
4512 "-v", "error",
4513 "-f", "lavfi",
4514 "-i", "smptebars=size=64x64:rate=25",
4515 "-vf", "hue=s=0",
4516 "-pix_fmt", pix_fmt,
4517 "-strict", "-1",
4518 "-t", "0.04",
4519 "-f", "yuv4mpegpipe",
4520 "-",
4521 ])
4522 .stdin(Stdio::null())
4523 .stdout(Stdio::piped())
4524 .stderr(Stdio::piped())
4525 .output()
4526 .expect("ffmpeg failed to run")
4527 .stdout
4528 };
4529 let y4m_a = render();
4530 let y4m_b = render();
4531 assert_eq!(
4532 y4m_a, y4m_b,
4533 "{NAME}: smptebars must render byte-identical across two runs at {depth}-bit"
4534 );
4535 let y4m = y4m_a;
4536 let depth_arg = format!("--bit-depth={depth}");
4537 let input_depth_arg = format!("--input-bit-depth={depth}");
4538 let mut child = Command::new(aomenc_path())
4539 .args([
4540 "--codec=av1",
4541 "--passes=1",
4542 "--end-usage=q",
4543 "--cq-level=30",
4544 "--cpu-used=0",
4545 "--threads=1",
4546 "--row-mt=0",
4547 "--sb-size=64",
4548 "--tune-content=screen",
4549 "--enable-palette=1",
4550 "--enable-intrabc=0",
4551 "--enable-rect-partitions=0",
4552 "--enable-ab-partitions=0",
4553 "--enable-1to4-partitions=0",
4554 "--min-partition-size=32",
4555 "--max-partition-size=32",
4556 "--enable-filter-intra=0",
4557 "--enable-smooth-intra=0",
4558 "--enable-paeth-intra=0",
4559 "--enable-directional-intra=0",
4560 "--enable-angle-delta=0",
4561 "--enable-cfl-intra=0",
4562 "--enable-cdef=0",
4563 "--enable-restoration=0",
4564 "--enable-tx-size-search=0",
4565 "--loopfilter-control=0",
4566 "--limit=1",
4567 ])
4568 // Per-arm overrides go AFTER the base recipe: aomenc keeps the
4569 // LAST occurrence of a repeated flag.
4570 .args([&depth_arg, &input_depth_arg])
4571 .args(["--obu", "-o", "-", "-"])
4572 .stdin(Stdio::piped())
4573 .stdout(Stdio::piped())
4574 .stderr(Stdio::piped())
4575 .spawn()
4576 .expect("aomenc failed to start");
4577 child
4578 .stdin
4579 .take()
4580 .expect("aomenc stdin")
4581 .write_all(&y4m)
4582 .expect("writing y4m to aomenc");
4583 let out = child.wait_with_output().expect("aomenc failed to run");
4584 assert!(
4585 out.status.success(),
4586 "{NAME}: aomenc refused the {depth}-bit fixture: {}",
4587 String::from_utf8_lossy(&out.stderr)
4588 );
4589 let stream = out.stdout;
4590 let before = decode::palette_hits();
4591 let frames = match decode_stream(&stream) {
4592 Ok(frames) => frames,
4593 Err(e) => panic!("{NAME}: decode_stream refused the {depth}-bit stream: {e}"),
4594 };
4595 assert!(
4596 decode::palette_hits() > before,
4597 "{NAME}: no real palette block at {depth}-bit -- gate is vacuous"
4598 );
4599 let ffmpeg_frames = if depth == 10 {
4600 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
4601 } else {
4602 ffmpeg_decode_sequence(&stream, width, height, 1)
4603 };
4604 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma at {depth}-bit");
4605 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U at {depth}-bit");
4606 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V at {depth}-bit");
4607 }
4608 }
4609
4610 /// lane-pal8 r1, the gate for a palette on a SQUARE 8x8 LEAF.
4611 ///
4612 /// `read_palette_mode_info` (decodemv.c:567) reads `palette_y_mode` for
4613 /// every `DC_PRED` block whose `av1_get_palette_bsize_ctx`
4614 /// (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`, 0 at 8x8) exists, and
4615 /// `av1_decode_palette_tokens` (decodeframe.c:1135, `av1_visit_palette`)
4616 /// reads the colour-index map after the WHOLE mode-info read. Ours passed
4617 /// `None`/`&[]` from [`decode::decode_leaf8`], reading the mode symbol off
4618 /// CDF row 0 and refusing "a block that actually uses a palette (Y) --
4619 /// reconstruction is out of scope" the moment it fired -- and at 8 bit
4620 /// aomenc palettes SQUARE blocks, so with `--min-partition-size=8` every
4621 /// 8-bit screen-content stream stopped there (lane-kf900 r4's measurement).
4622 ///
4623 /// Sweeps both bit depths x cq 30/40/55 x `--enable-tx-size-search` 0/1 x
4624 /// two lavfi sources (+ a `--tile-columns=1` arm, per the neighbour-map
4625 /// rule: the palette bands are per-mi and tile-guarded). Key frame only
4626 /// (`--limit=1`): the inter frames of these recipes stop on OTHER lanes'
4627 /// open refusals (8x8 inter leaf chroma mode, inter 1:4 partitions).
4628 /// HARD-asserts the 8x8-leaf palette counter moved on the compared arms
4629 /// and that no arm mismatched, in or out of scope.
4630 #[test]
4631 fn a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact() {
4632 const NAME: &str = "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact";
4633 if !have_ffmpeg() {
4634 eprintln!("SKIP {NAME}: no ffmpeg");
4635 return;
4636 }
4637 if !have_aomenc() {
4638 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4639 return;
4640 }
4641 let (width, height) = (128usize, 128usize);
4642 let (mut leaf8_total, mut fired_arms, mut compared, mut frames_compared) =
4643 (0usize, 0u32, 0u32, 0usize);
4644 let (mut out_of_scope, mut out_of_scope_mismatch, mut refusals) = (0u32, 0u32, 0u32);
4645 let (mut sb_strip_total, mut sb_strip_arms) = (0usize, 0u32);
4646 // lane-t900 r34 LIFTED this shape; the counter stays so the gate
4647 // fails loudly if the refusal ever comes back.
4648 let mut sb_strip_refusals = 0u32;
4649 for src in ["testsrc2", "smptebars"] {
4650 for depth in [8usize, 10usize] {
4651 for cq in [30usize, 40, 55] {
4652 for txs in [0usize, 1] {
4653 for tiles in [0usize, 1] {
4654 let arm = format!("{src}-{depth}bit-cq{cq}-txs{txs}-tc{tiles}");
4655 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
4656 let size = format!("{src}=size={width}x{height}:rate=25");
4657 let render = || {
4658 let out = Command::new("ffmpeg")
4659 .args([
4660 "-v", "error", "-f", "lavfi", "-i", &size, "-t", "0.04",
4661 "-pix_fmt", pix_fmt, "-strict", "-1", "-f",
4662 "yuv4mpegpipe", "-",
4663 ])
4664 .stdin(Stdio::null())
4665 .stdout(Stdio::piped())
4666 .stderr(Stdio::piped())
4667 .output()
4668 .expect("ffmpeg failed to run");
4669 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
4670 out.stdout
4671 };
4672 let y4m_a = render();
4673 let y4m_b = render();
4674 assert_eq!(
4675 y4m_a, y4m_b,
4676 "{NAME}: {arm} must render byte-identical across two runs"
4677 );
4678 let y4m = y4m_a;
4679 let depth_arg = format!("--bit-depth={depth}");
4680 let input_depth_arg = format!("--input-bit-depth={depth}");
4681 let cq_arg = format!("--cq-level={cq}");
4682 let txs_arg = format!("--enable-tx-size-search={txs}");
4683 let tiles_arg = format!("--tile-columns={tiles}");
4684 let mut child = Command::new(aomenc_path())
4685 .args([
4686 "--codec=av1",
4687 "--passes=1",
4688 "--end-usage=q",
4689 "--cpu-used=0",
4690 "--threads=1",
4691 "--row-mt=0",
4692 "--lag-in-frames=0",
4693 "--limit=1",
4694 "--sb-size=64",
4695 "--tune-content=screen",
4696 "--enable-palette=1",
4697 "--enable-intrabc=0",
4698 "--min-partition-size=8",
4699 "--enable-cdef=0",
4700 "--enable-restoration=0",
4701 "--loopfilter-control=0",
4702 ])
4703 // aomenc keeps the LAST occurrence of a repeated flag,
4704 // so per-arm overrides go after the base recipe.
4705 .args([&depth_arg, &input_depth_arg, &cq_arg, &txs_arg, &tiles_arg])
4706 .args(["--obu", "-o", "-", "-"])
4707 .stdin(Stdio::piped())
4708 .stdout(Stdio::piped())
4709 .stderr(Stdio::piped())
4710 .spawn()
4711 .expect("aomenc failed to start");
4712 child
4713 .stdin
4714 .take()
4715 .expect("aomenc stdin")
4716 .write_all(&y4m)
4717 .or_else(|e| match e.kind() {
4718 std::io::ErrorKind::BrokenPipe => Ok(()),
4719 _ => Err(e),
4720 })
4721 .expect("writing y4m to aomenc");
4722 let out = child.wait_with_output().expect("aomenc failed to run");
4723 assert!(
4724 out.status.success(),
4725 "{NAME}: aomenc refused {arm}: {}",
4726 String::from_utf8_lossy(&out.stderr)
4727 );
4728 let stream = out.stdout;
4729 decode::reset_palette_leaf8_hits();
4730 decode::reset_palette_sb_strip_hits();
4731 let decoded = decode_stream(&stream);
4732 let leaf8 = decode::palette_leaf8_hits();
4733 let sb_strip = decode::palette_sb_strip_hits();
4734 leaf8_total += leaf8;
4735 sb_strip_total += sb_strip;
4736 match decoded {
4737 Ok(frames) => {
4738 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
4739 let theirs = if depth == 10 {
4740 ffmpeg_decode_sequence_10bit(
4741 &stream,
4742 width,
4743 height,
4744 frames.len(),
4745 )
4746 } else {
4747 ffmpeg_decode_sequence(&stream, width, height, frames.len())
4748 };
4749 assert_eq!(
4750 frames.len(),
4751 theirs.len(),
4752 "{NAME}: {arm} frame count"
4753 );
4754 let mut same = true;
4755 for (i, (ours, ref_f)) in
4756 frames.iter().zip(theirs.iter()).enumerate()
4757 {
4758 let ok = ours.y == ref_f.y
4759 && ours.u == ref_f.u
4760 && ours.v == ref_f.v;
4761 if !ok {
4762 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
4763 }
4764 same &= ok;
4765 frames_compared += 1;
4766 }
4767 compared += 1;
4768 if sb_strip > 0 {
4769 sb_strip_arms += 1;
4770 assert!(
4771 same,
4772 "{NAME}: {arm} decoded {sb_strip} non-skip palette \
4773 block(s) on a superblock-level strip and did not \
4774 match ffmpeg"
4775 );
4776 }
4777 if leaf8 > 0 || sb_strip > 0 {
4778 fired_arms += 1;
4779 assert!(
4780 same,
4781 "{NAME}: {arm} decoded {leaf8} 8x8-leaf palette \
4782 block(s) and did not match ffmpeg"
4783 );
4784 } else {
4785 out_of_scope += 1;
4786 if !same {
4787 out_of_scope_mismatch += 1;
4788 }
4789 }
4790 eprintln!(
4791 "{NAME}: {arm} {} frame(s), {leaf8} 8x8-leaf palette \
4792 block(s), {sb_strip} superblock-strip palette \
4793 block(s), exact={same}",
4794 frames.len()
4795 );
4796 }
4797 Err(e) => {
4798 let msg = e.to_string();
4799 assert!(
4800 msg.contains("unsupported"),
4801 "{NAME}: {arm} decode failed: {e}"
4802 );
4803 // Named, counted, never turned into a skip.
4804 if msg.contains("superblock-level HORZ/VERT strip") {
4805 sb_strip_refusals += 1;
4806 }
4807 eprintln!("{NAME}: {arm} REFUSED: {e}");
4808 refusals += 1;
4809 }
4810 }
4811 }
4812 }
4813 }
4814 }
4815 }
4816 eprintln!(
4817 "{NAME}: {leaf8_total} 8x8-leaf palette block(s) across {fired_arms} arm(s), \
4818 {compared} arms compared ({frames_compared} frames), {sb_strip_total} \
4819 superblock-strip palette block(s) across {sb_strip_arms} arm(s), \
4820 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
4821 {refusals} refused ({sb_strip_refusals} superblock-strip palette)"
4822 );
4823 assert!(
4824 leaf8_total > 0 && fired_arms > 0,
4825 "{NAME}: gate is vacuous -- no compared arm decoded an 8x8-leaf palette block"
4826 );
4827 assert_eq!(
4828 sb_strip_refusals, 0,
4829 "{NAME}: the superblock-strip palette refusal is back (lane-t900 r34 lifted it)"
4830 );
4831 assert!(
4832 sb_strip_arms > 0 && sb_strip_total > 0,
4833 "{NAME}: no arm decoded a non-skip palette block on a superblock-level strip -- \
4834 the shape r34 lifted is no longer exercised"
4835 );
4836 assert_eq!(
4837 out_of_scope_mismatch, 0,
4838 "{NAME}: an out-of-scope arm mismatched ffmpeg -- a defect, never a skip"
4839 );
4840 assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact");
4841 }
4842
4843 /// lane-kf900 r5, the gate for the rect-strip `use_intrabc` read.
4844 ///
4845 /// `av1_allow_intrabc` is a FRAME-level test (`decodemv.c:892`,
4846 /// `read_intra_frame_mode_info`): on an intra frame whose header set
4847 /// `allow_intrabc`, EVERY intra block reads a `use_intrabc` symbol right
4848 /// after `skip`/`cdef`/`delta_q` and before `mbmi->mode`. There is no
4849 /// block-shape term, so rect strips read it exactly like square leaves --
4850 /// `read_intra_mode_rect` never did, and the arithmetic decoder desynced
4851 /// at the FIRST symbol of the first rect block of every
4852 /// `--tune-content=screen` key frame (measured: `testsrc2` 256x192 cq59
4853 /// 8-bit decoded "OK" with all 49152 luma samples wrong).
4854 ///
4855 /// Arm 0 is that recipe at cq50 without palette: its rect strips really do
4856 /// use intrabc, which this decoder cannot reconstruct, so it must stop on
4857 /// the NAMED refusal instead of emitting a wrong frame -- and it must have
4858 /// read the symbol to get there.
4859 /// Arm 1 is the same recipe without palette and without tx-size search --
4860 /// it decodes the whole frame, reading the symbol dozens of times.
4861 /// Arm 2 is a screen-tools key frame whose header does NOT set
4862 /// `allow_intrabc` (cq63): it stays pixel-exact, proving the new read is
4863 /// not taken when libaom does not write it.
4864 ///
4865 /// PIXEL RESIDUE (open, lane-kf900 r5): arm 1's frame is entropy-exact
4866 /// against the instrumented aomdec for 429 mode-ladder elements and then
4867 /// diverges inside the DV read of a SQUARE intrabc block at mi(32,44), so
4868 /// its pixels are not compared here. That is a separate defect in
4869 /// `read_intrabc_dv`, not in the read this gate covers.
4870 #[test]
4871 fn a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips() {
4872 const NAME: &str = "a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips";
4873 if !have_ffmpeg() {
4874 eprintln!("SKIP {NAME}: no ffmpeg");
4875 return;
4876 }
4877 if !have_aomenc() {
4878 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4879 return;
4880 }
4881 let (width, height) = (256usize, 192usize);
4882 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
4883 // must_read_use_intrabc)
4884 const TS: &str = "testsrc2=s=256x192:r=25";
4885 const SB: &str = "smptebars=size=256x192:rate=25";
4886 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
4887 // must_read_use_intrabc_on_a_rect_strip)
4888 let arms: [(&str, &str, &[&str], bool, bool); 8] = [
4889 ("testsrc2-cq50-txs0", TS, &["--cq-level=50", "--enable-palette=0", "--enable-tx-size-search=0"], true, true),
4890 ("smptebars-cq40-txs0", SB, &["--cq-level=40", "--enable-palette=0", "--enable-tx-size-search=0"], false, false),
4891 ("smptebars-cq45-txs0", SB, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=0"], false, true),
4892 ("smptebars-cq45-txs1", SB, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=1"], false, false),
4893 ("smptebars-cq50-txs1", SB, &["--cq-level=50", "--enable-palette=0", "--enable-tx-size-search=1"], false, false),
4894 ("smptebars-cq55-txs0", SB, &["--cq-level=55", "--enable-palette=0", "--enable-tx-size-search=0"], false, false),
4895 ("testsrc2-cq63-txs1", TS, &["--cq-level=63", "--enable-palette=0", "--enable-tx-size-search=1"], false, false),
4896 // lane-kf900 r7: the 8x8-LEAF intrabc arm. Rect and 1:4
4897 // partitions off (so no rect strip refuses first), palette on,
4898 // `TxMode::Largest`: aomenc puts exactly one `use_intrabc` block
4899 // on a `BLOCK_8X8` leaf here, the shape `decode_leaf8` decoded as
4900 // ordinary intra before this round.
4901 ("testsrc2-cq55-leaf8", TS, &["--cq-level=55", "--enable-palette=1", "--enable-tx-size-search=0", "--enable-rect-partitions=0", "--enable-1to4-partitions=0"], false, false),
4902 ];
4903 let (mut reads_total, mut refused, mut frames_compared) = (0usize, 0u32, 0usize);
4904 let (mut blocks_total, mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) =
4905 (0usize, 0u32, 0u32, 0u32);
4906 let mut leaf8_total = 0usize;
4907 for (arm, src, extra, expect_refusal, must_read) in &arms {
4908 let render = || {
4909 let out = Command::new("ffmpeg")
4910 .args([
4911 "-v", "error", "-f", "lavfi", "-i", *src, "-t", "0.2", "-pix_fmt",
4912 "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
4913 ])
4914 .stdin(Stdio::null())
4915 .stdout(Stdio::piped())
4916 .stderr(Stdio::piped())
4917 .output()
4918 .expect("ffmpeg failed to run");
4919 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
4920 out.stdout
4921 };
4922 let y4m_a = render();
4923 let y4m_b = render();
4924 assert_eq!(y4m_a, y4m_b, "{NAME}: {arm} must render byte-identical across two runs");
4925 let y4m = y4m_a;
4926 let mut child = Command::new(aomenc_path())
4927 .args([
4928 "--codec=av1",
4929 "--bit-depth=8",
4930 "--input-bit-depth=8",
4931 "--passes=1",
4932 "--end-usage=q",
4933 "--cpu-used=0",
4934 "--lag-in-frames=0",
4935 "--kf-max-dist=1",
4936 "--limit=1",
4937 "--threads=1",
4938 "--tile-columns=0",
4939 "--enable-rect-partitions=1",
4940 "--enable-1to4-partitions=1",
4941 "--min-partition-size=8",
4942 "--max-partition-size=32",
4943 "--sb-size=64",
4944 // `allow_screen_content_tools` (and with it the frame
4945 // header's `allow_intrabc` bit) comes from here.
4946 "--tune-content=screen",
4947 // Spelled so `gate_coverage` counts the tool as exercised
4948 // rather than defaulted (class `tool-disabled-in-every-gate`).
4949 "--enable-intrabc=1",
4950 ])
4951 // aomenc keeps the LAST occurrence of a repeated flag.
4952 .args(*extra)
4953 .args(["--obu", "-o", "-", "-"])
4954 .stdin(Stdio::piped())
4955 .stdout(Stdio::piped())
4956 .stderr(Stdio::piped())
4957 .spawn()
4958 .expect("aomenc failed to start");
4959 child
4960 .stdin
4961 .take()
4962 .expect("aomenc stdin")
4963 .write_all(&y4m)
4964 .or_else(|e| match e.kind() {
4965 std::io::ErrorKind::BrokenPipe => Ok(()),
4966 _ => Err(e),
4967 })
4968 .expect("writing y4m to aomenc");
4969 let out = child.wait_with_output().expect("aomenc failed to run");
4970 assert!(
4971 out.status.success(),
4972 "{NAME}: aomenc refused {arm}: {}",
4973 String::from_utf8_lossy(&out.stderr)
4974 );
4975 let stream = out.stdout;
4976 decode::reset_rect_intrabc_reads();
4977 crate::decode::reset_intrabc_hits();
4978 crate::decode::reset_leaf8_intrabc_hits();
4979 let decoded = decode_stream(&stream);
4980 let reads = decode::rect_intrabc_reads();
4981 // Blocks that decoded `use_intrabc == 1` (square path), i.e. that
4982 // read a DV and predicted from the current frame -- distinct from
4983 // `reads`, which counts rect strips that merely READ the flag.
4984 let blocks = crate::decode::intrabc_hits();
4985 reads_total += reads;
4986 blocks_total += blocks;
4987 // The 8x8-leaf shape has its own counter: without it this gate's
4988 // other arms (all rect/32x32 intrabc) would stay green while the
4989 // leaf path decoded an intrabc block as ordinary intra (class
4990 // `gate-blind-to-feature`).
4991 let leaf8 = crate::decode::leaf8_intrabc_hits();
4992 leaf8_total += leaf8;
4993 if *arm == "testsrc2-cq55-leaf8" {
4994 assert!(
4995 leaf8 > 0,
4996 "{NAME}: {arm} decoded no intrabc block at an 8x8 leaf -- the arm no longer exercises `decode_leaf8`'s intrabc path"
4997 );
4998 }
4999 if *must_read {
5000 assert!(
5001 reads > 0,
5002 "{NAME}: {arm} read no use_intrabc symbol on a rect strip -- the \
5003 arm no longer exercises the fix (allow_intrabc not set?)"
5004 );
5005 }
5006 match decoded {
5007 Ok(frames) => {
5008 assert!(
5009 !*expect_refusal,
5010 "{NAME}: {arm} decoded a frame whose rect strips use intrabc -- \
5011 reconstruction is not ported, it must refuse by name"
5012 );
5013 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
5014 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
5015 assert_eq!(frames.len(), ffmpeg_frames.len(), "{NAME}: {arm} frame count");
5016 // EVERY frame is compared; an arm whose decode never hit an
5017 // intrabc block proves nothing about the DV/prediction path,
5018 // so it is counted OUT OF SCOPE -- but a mismatch there is
5019 // still a failure (`out_of_scope_mismatch == 0`), never a skip.
5020 let mut same = true;
5021 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
5022 let ok = ours.y == theirs.y && ours.u == theirs.u && ours.v == theirs.v;
5023 if !ok {
5024 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
5025 }
5026 same &= ok;
5027 frames_compared += 1;
5028 }
5029 if blocks > 0 {
5030 fired_arms += 1;
5031 assert!(
5032 same,
5033 "{NAME}: {arm} decoded {blocks} intrabc block(s) and did not match ffmpeg"
5034 );
5035 } else {
5036 out_of_scope += 1;
5037 if !same {
5038 out_of_scope_mismatch += 1;
5039 }
5040 }
5041 eprintln!(
5042 "{NAME}: {arm} {} frame(s), {reads} rect use_intrabc reads, \
5043 {blocks} intrabc block(s), exact={same}",
5044 frames.len()
5045 );
5046 }
5047 Err(e) => {
5048 let msg = e.to_string();
5049 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
5050 assert!(
5051 *expect_refusal,
5052 "{NAME}: {arm} was expected to decode, it refused: {e}"
5053 );
5054 assert!(
5055 msg.contains("intra block copy") || msg.contains("intrabc"),
5056 "{NAME}: {arm} refused for an unrelated reason: {e}"
5057 );
5058 eprintln!("{NAME}: {arm} REFUSED (expected): {e}");
5059 refused += 1;
5060 }
5061 }
5062 }
5063 eprintln!(
5064 "{NAME}: {reads_total} rect-strip use_intrabc symbol(s) read, \
5065 {blocks_total} intrabc block(s) decoded across {fired_arms} arm(s), \
5066 {refused} refused by name, {frames_compared} frames compared, \
5067 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched)"
5068 );
5069 eprintln!("{NAME}: {leaf8_total} intrabc block(s) at an 8x8 leaf");
5070 assert!(reads_total > 0, "{NAME}: gate is vacuous -- no arm read the symbol");
5071 assert!(
5072 leaf8_total > 0,
5073 "{NAME}: no arm decoded an intrabc block at an 8x8 leaf -- lane-kf900 r7's fix is untested"
5074 );
5075 assert!(
5076 blocks_total > 0 && fired_arms > 0,
5077 "{NAME}: gate is vacuous -- no compared arm actually decoded an intrabc block"
5078 );
5079 assert_eq!(refused, 1, "{NAME}: expected exactly one named intrabc refusal");
5080 assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact");
5081 assert_eq!(
5082 out_of_scope_mismatch, 0,
5083 "{NAME}: an arm without an intrabc block still mismatched ffmpeg"
5084 );
5085 }
5086
5087 /// lane-t900 r31: builds one `--tune-content=screen --enable-intrabc=1`
5088 /// key frame, 256x192 8-bit, from a deterministic lavfi source. `tiled`
5089 /// renders a 2x2 tiling of a 128x96 pattern -- exact spatial repetition,
5090 /// the content intra block copy exists for; `square_only` turns the rect
5091 /// and 1:4 partitions off so an intrabc block lands on a SQUARE block
5092 /// instead of stopping on the rect-strip intrabc refusal first.
5093 fn screen_intrabc_stream(src: &str, cq: &str, txs: &str, tiled: bool, square_only: bool) -> Vec<u8> {
5094 screen_intrabc_stream_with(src, cq, txs, tiled, square_only, &[])
5095 }
5096
5097 /// [`screen_intrabc_stream`] with per-arm flags appended AFTER the base
5098 /// recipe -- aomenc keeps the LAST occurrence of a repeated flag, so an
5099 /// arm can override `--sb-size` / `--min-partition-size` here.
5100 fn screen_intrabc_stream_with(
5101 src: &str,
5102 cq: &str,
5103 txs: &str,
5104 tiled: bool,
5105 square_only: bool,
5106 extra: &[&str],
5107 ) -> Vec<u8> {
5108 let mut ff = Command::new("ffmpeg");
5109 ff.args(["-v", "error", "-f", "lavfi", "-i", src, "-t", "0.2"]);
5110 if tiled {
5111 ff.args(["-vf", "tile=2x2"]);
5112 }
5113 let out = ff
5114 .args(["-pix_fmt", "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-"])
5115 .stdin(Stdio::null())
5116 .stdout(Stdio::piped())
5117 .stderr(Stdio::piped())
5118 .output()
5119 .expect("ffmpeg failed to run");
5120 assert!(out.status.success(), "ffmpeg failed for {src}");
5121 let y4m = out.stdout;
5122 let mut child = Command::new(aomenc_path())
5123 .args([
5124 "--codec=av1",
5125 "--bit-depth=8",
5126 "--input-bit-depth=8",
5127 "--passes=1",
5128 "--end-usage=q",
5129 "--cpu-used=0",
5130 "--lag-in-frames=0",
5131 "--kf-max-dist=1",
5132 "--limit=1",
5133 "--threads=1",
5134 "--tile-columns=0",
5135 "--min-partition-size=8",
5136 "--max-partition-size=32",
5137 "--sb-size=64",
5138 "--tune-content=screen",
5139 "--enable-intrabc=1",
5140 "--enable-palette=0",
5141 ])
5142 .args([format!("--cq-level={cq}"), format!("--enable-tx-size-search={txs}")])
5143 // aomenc keeps the LAST occurrence of a repeated flag.
5144 .args(if square_only {
5145 &["--enable-rect-partitions=0", "--enable-1to4-partitions=0"][..]
5146 } else {
5147 &[][..]
5148 })
5149 .args(extra)
5150 .args(["--obu", "-o", "-", "-"])
5151 .stdin(Stdio::piped())
5152 .stdout(Stdio::piped())
5153 .stderr(Stdio::piped())
5154 .spawn()
5155 .expect("aomenc failed to start");
5156 child
5157 .stdin
5158 .take()
5159 .expect("aomenc stdin")
5160 .write_all(&y4m)
5161 .or_else(|e| match e.kind() {
5162 std::io::ErrorKind::BrokenPipe => Ok(()),
5163 _ => Err(e),
5164 })
5165 .expect("writing y4m to aomenc");
5166 let enc = child.wait_with_output().expect("aomenc failed to run");
5167 assert!(
5168 enc.status.success(),
5169 "aomenc refused {src} cq={cq}: {}",
5170 String::from_utf8_lossy(&enc.stderr)
5171 );
5172 enc.stdout
5173 }
5174
5175 /// The sequence header's `use_128x128_superblock`, and how many frames of
5176 /// `stream` keep `allow_intrabc` -- the two bits the refusal "intrabc
5177 /// under a 128x128 superblock" is the conjunction of, read out of the
5178 /// headers rather than assumed from the flags handed to the encoder.
5179 fn sb128_and_intrabc_frames(stream: &[u8]) -> (bool, u32) {
5180 let mut parser = Av1Parser::new();
5181 let mut pos = 0usize;
5182 let (mut sb128, mut intrabc) = (false, 0u32);
5183 while pos < stream.len() {
5184 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
5185 break;
5186 };
5187 pos += obu.total_size.max(1);
5188 if let Some(seq) = parser.sequence_header() {
5189 sb128 = seq.use_128x128_superblock;
5190 }
5191 let header = match &obu.kind {
5192 ObuKind::Frame(h, _) => Some(&**h),
5193 ObuKind::FrameHeader(h) => Some(&**h),
5194 _ => None,
5195 };
5196 if header.is_some_and(|h| h.allow_intrabc) {
5197 intrabc += 1;
5198 }
5199 }
5200 (sb128, intrabc)
5201 }
5202
5203 /// lane-t900 r34, the WITNESS (r33 pinned it ignored) that intrabc under
5204 /// a 128x128 superblock decodes pixel-exact.
5205 ///
5206 /// All four arms of r33's census -- `--sb-size=128 --tune-content=screen
5207 /// --enable-intrabc=1` over both `--enable-tx-size-search` settings and
5208 /// two quantisers, on a 2x2 tiling of a 128x96 bar pattern (256x192,
5209 /// 8-bit, `--cpu-used=0 --min-partition-size=8 --max-partition-size=32`,
5210 /// rect and 1:4 off) -- code `use_128x128_superblock && allow_intrabc`.
5211 ///
5212 /// The lift was one constant: `av1_find_ref_dv` (mvref_common.c) takes
5213 /// `mib_size`, the SEQUENCE's superblock size in mi units, so the
5214 /// fallback DV is one 128-px superblock up (or 128 + `INTRABC_DELAY_PIXELS`
5215 /// left on the tile's first superblock row) under a 128 superblock, where
5216 /// [`crate::decode::read_intrabc_dv`] hardcoded 64. Every arm is compared
5217 /// to ffmpeg and the decoded-intrabc-block counter is asserted non-zero,
5218 /// so a stream that stopped using intrabc could not make this vacuous.
5219 #[test]
5220 fn an_sb128_screen_stream_with_intrabc_decodes_pixel_exact() {
5221 const NAME: &str = "an_sb128_screen_stream_with_intrabc_decodes_pixel_exact";
5222 if !have_ffmpeg() || !have_aomenc() {
5223 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
5224 return;
5225 }
5226 let (width, height) = (256usize, 192usize);
5227 let _guard = lock_gate_counters();
5228 let (mut blocks_total, mut frames_compared) = (0usize, 0u32);
5229 for txs in ["0", "1"] {
5230 for cq in ["30", "45"] {
5231 let arm = format!("sb128 txs={txs} cq={cq}");
5232 let stream = screen_intrabc_stream_with(
5233 "smptebars=size=128x96:rate=25",
5234 cq,
5235 txs,
5236 true,
5237 true,
5238 &["--sb-size=128"],
5239 );
5240 let (sb128, intrabc_frames) = sb128_and_intrabc_frames(&stream);
5241 assert!(
5242 sb128 && intrabc_frames > 0,
5243 "{NAME}: {arm} no longer codes sb128 + allow_intrabc"
5244 );
5245 crate::decode::reset_intrabc_hits();
5246 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm}: {e}"));
5247 let blocks = crate::decode::intrabc_hits();
5248 blocks_total += blocks;
5249 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
5250 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
5251 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
5252 assert!(
5253 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
5254 "{NAME}: {arm} frame {i} does not match ffmpeg"
5255 );
5256 frames_compared += 1;
5257 }
5258 eprintln!(
5259 "{NAME}: {arm} intrabc_frames={intrabc_frames} intrabc_blocks={blocks} \
5260 DECODED {} frame(s) exact",
5261 frames.len()
5262 );
5263 }
5264 }
5265 assert!(frames_compared > 0, "{NAME}: no frame was compared");
5266 assert!(
5267 blocks_total > 0,
5268 "{NAME}: gate is vacuous -- no arm decoded a single intrabc block"
5269 );
5270 }
5271
5272 /// lane-t900 r33, CENSUS for "a sub-8x8 leaf that uses intrabc".
5273 ///
5274 /// The `use_intrabc` symbol IS read at that reader for every sub-8x8 leaf
5275 /// of an `allow_intrabc` frame, so arrival is provable rather than
5276 /// assumed: the arms below force 4x4 leaves (`--min-partition-size=4`) on
5277 /// the exact-repetition screen content that keeps `allow_intrabc`, and the
5278 /// gate requires both counters -- `allow_intrabc` frames and decoded sub-8
5279 /// leaves -- to be non-zero before it reads anything into the refusal
5280 /// firing 0 times (class `gate-blind-to-feature`).
5281 #[test]
5282 fn a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal() {
5283 const NAME: &str = "a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal";
5284 if !have_ffmpeg() || !have_aomenc() {
5285 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
5286 return;
5287 }
5288 let (width, height) = (256usize, 192usize);
5289 let _guard = lock_gate_counters();
5290 let (mut premise_arms, mut reached, mut sub8_total, mut frames_compared) =
5291 (0u32, 0u32, 0usize, 0u32);
5292 for cq in ["30", "45"] {
5293 let arm = format!("sub8 cq={cq}");
5294 let stream = screen_intrabc_stream_with(
5295 "smptebars=size=128x96:rate=25",
5296 cq,
5297 "0",
5298 true,
5299 true,
5300 &["--min-partition-size=4"],
5301 );
5302 let (_, intrabc_frames) = sb128_and_intrabc_frames(&stream);
5303 if intrabc_frames > 0 {
5304 premise_arms += 1;
5305 }
5306 // No reset for this counter, so measure the delta (the gate lock
5307 // above keeps another gate's decode out of it).
5308 let sub8_before = crate::decode::sub8_split_hits();
5309 match decode_stream(&stream) {
5310 Ok(frames) => {
5311 let sub8 = crate::decode::sub8_split_hits() - sub8_before;
5312 sub8_total += sub8;
5313 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
5314 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
5315 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
5316 assert!(
5317 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
5318 "{NAME}: {arm} frame {i} does not match ffmpeg"
5319 );
5320 frames_compared += 1;
5321 }
5322 eprintln!(
5323 "{NAME}: {arm} intrabc_frames={intrabc_frames} sub8_leaves={sub8} \
5324 DECODED {} frame(s) exact",
5325 frames.len()
5326 );
5327 }
5328 Err(e) => {
5329 let msg = e.to_string();
5330 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
5331 if msg.contains("a sub-8x8 leaf that uses intrabc") {
5332 reached += 1;
5333 }
5334 sub8_total += crate::decode::sub8_split_hits() - sub8_before;
5335 eprintln!(
5336 "{NAME}: {arm} intrabc_frames={intrabc_frames} REFUSED: {e}"
5337 );
5338 }
5339 }
5340 }
5341 eprintln!(
5342 "{NAME}: {premise_arms}/2 arm(s) keep allow_intrabc, {sub8_total} sub-8 leaf/leaves \
5343 decoded, {reached} reach the refusal, {frames_compared} frame(s) exact"
5344 );
5345 assert!(
5346 premise_arms > 0,
5347 "{NAME}: census is vacuous -- no arm kept allow_intrabc, so the refusal's own \
5348 premise was never within reach"
5349 );
5350 assert!(
5351 sub8_total > 0,
5352 "{NAME}: census is vacuous -- no sub-8 leaf was decoded at all, so the \
5353 `use_intrabc` symbol this refusal guards was never read"
5354 );
5355 }
5356
5357 /// lane-t900 r33, CENSUS for "an intrabc block whose var-tx tree resolved
5358 /// to mixed leaf transform sizes" -- the residue lane-t900 r32 left when
5359 /// it lifted the intrabc `TX_MODE_SELECT` refusal.
5360 ///
5361 /// The tree is read in full, but the luma reconstruct loop it feeds is a
5362 /// UNIFORM grid of one square transform, so a tree that split unevenly
5363 /// would be reconstructed at the wrong stride. This census sweeps the
5364 /// quantiser across the exact-repetition recipe that reaches the tree at
5365 /// all and requires the tree to actually be read (`intrabc_vartx_hits`)
5366 /// before reading anything into the refusal firing 0 times.
5367 #[test]
5368 fn an_intrabc_vartx_census_measures_the_mixed_leaf_refusal() {
5369 const NAME: &str = "an_intrabc_vartx_census_measures_the_mixed_leaf_refusal";
5370 if !have_ffmpeg() || !have_aomenc() {
5371 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
5372 return;
5373 }
5374 let (width, height) = (256usize, 192usize);
5375 let _guard = lock_gate_counters();
5376 let (mut vartx_total, mut reached, mut frames_compared) = (0usize, 0u32, 0u32);
5377 for cq in ["20", "30", "45", "55"] {
5378 let arm = format!("vartx cq={cq}");
5379 let stream =
5380 screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
5381 let (select, premise) = tx_select_and_intrabc_frames(&stream);
5382 crate::decode::reset_intrabc_vartx_hits();
5383 match decode_stream(&stream) {
5384 Ok(frames) => {
5385 let vartx = crate::decode::intrabc_vartx_hits();
5386 vartx_total += vartx;
5387 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
5388 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
5389 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
5390 assert!(
5391 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
5392 "{NAME}: {arm} frame {i} does not match ffmpeg"
5393 );
5394 frames_compared += 1;
5395 }
5396 eprintln!(
5397 "{NAME}: {arm} select={select} premise={premise} vartx_blocks={vartx} \
5398 DECODED {} frame(s) exact",
5399 frames.len()
5400 );
5401 }
5402 Err(e) => {
5403 let msg = e.to_string();
5404 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
5405 vartx_total += crate::decode::intrabc_vartx_hits();
5406 if msg.contains("mixed leaf transform sizes") {
5407 reached += 1;
5408 }
5409 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
5410 }
5411 }
5412 }
5413 eprintln!(
5414 "{NAME}: {vartx_total} intrabc block(s) read the var-tx tree, {reached} resolved to \
5415 mixed leaves, {frames_compared} frame(s) exact"
5416 );
5417 assert!(
5418 vartx_total > 0,
5419 "{NAME}: census is vacuous -- no intrabc block read the var-tx tree at all"
5420 );
5421 assert_eq!(
5422 reached, 0,
5423 "{NAME}: an intrabc var-tx tree resolved to mixed leaves -- the refusal is a live \
5424 capability gap and needs a pinned witness, not this census"
5425 );
5426 }
5427
5428 /// How many frames of `stream` carry `tx_mode == Select`, and how many of
5429 /// those also keep `allow_intrabc` -- the frame-level premise of the
5430 /// refusal "an intrabc block under TxMode::Select", read out of the
5431 /// headers rather than assumed from the flags handed to the encoder
5432 /// (libaom clears `allow_intrabc` again when no block picked it,
5433 /// encodeframe.c:2336).
5434 fn tx_select_and_intrabc_frames(stream: &[u8]) -> (u32, u32) {
5435 let (mut select, mut premise) = (0u32, 0u32);
5436 let mut p = Av1Parser::new();
5437 let mut pos = 0usize;
5438 while pos < stream.len() {
5439 let obu = p.parse_obu(&stream[pos..]).expect("parse");
5440 pos += obu.total_size;
5441 let header = match &obu.kind {
5442 ObuKind::Frame(h, _) => Some(&**h),
5443 ObuKind::FrameHeader(h) => Some(&**h),
5444 _ => None,
5445 };
5446 if let Some(h) = header {
5447 if h.tx_mode == TxMode::Select {
5448 select += 1;
5449 if h.allow_intrabc {
5450 premise += 1;
5451 }
5452 }
5453 }
5454 }
5455 (select, premise)
5456 }
5457
5458 /// lane-t900 r31, CENSUS for the refusal "an intrabc block under
5459 /// TxMode::Select" -- which this gate DISPROVES as an "no encoder writes
5460 /// one" claim and pins as a real capability gap instead.
5461 ///
5462 /// The premise is reachable by the SPEC: `tx_mode` (5.9.21) is forced to
5463 /// `ONLY_4X4` only under `CodedLossless`, while `allow_intrabc` (5.9.2)
5464 /// needs `allow_screen_content_tools` at unscaled resolution -- two
5465 /// independent conditions. libaom leaves it open too: `select_tx_mode`
5466 /// (encodeframe.c:2355) never consults `allow_intrabc`, and the only
5467 /// downgrade to `TX_MODE_LARGEST` is `txb_split_count == 0`
5468 /// (encodeframe.c:2690).
5469 ///
5470 /// The measurement over 14 real `--tune-content=screen --enable-intrabc=1`
5471 /// recipes:
5472 ///
5473 /// * the 10 non-repeating arms never present the premise at all -- with
5474 /// `--enable-tx-size-search=1` the frame codes `TX_MODE_SELECT` but RD
5475 /// never picks intrabc, so libaom clears `allow_intrabc` again; with
5476 /// `=0` intrabc IS used and the frame is `TX_MODE_LARGEST`. That
5477 /// correlation, not any rule, is why earlier rounds never saw this;
5478 /// * the four EXACT-REPETITION arms (a 2x2 tiling of one 128x96 bar
5479 /// pattern) all code `allow_intrabc && tx_mode == Select`. Two of them
5480 /// stop on the older rect-strip intrabc refusal (the shape that fires
5481 /// first, class `refusal-hides-a-defect`), and the two with rect/1:4
5482 /// partitions off put intrabc on a SQUARE block: `cq=30` reaches THIS
5483 /// refusal by name, `cq=45`'s intrabc blocks are all `skip` and decode
5484 /// pixel-exact against ffmpeg.
5485 ///
5486 /// So the refusal is correct and load-bearing, exactly one arm reaches it,
5487 /// and the lift it names has a waiting witness:
5488 /// [`an_intrabc_block_under_tx_mode_select_decodes_pixel_exact`] (ignored
5489 /// until the intra path reads the inter var-tx tree for an intrabc block).
5490 #[test]
5491 fn an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal() {
5492 const NAME: &str =
5493 "an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal";
5494 if !have_ffmpeg() {
5495 eprintln!("SKIP {NAME}: no ffmpeg");
5496 return;
5497 }
5498 if !have_aomenc() {
5499 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5500 return;
5501 }
5502 const TS: &str = "testsrc2=s=256x192:r=25";
5503 const SB: &str = "smptebars=size=256x192:rate=25";
5504 const PB: &str = "pal75bars=size=256x192:rate=25";
5505 const TILE: &str = "smptebars=size=128x96:rate=25";
5506 let (width, height) = (256usize, 192usize);
5507 // (arm, source, cq, tx-size-search, tiled, square_only)
5508 let arms: [(&str, &str, &str, &str, bool, bool); 14] = [
5509 ("smptebars-cq40-txs1", SB, "40", "1", false, false),
5510 ("smptebars-cq45-txs1", SB, "45", "1", false, false),
5511 ("smptebars-cq55-txs1", SB, "55", "1", false, false),
5512 ("smptebars-cq63-txs1", SB, "63", "1", false, false),
5513 ("pal75bars-cq40-txs1", PB, "40", "1", false, false),
5514 ("pal75bars-cq55-txs1", PB, "55", "1", false, false),
5515 ("testsrc2-cq50-txs1", TS, "50", "1", false, false),
5516 ("testsrc2-cq63-txs1", TS, "63", "1", false, false),
5517 ("smptebars-cq45-txs0", SB, "45", "0", false, false),
5518 ("pal75bars-cq45-txs0", PB, "45", "0", false, false),
5519 ("tiled-cq30-txs1", TILE, "30", "1", true, false),
5520 ("tiled-cq45-txs1", TILE, "45", "1", true, false),
5521 ("tiled-square-cq30-txs1", TILE, "30", "1", true, true),
5522 // lane-t900 r32: both square arms are now ORDINARY census members
5523 // -- cq30 (unskipped intrabc, the inter var-tx tree) and cq45
5524 // (all-skip intrabc, `maxRectTxSize` with no symbol at all) decode
5525 // pixel-exact, so nothing here reaches the lifted refusal.
5526 ("tiled-square-cq45-txs1", TILE, "45", "1", true, true),
5527 ];
5528 let (mut select_arms, mut premise_arms, mut intrabc_arms, mut blocks_total) =
5529 (0u32, 0u32, 0u32, 0usize);
5530 let (mut refused_tx_select, mut frames_compared) = (0u32, 0usize);
5531 for (arm, src, cq, txs, tiled, square_only) in &arms {
5532 let stream = screen_intrabc_stream(src, cq, txs, *tiled, *square_only);
5533 let (select, premise) = tx_select_and_intrabc_frames(&stream);
5534 if select > 0 {
5535 select_arms += 1;
5536 }
5537 if premise > 0 {
5538 premise_arms += 1;
5539 }
5540 crate::decode::reset_intrabc_hits();
5541 let decoded = decode_stream(&stream);
5542 let blocks = crate::decode::intrabc_hits();
5543 blocks_total += blocks;
5544 if blocks > 0 {
5545 intrabc_arms += 1;
5546 }
5547 match decoded {
5548 Ok(frames) => {
5549 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
5550 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
5551 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
5552 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
5553 assert!(
5554 ours.y == ref_frame.y
5555 && ours.u == ref_frame.u
5556 && ours.v == ref_frame.v,
5557 "{NAME}: {arm} frame {i} does not match ffmpeg"
5558 );
5559 frames_compared += 1;
5560 }
5561 eprintln!(
5562 "{NAME}: {arm} select={select} premise={premise} {blocks} intrabc \
5563 block(s), {} frame(s) exact",
5564 frames.len()
5565 );
5566 }
5567 Err(e) => {
5568 let msg = e.to_string();
5569 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
5570 if msg.contains("an intrabc block under TxMode::Select") {
5571 refused_tx_select += 1;
5572 assert!(
5573 premise > 0,
5574 "{NAME}: {arm} reached the TxMode::Select intrabc refusal in a \
5575 frame that codes no such header"
5576 );
5577 } else {
5578 assert!(
5579 msg.contains("intra block copy"),
5580 "{NAME}: {arm} refused for an unrelated reason: {e}"
5581 );
5582 }
5583 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
5584 }
5585 }
5586 }
5587 eprintln!(
5588 "{NAME}: {select_arms}/{n} arm(s) code a TX_MODE_SELECT frame, {premise_arms} of \
5589 those keep allow_intrabc, {intrabc_arms} arm(s) decode an intrabc block \
5590 ({blocks_total} total), {refused_tx_select} reach the refusal, \
5591 {frames_compared} frame(s) compared exact",
5592 n = arms.len()
5593 );
5594 assert!(
5595 intrabc_arms > 0 && blocks_total > 0,
5596 "{NAME}: census is vacuous -- no arm decoded an intrabc block at all"
5597 );
5598 assert!(
5599 premise_arms > 0,
5600 "{NAME}: census is vacuous -- no arm coded a frame with both allow_intrabc and \
5601 tx_mode == Select, so the refusal's own premise was never within reach"
5602 );
5603 assert_eq!(
5604 refused_tx_select, 0,
5605 "{NAME}: lane-t900 r32 lifted this refusal -- an intrabc block now reads the \
5606 INTER tx-size syntax, so no arm may reach it again"
5607 );
5608 assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact");
5609 }
5610
5611 /// lane-t900 r31, the WAITING witness for the capability
5612 /// [`an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal`]
5613 /// pins: a real aomenc screen key frame whose intrabc block sits on a
5614 /// square block of a `TX_MODE_SELECT` frame, unskipped. libaom's
5615 /// `parse_decode_block` treats an intrabc block as `inter_block_tx`, so
5616 /// its transform size comes off the inter var-tx partition tree
5617 /// (`read_var_tx_size`), which this decoder reads nowhere on the intra
5618 /// path -- reading the intra `tx_depth` symbol instead desyncs.
5619 ///
5620 /// lane-t900 r32 closed both arms. A SKIPPED intrabc block reads no
5621 /// tx-size symbol at all (`allowSelect = !skip || !is_inter`, false for an
5622 /// intrabc block since libaom's `is_inter_block` counts one); reading the
5623 /// intra `tx_depth` for it consumed a symbol libaom never wrote and
5624 /// desynced the tile a whole block later, at the superblock corner
5625 /// (192,64) (class `equal-range-means-unread`). An UNSKIPPED one reads the
5626 /// inter var-tx tree (`read_var_tx_size`). r31's note that cq=45's blocks
5627 /// are all `skip` was read off that desynced decode: with the tx-size read
5628 /// corrected, cq=45 carries 3 unskipped intrabc blocks of 10 and cq=30
5629 /// carries 1 of 16, so both arms exercise both sides of the split.
5630 #[test]
5631 fn an_intrabc_block_under_tx_mode_select_decodes_pixel_exact() {
5632 const NAME: &str = "an_intrabc_block_under_tx_mode_select_decodes_pixel_exact";
5633 if !have_ffmpeg() || !have_aomenc() {
5634 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
5635 return;
5636 }
5637 let (width, height) = (256usize, 192usize);
5638 for cq in ["30", "45"] {
5639 let stream = screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
5640 let (select, premise) = tx_select_and_intrabc_frames(&stream);
5641 assert!(
5642 select > 0 && premise > 0,
5643 "{NAME}: cq={cq} no longer codes allow_intrabc under TX_MODE_SELECT \
5644 (select={select} premise={premise})"
5645 );
5646 crate::decode::reset_intrabc_hits();
5647 crate::decode::reset_intrabc_vartx_hits();
5648 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: cq={cq}: {e}"));
5649 let (blocks, vartx) =
5650 (crate::decode::intrabc_hits(), crate::decode::intrabc_vartx_hits());
5651 assert!(blocks > 0, "{NAME}: cq={cq} no longer decodes an intrabc block");
5652 // r31 recorded cq=45's intrabc blocks as ALL skip; that was read
5653 // off the desynced decode. With the tx-size read corrected both
5654 // arms carry unskipped ones (cq30 1 of 16, cq45 3 of 10), so both
5655 // must reach the var-tx tree or the gate is blind to the lift
5656 // (class `gate-blind-to-feature`).
5657 assert!(
5658 vartx > 0,
5659 "{NAME}: cq={cq} no longer reads the inter var-tx tree for an intrabc block"
5660 );
5661 eprintln!("{NAME}: cq={cq} {blocks} intrabc block(s), {vartx} through var-tx");
5662 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
5663 assert_eq!(frames.len(), theirs.len(), "{NAME}: cq={cq} frame count");
5664 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
5665 assert!(
5666 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
5667 "{NAME}: cq={cq} frame {i} does not match ffmpeg"
5668 );
5669 }
5670 }
5671 }
5672
5673 /// lane-kf900 r4, the gate for the two lifted palette refusals ("a 1:4
5674 /// rect strip that actually uses a palette (reconstruction is not ported
5675 /// at this shape)" and "a palette block on a HORZ/VERT intra strip below
5676 /// 16x16 (reconstruction not ported)"): real `aomenc` streams that put a
5677 /// palette on a RECT strip, decoded whole-frame pixel-exact against
5678 /// ffmpeg's own decode of the identical bytes, at 8 AND 10 bit.
5679 ///
5680 /// Arm 0 is the stream lane-kf900 r3 pinned and stopped on -- `testsrc2`
5681 /// 256x192, `--cq-level=59 --cpu-used=0 --min-partition-size=8
5682 /// --enable-rect-partitions=1 --enable-tx-size-search=1`, md5
5683 /// `e5f033d8fe34e4418d8cca3ac9d2b595` at 10 bit. Arms 1-2 force the shape
5684 /// on screen-like content with `--tune-content=screen --enable-palette=1
5685 /// --enable-1to4-partitions=1`.
5686 ///
5687 /// An attempt whose decode never hit a rect-strip palette block proves
5688 /// nothing about the lift, so it is counted OUT OF SCOPE rather than
5689 /// silently passing -- but a mismatch on one is still a failure
5690 /// (`out_of_scope_mismatch == 0`), and at least one attempt must fire the
5691 /// counter or the gate is vacuous.
5692 #[test]
5693 fn a_real_aomenc_rect_strip_palette_decodes_pixel_exact() {
5694 const NAME: &str = "a_real_aomenc_rect_strip_palette_decodes_pixel_exact";
5695 if !have_ffmpeg() {
5696 eprintln!("SKIP {NAME}: no ffmpeg");
5697 return;
5698 }
5699 if !have_aomenc() {
5700 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5701 return;
5702 }
5703 let (width, height) = (256usize, 192usize);
5704 let screen: &[&str] = &[
5705 "--tune-content=screen",
5706 "--enable-palette=1",
5707 "--enable-1to4-partitions=1",
5708 "--min-partition-size=8",
5709 ];
5710 // lane-kf900 r6: arms 3-4 are the palette + `--enable-tx-size-search=1`
5711 // shape whose neighbour palette lookup was SUB-granular -- a 16x8 strip
5712 // pair shares one 16px cell, so strip 1 read strip 0's palette size and
5713 // the colour cache came out short. Both were whole-frame wrong before
5714 // the mi-granular fix (`$HOME/.cache/kf900-r6/sweep.log`: smptebars
5715 // cq40/cq55 txs=1 pal=1 = DIFF).
5716 let screen_txs: &[&str] = &[
5717 "--tune-content=screen",
5718 "--enable-palette=1",
5719 "--enable-1to4-partitions=1",
5720 "--min-partition-size=8",
5721 "--max-partition-size=32",
5722 "--sb-size=64",
5723 "--enable-intrabc=1",
5724 "--enable-tx-size-search=1",
5725 ];
5726 let cq40: Vec<&str> = screen_txs.iter().copied().chain(["--cq-level=40"]).collect();
5727 let cq55: Vec<&str> = screen_txs.iter().copied().chain(["--cq-level=55"]).collect();
5728 let arms: [(&str, String, &[&str]); 5] = [
5729 ("testsrc2-pinned", "testsrc2=s=256x192:r=25".to_string(), &[]),
5730 ("testsrc2-screen", "testsrc2=s=256x192:r=25".to_string(), screen),
5731 ("smptebars-screen", "smptebars=size=256x192:rate=25".to_string(), screen),
5732 ("smptebars-screen-txs-cq40", "smptebars=size=256x192:rate=25".to_string(), &cq40),
5733 ("smptebars-screen-txs-cq55", "smptebars=size=256x192:rate=25".to_string(), &cq55),
5734 ];
5735 let (mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32, 0u32);
5736 let mut refused = 0u32;
5737 let mut fired_at_depth = [0u32; 2];
5738 let mut frames_compared = 0usize;
5739 for (arm, src, extra) in &arms {
5740 for depth in [8usize, 10] {
5741 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
5742 let render = || {
5743 let out = Command::new("ffmpeg")
5744 .args([
5745 "-v", "error", "-f", "lavfi", "-i", src.as_str(), "-t", "0.2",
5746 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
5747 ])
5748 .stdin(Stdio::null())
5749 .stdout(Stdio::piped())
5750 .stderr(Stdio::piped())
5751 .output()
5752 .expect("ffmpeg failed to run");
5753 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
5754 out.stdout
5755 };
5756 let y4m_a = render();
5757 let y4m_b = render();
5758 assert_eq!(
5759 y4m_a, y4m_b,
5760 "{NAME}: {arm} must render byte-identical across two runs at {depth}-bit"
5761 );
5762 let y4m = y4m_a;
5763 let depth_arg = format!("--bit-depth={depth}");
5764 let in_depth_arg = format!("--input-bit-depth={depth}");
5765 let mut child = Command::new(aomenc_path())
5766 .args(["--codec=av1"])
5767 .args([&depth_arg, &in_depth_arg])
5768 .args([
5769 "--passes=1",
5770 "--end-usage=q",
5771 "--cq-level=59",
5772 "--cpu-used=0",
5773 "--lag-in-frames=0",
5774 "--kf-max-dist=1",
5775 "--limit=1",
5776 "--threads=1",
5777 "--tile-columns=0",
5778 "--enable-tx-size-search=1",
5779 "--min-partition-size=8",
5780 "--enable-rect-partitions=1",
5781 ])
5782 // Per-arm overrides go AFTER the base recipe: aomenc keeps
5783 // the LAST occurrence of a repeated flag.
5784 .args(*extra)
5785 // The 8-bit twin of the pinned recipe picks a 128-root
5786 // HORZ partition, which this decoder still refuses by name
5787 // ("a 128x128 superblock HORZ/VERT or AB partition") --
5788 // an open refusal of another lane, unrelated to palette.
5789 // Pinning the superblock to 64 keeps the 8-bit arm on the
5790 // shape this gate is about; the 10-bit arms are the
5791 // untouched pinned recipe.
5792 .args(if depth == 8 { &["--sb-size=64"][..] } else { &[][..] })
5793 .args(["--obu", "-o", "-", "-"])
5794 .stdin(Stdio::piped())
5795 .stdout(Stdio::piped())
5796 .stderr(Stdio::piped())
5797 .spawn()
5798 .expect("aomenc failed to start");
5799 child
5800 .stdin
5801 .take()
5802 .expect("aomenc stdin")
5803 .write_all(&y4m)
5804 .or_else(|e| match e.kind() {
5805 // aomenc rejecting the input closes the pipe before we
5806 // finish writing; its own stderr below is the report.
5807 std::io::ErrorKind::BrokenPipe => Ok(()),
5808 _ => Err(e),
5809 })
5810 .expect("writing y4m to aomenc");
5811 let out = child.wait_with_output().expect("aomenc failed to run");
5812 assert!(
5813 out.status.success(),
5814 "{NAME}: aomenc refused {arm} at {depth}-bit: {}",
5815 String::from_utf8_lossy(&out.stderr)
5816 );
5817 let stream = out.stdout;
5818 let before = decode::rect4_palette_hits();
5819 let frames = match decode_stream(&stream) {
5820 Ok(frames) => frames,
5821 // A NAMED refusal is another lane's open shape (here: a
5822 // palette on an 8x8 SQUARE leaf, still out of scope), never
5823 // a pass -- the attempt is counted out of scope and the
5824 // per-depth firing assert below keeps the gate honest.
5825 Err(e) if e.to_string().contains("unsupported") => {
5826 eprintln!("{NAME}: {arm} {depth}-bit REFUSED: {e}");
5827 refused += 1;
5828 continue;
5829 }
5830 Err(e) => panic!("{NAME}: decode failed on {arm} at {depth}-bit: {e}"),
5831 };
5832 let fired = decode::rect4_palette_hits() - before;
5833 let ffmpeg_frames = if depth == 10 {
5834 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
5835 } else {
5836 ffmpeg_decode_sequence(&stream, width, height, frames.len())
5837 };
5838 assert_eq!(
5839 frames.len(),
5840 ffmpeg_frames.len(),
5841 "{NAME}: {arm} at {depth}-bit -- frame count"
5842 );
5843 assert!(!frames.is_empty(), "{NAME}: {arm} at {depth}-bit decoded no frame");
5844 // EVERY decode-order frame, all three planes.
5845 let mut exact = true;
5846 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
5847 if ours.y != theirs.y || ours.u != theirs.u || ours.v != theirs.v {
5848 exact = false;
5849 eprintln!("{NAME}: {arm} {depth}-bit frame {i} differs");
5850 }
5851 frames_compared += 1;
5852 }
5853 if fired > 0 {
5854 fired_arms += 1;
5855 fired_at_depth[usize::from(depth == 10)] += 1;
5856 assert!(
5857 exact,
5858 "{NAME}: {arm} at {depth}-bit has {fired} rect-strip palette block(s) \
5859 and does NOT decode pixel-exact"
5860 );
5861 } else {
5862 out_of_scope += 1;
5863 if !exact {
5864 out_of_scope_mismatch += 1;
5865 }
5866 }
5867 }
5868 }
5869 eprintln!(
5870 "{NAME}: {fired_arms} attempt(s) with a rect-strip palette block, \
5871 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
5872 {refused} refused, {frames_compared} frames compared, \
5873 fired 8-bit={} 10-bit={}",
5874 fired_at_depth[0], fired_at_depth[1]
5875 );
5876 // MEASURED 2026-09-02, every 8-bit attempt of these recipes: aomenc
5877 // puts its palettes on SQUARE blocks at 8 bit and every 8-bit stream
5878 // that reaches a rect strip with one lands on a palette shape still
5879 // out of scope (8x8 square leaf, or a 64x32/32x64 superblock strip
5880 // with a real transform). So the 8-bit arms here prove the DECODE
5881 // path, not the lift -- `fired_at_depth[0] == 0` is a known, reported
5882 // coverage gap and not a silent pass: the counter is printed.
5883 assert!(
5884 fired_at_depth[1] > 0,
5885 "{NAME}: no attempt put a palette on a rect strip \
5886 (8-bit={}, 10-bit={}) -- gate is vacuous",
5887 fired_at_depth[0],
5888 fired_at_depth[1]
5889 );
5890 assert!(fired_arms > 0, "{NAME}: gate is vacuous");
5891 assert_eq!(
5892 out_of_scope_mismatch, 0,
5893 "{NAME}: {out_of_scope_mismatch} attempt(s) without a rect-strip palette block \
5894 still mismatched -- an unrelated defect, not a SKIP"
5895 );
5896 }
5897
5898 /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through
5899 /// this crate's own 10-bit planes (`Picture` widened to `u16` in an
5900 /// earlier round) and checked pixel-exact against ffmpeg's own decode of
5901 /// the identical bytes via [`ffmpeg_decode_sequence_10bit`]. Confirms
5902 /// (hard-asserts, not just trusts) the sequence header this stream
5903 /// actually parses to says `bit_depth == 10` before trusting any pixel
5904 /// match -- a stream that silently fell back to 8-bit would still
5905 /// "match" trivially.
5906 #[test]
5907 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
5908 const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";
5909 if !have_ffmpeg() {
5910 eprintln!("SKIP {NAME}: no ffmpeg");
5911 return;
5912 }
5913 if !have_aomenc() {
5914 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5915 return;
5916 }
5917 let (width, height) = (64usize, 64usize);
5918 let y4m = Command::new("ffmpeg")
5919 .args([
5920 "-v",
5921 "error",
5922 "-f",
5923 "lavfi",
5924 "-i",
5925 &gradients_source(42, width, height, "duration=0.04:rate=25"),
5926 "-pix_fmt",
5927 "yuv420p10le",
5928 "-strict",
5929 "-1",
5930 "-t",
5931 "0.04",
5932 "-f",
5933 "yuv4mpegpipe",
5934 "-",
5935 ])
5936 .stdin(Stdio::null())
5937 .stdout(Stdio::piped())
5938 .stderr(Stdio::piped())
5939 .output()
5940 .expect("ffmpeg failed to run");
5941 assert!(
5942 y4m.status.success(),
5943 "ffmpeg failed to render the 10-bit fixture: {}",
5944 String::from_utf8_lossy(&y4m.stderr)
5945 );
5946 let mut child = Command::new(aomenc_path())
5947 .args([
5948 "--codec=av1",
5949 "--passes=1",
5950 "--end-usage=q",
5951 "--cq-level=30",
5952 "--cpu-used=0",
5953 "--threads=1",
5954 "--row-mt=0",
5955 "--sb-size=64",
5956 "--input-bit-depth=10",
5957 "--bit-depth=10",
5958 "--limit=1",
5959 "--obu",
5960 "-o",
5961 "-",
5962 "-",
5963 ])
5964 .stdin(Stdio::piped())
5965 .stdout(Stdio::piped())
5966 .stderr(Stdio::piped())
5967 .spawn()
5968 .expect("aomenc failed to start");
5969 child
5970 .stdin
5971 .take()
5972 .expect("aomenc stdin")
5973 .write_all(&y4m.stdout)
5974 .expect("writing y4m to aomenc");
5975 let out = child.wait_with_output().expect("aomenc failed to run");
5976 assert!(
5977 out.status.success(),
5978 "aomenc refused the 10-bit fixture: {}",
5979 String::from_utf8_lossy(&out.stderr)
5980 );
5981 let stream = out.stdout;
5982 // Confirm the sequence header this stream actually parses to before
5983 // trusting any pixel comparison below.
5984 let mut probe = Av1Parser::new();
5985 let mut pos = 0usize;
5986 while pos < stream.len() && probe.sequence_header().is_none() {
5987 let obu = probe.parse_obu(&stream[pos..]).unwrap();
5988 pos += obu.total_size;
5989 }
5990 let seq = probe
5991 .sequence_header()
5992 .expect("stream has a sequence header OBU");
5993 assert_eq!(
5994 seq.color_config.bit_depth, 10,
5995 "{NAME}: aomenc did not actually write a 10-bit sequence header"
5996 );
5997 let frames = match decode_stream(&stream) {
5998 Ok(frames) => frames,
5999 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"),
6000 };
6001 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
6002 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)");
6003 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)");
6004 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
6005 }
6006
6007 /// The 10-bit *inter* counterpart of the gate above: a real `aomenc`
6008 /// `yuv420p10le` sequence whose non-key frames are plain forward
6009 /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0
6010 /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate),
6011 /// decoded pixel-exact on every frame. 10-bit intra was proven exact by
6012 /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated.
6013 #[test]
6014 fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() {
6015 const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact";
6016 let _gate_lock = lock_gate_counters();
6017 if !have_ffmpeg() {
6018 eprintln!("SKIP {NAME}: no ffmpeg");
6019 return;
6020 }
6021 if !have_aomenc() {
6022 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6023 return;
6024 }
6025 let (width, height, frame_count) = (128usize, 64usize, 16usize);
6026 let y4m = Command::new("ffmpeg")
6027 .args([
6028 "-v",
6029 "error",
6030 "-f",
6031 "lavfi",
6032 "-i",
6033 &gradients_source(42, width, height, "duration=0.64:rate=25"),
6034 "-pix_fmt",
6035 "yuv420p10le",
6036 "-strict",
6037 "-1",
6038 "-t",
6039 "0.64",
6040 "-f",
6041 "yuv4mpegpipe",
6042 "-",
6043 ])
6044 .stdin(Stdio::null())
6045 .stdout(Stdio::piped())
6046 .stderr(Stdio::piped())
6047 .output()
6048 .expect("ffmpeg failed to run");
6049 assert!(
6050 y4m.status.success(),
6051 "ffmpeg failed to render the 10-bit fixture: {}",
6052 String::from_utf8_lossy(&y4m.stderr)
6053 );
6054 let mut child = Command::new(aomenc_path())
6055 .args([
6056 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
6057 // occurrence, so overrides go before the base list).
6058 "--loopfilter-control=1",
6059 "--codec=av1",
6060 "--passes=1",
6061 "--end-usage=q",
6062 "--cq-level=15",
6063 "--cpu-used=0",
6064 "--threads=1",
6065 "--row-mt=0",
6066 "--sb-size=64",
6067 "--input-bit-depth=10",
6068 "--bit-depth=10",
6069 "--lag-in-frames=0",
6070 "--auto-alt-ref=0",
6071 "--kf-max-dist=1000",
6072 "--error-resilient=1",
6073 "--aq-mode=0",
6074 "--deltaq-mode=0",
6075 "--enable-cdef=0",
6076 "--enable-rect-partitions=0",
6077 "--enable-ab-partitions=0",
6078 "--enable-1to4-partitions=0",
6079 "--enable-filter-intra=0",
6080 "--enable-smooth-intra=0",
6081 "--enable-paeth-intra=0",
6082 "--enable-directional-intra=0",
6083 "--enable-angle-delta=0",
6084 "--enable-tx-size-search=0",
6085 "--enable-cdef=1",
6086 "--enable-restoration=1",
6087 "--min-partition-size=16",
6088 "--max-partition-size=32",
6089 "--enable-palette=0",
6090 "--enable-intrabc=0",
6091 "--enable-cfl-intra=0",
6092 "--enable-ref-frame-mvs=0",
6093 "--obu",
6094 "-o",
6095 "-",
6096 "-",
6097 ])
6098 .stdin(Stdio::piped())
6099 .stdout(Stdio::piped())
6100 .stderr(Stdio::piped())
6101 .spawn()
6102 .expect("aomenc failed to start");
6103 child
6104 .stdin
6105 .take()
6106 .expect("aomenc stdin")
6107 .write_all(&y4m.stdout)
6108 .expect("writing y4m to aomenc");
6109 let out = child.wait_with_output().expect("aomenc failed to run");
6110 assert!(
6111 out.status.success(),
6112 "aomenc refused the 10-bit fixture: {}",
6113 String::from_utf8_lossy(&out.stderr)
6114 );
6115 let stream = out.stdout;
6116 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
6117 std::fs::write(dump, &stream).expect("dump stream");
6118 }
6119 let mut probe = Av1Parser::new();
6120 let mut pos = 0usize;
6121 while pos < stream.len() && probe.sequence_header().is_none() {
6122 let obu = probe.parse_obu(&stream[pos..]).unwrap();
6123 pos += obu.total_size;
6124 }
6125 assert_eq!(
6126 probe
6127 .sequence_header()
6128 .expect("stream has a sequence header OBU")
6129 .color_config
6130 .bit_depth,
6131 10,
6132 "{NAME}: aomenc did not actually write a 10-bit sequence header"
6133 );
6134 let before_deblock = decode::deblock_hits();
6135 let before_inter = decode::inter_pred_hits();
6136 let before_lr = crate::restoration::wiener_hits()
6137 + crate::restoration::sgrproj_hits()
6138 + crate::restoration::switchable_hits();
6139 let frames = match decode_stream(&stream) {
6140 Ok(frames) => frames,
6141 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"),
6142 };
6143 assert!(
6144 decode::inter_pred_hits() > before_inter,
6145 "{NAME}: no inter-predicted block decoded -- the gate proves nothing"
6146 );
6147 assert!(
6148 decode::deblock_hits() > before_deblock,
6149 "{NAME}: no deblocking edge fired -- raise cq-level"
6150 );
6151 // Loop restoration is where the 10-bit inter/intra defect lived
6152 // (lane-hbdinter r1: the self-guided box sums were never brought back
6153 // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened
6154 // to pick RESTORE_NONE would pass while proving nothing.
6155 assert!(
6156 crate::restoration::wiener_hits()
6157 + crate::restoration::sgrproj_hits()
6158 + crate::restoration::switchable_hits()
6159 > before_lr,
6160 "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level"
6161 );
6162 eprintln!(
6163 "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}",
6164 decode::inter_pred_hits() - before_inter,
6165 decode::deblock_hits() - before_deblock,
6166 decode::cdef_idx_hits(),
6167 crate::restoration::wiener_hits(),
6168 crate::restoration::sgrproj_hits(),
6169 );
6170 assert_eq!(frames.len(), frame_count);
6171 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count);
6172 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6173 if got.y != want.y || got.u != want.u || got.v != want.v {
6174 let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu");
6175 let _ = std::fs::write(&pin, &stream);
6176 let first = |a: &Vec<u16>, b: &Vec<u16>| {
6177 a.iter()
6178 .zip(b)
6179 .enumerate()
6180 .find(|(_, (x, y))| x != y)
6181 .map(|(k, (x, y))| (k, *x, *y))
6182 };
6183 panic!(
6184 "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}",
6185 first(&got.y, &want.y),
6186 first(&got.u, &want.u),
6187 first(&got.v, &want.v),
6188 pin.display()
6189 );
6190 }
6191 }
6192 }
6193
6194 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
6195 /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
6196 /// identical bytes (ffmpeg synthesizes grain by default -- no
6197 /// grain-disable flag is passed anywhere in this file). Proves the
6198 /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
6199 /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
6200 /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
6201 /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
6202 /// silent 8-bit fallback nor a stream aomenc emitted without
6203 /// `apply_grain` can make it pass vacuously.
6204 #[test]
6205 fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
6206 const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
6207 if !have_ffmpeg() {
6208 eprintln!("SKIP {NAME}: no ffmpeg");
6209 return;
6210 }
6211 if !have_aomenc() {
6212 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6213 return;
6214 }
6215 let (width, height) = (64usize, 64usize);
6216 let stream = encode_10bit_gradients(
6217 NAME,
6218 width,
6219 height,
6220 1,
6221 &["--film-grain-test=1", "--limit=1"],
6222 );
6223 assert_eq!(
6224 parsed_bit_depth(&stream),
6225 10,
6226 "{NAME}: aomenc did not actually write a 10-bit sequence header"
6227 );
6228 let mut probe = Av1Parser::new();
6229 let mut pos = 0usize;
6230 let mut saw_grain = false;
6231 while pos < stream.len() {
6232 let obu = probe.parse_obu(&stream[pos..]).unwrap();
6233 pos += obu.total_size;
6234 if let ObuKind::Frame(header, _) = obu.kind
6235 && header.film_grain.apply_grain
6236 {
6237 // A grain block whose scaling LUT is empty would blend a
6238 // zero delta into every pixel and let this gate pass without
6239 // the bit-depth math mattering at all.
6240 assert!(
6241 header.film_grain.num_y_points > 0,
6242 "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
6243 );
6244 saw_grain = true;
6245 }
6246 }
6247 assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
6248 let before = crate::film_grain::grain_hits();
6249 let frames = match decode_stream(&stream) {
6250 Ok(frames) => frames,
6251 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
6252 };
6253 assert!(
6254 crate::film_grain::grain_hits() > before,
6255 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
6256 );
6257 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
6258 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
6259 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
6260 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
6261 eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits());
6262 }
6263
6264 /// lane-t900 r29: `fixtures/superres_kf_cdef_lr_64x64.obu` is a real
6265 /// aomenc key frame (64x64 upscaled from a coded 43x64,
6266 /// `--superres-mode=1 --superres-denominator=12 --cpu-used=0 --sb-size=64
6267 /// --enable-cdef=1 --enable-restoration=1 --cq-level=32`) -- the first
6268 /// stream in this repo that runs BOTH in-loop filters under superres.
6269 ///
6270 /// The defect it pins: spec 7.16's upscale runs between CDEF and loop
6271 /// restoration (libaom `superres_post_decode`, `decodeframe.c`, called
6272 /// between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`),
6273 /// but this decoder ran the whole filter chain on the DOWNSCALED frame
6274 /// and upscaled last, in `stream.rs`. Loop restoration therefore filtered
6275 /// downscaled pixels with a unit grid sized from the downscaled width
6276 /// (1873 wrong samples, max 7, on this very stream). Class
6277 /// `wrong-stage-width`: every plane width in the filter chain is either
6278 /// the downscaled one (deblock, CDEF, and the mi grid all three walk) or
6279 /// the upscaled one (loop restoration's `av1_get_upsampled_plane_size`
6280 /// unit grid, `av1_loop_restoration_corners_in_sb`'s `mi_to_num_x`
6281 /// superres arm, and the pixel filters themselves); the sweep is every
6282 /// caller of `apply_deblock`/`apply_cdef`/`apply_loop_restoration` plus
6283 /// `RestorationGrid::new` and `read_lr`.
6284 #[test]
6285 fn a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact() {
6286 const NAME: &str =
6287 "a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact";
6288 let _gate_lock = lock_gate_counters();
6289 if !have_ffmpeg() {
6290 eprintln!("SKIP {NAME}: no ffmpeg");
6291 return;
6292 }
6293 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6294 .join("fixtures/superres_kf_cdef_lr_64x64.obu");
6295 let stream = std::fs::read(&path)
6296 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6297 let (width, height) = (64usize, 64usize);
6298 let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
6299 let frames = match decode_stream(&stream) {
6300 Ok(frames) => frames,
6301 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
6302 };
6303 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
6304 assert_eq!((frames[0].width, frames[0].height), (width, height));
6305 // class `gate-blind-to-feature`: the stream must actually upscale and
6306 // actually run a real restoration filter, or this gate proves nothing.
6307 assert!(
6308 crate::superres::superres_hits() > 0,
6309 "{NAME}: zero superres_hits -- the frame was never upscaled"
6310 );
6311 assert!(
6312 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
6313 "{NAME}: zero restoration units fired -- LR never ran under superres"
6314 );
6315 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
6316 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
6317 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
6318 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
6319 }
6320
6321 /// lane-filt1: `EC_AV1_FILTER_THREADS` splits every in-frame filter stage
6322 /// -- deblock (row bands for the vertical-edge pass, column bands for the
6323 /// horizontal one), CDEF (mi row bands), loop restoration (RU row bands)
6324 /// and film grain (32-pixel block rows) -- across scoped worker threads.
6325 /// A split is only legal if it is BYTE-EXACT, so this gate decodes two
6326 /// real aomenc streams at 1 and at 4 filter threads and compares every
6327 /// output frame's three planes.
6328 ///
6329 /// Between them the fixtures fire all four stages, and the firing
6330 /// counters are asserted rather than assumed (class `gate-blind-to-feature`):
6331 /// `superres_alltools_sb128_320x180.obu` is the 10-bit CDEF + loop
6332 /// restoration stream, `grain_cdef_lr_128x128.obu` a 128x128
6333 /// `--denoise-noise-level=25` stream whose frames carry film grain
6334 /// parameters (small enough that 4 bands is one block row each, which is
6335 /// what exercises the grain band's one-row `prelude` replay).
6336 /// lane-wave1 step (ii): the superblock-row wavefront
6337 /// (`EC_AV1_RECON_THREADS`) reconstructs every output frame byte for
6338 /// byte as the inline path does, on a hidden-ARF 10-bit stream (no-show
6339 /// frames, CfL, 128 superblocks) and on the two screen-content streams
6340 /// whose palette/intrabc blocks READ the current frame's pixels while
6341 /// parsing -- the sites that make the workers barrier.
6342 #[test]
6343 fn a_real_stream_reconstructs_identically_with_one_and_four_recon_threads() {
6344 const NAME: &str = "a_real_stream_reconstructs_identically_with_one_and_four_recon_threads";
6345 let _gate_lock = lock_gate_counters();
6346 for fixture in [
6347 "reelb_arf_witness.obu",
6348 "palette_screen_witness.obu",
6349 "palette_screen_witness_10bit.obu",
6350 ] {
6351 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6352 .join("fixtures")
6353 .join(fixture);
6354 let stream = std::fs::read(&path)
6355 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6356 crate::par::set_recon_threads(1);
6357 let one = match decode_stream(&stream) {
6358 Ok(frames) => frames,
6359 Err(e) => panic!("{NAME}: {fixture} refused at 1 recon thread: {e}"),
6360 };
6361 crate::par::set_recon_threads(4);
6362 let four = match decode_stream(&stream) {
6363 Ok(frames) => frames,
6364 Err(e) => {
6365 crate::par::set_recon_threads(1);
6366 panic!("{NAME}: {fixture} refused at 4 recon threads: {e}")
6367 }
6368 };
6369 crate::par::set_recon_threads(1);
6370 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
6371 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
6372 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
6373 assert_eq!(a.y, b.y, "{NAME}: {fixture} frame {i} luma differs at 4 recon threads");
6374 assert_eq!(a.u, b.u, "{NAME}: {fixture} frame {i} U differs at 4 recon threads");
6375 assert_eq!(a.v, b.v, "{NAME}: {fixture} frame {i} V differs at 4 recon threads");
6376 }
6377 }
6378 }
6379
6380 /// lane-memfix: the pool grows to the peak of `busy + queued` over the
6381 /// job tree and stops there. Before, a job running on a pool worker
6382 /// opened a SECOND pool on that worker's own thread-local -- one level
6383 /// per pipeline stage, none of them ever shrinking -- which is how a 4K
6384 /// decode at `(16, 4, 2)` reached 1038 live threads. Two decodes of the
6385 /// same stream: the count stays inside the composed setting and the
6386 /// second decode adds nothing (the ratchet is what cost the memory).
6387 #[test]
6388 fn the_worker_pool_stays_bounded_across_repeated_threaded_decodes() {
6389 const NAME: &str = "the_worker_pool_stays_bounded_across_repeated_threaded_decodes";
6390 let _gate_lock = lock_gate_counters();
6391 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6392 .join("fixtures")
6393 .join("superres_alltools_sb128_320x180.obu");
6394 let stream = std::fs::read(&path)
6395 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6396 crate::par::set_filter_threads(4);
6397 crate::par::set_recon_threads(2);
6398 let mut counts = [0usize; 2];
6399 let mut frames = [0usize; 2];
6400 for (i, slot) in counts.iter_mut().enumerate() {
6401 let mut n = 0usize;
6402 let r = decode_stream_with_threads(&stream, 4, |_, _, _| {
6403 n += 1;
6404 Ok(())
6405 });
6406 if let Err(e) = r {
6407 crate::par::set_filter_threads(1);
6408 crate::par::set_recon_threads(1);
6409 panic!("{NAME}: refused on decode {i}: {e}");
6410 }
6411 frames[i] = n;
6412 *slot = crate::par::pool_threads();
6413 }
6414 crate::par::set_filter_threads(1);
6415 crate::par::set_recon_threads(1);
6416 assert!(frames[0] > 1, "{NAME}: the fixture decoded {} frames, so nothing was threaded", frames[0]);
6417 // 4 frame workers x (recon 2 + filter 4) plus the two in-flight
6418 // slots `stream.rs` allows over the thread count, with room for the
6419 // show jobs -- 1038 was three orders past this.
6420 assert!(
6421 counts[1] <= 4 * (2 + 4) + 2 * 4,
6422 "{NAME}: the pool grew to {} threads at 4 frame / 4 filter / 2 recon",
6423 counts[1]
6424 );
6425 // The pool grows to `busy + queued`, so a loaded box can queue one
6426 // more job than an idle one did (seen: 9 -> 10 at load 62). The
6427 // bound above is the structural claim; here only a runaway counts.
6428 assert!(
6429 counts[1] <= counts[0] + 4,
6430 "{NAME}: a second decode of the same stream grew the pool from {} to {} threads",
6431 counts[0], counts[1]
6432 );
6433 }
6434
6435 #[test]
6436 fn a_real_stream_filters_identically_with_one_and_four_filter_threads() {
6437 const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads";
6438 let _gate_lock = lock_gate_counters();
6439 for (fixture, wants_lr, wants_grain) in [
6440 ("superres_alltools_sb128_320x180.obu", true, false),
6441 ("grain_cdef_lr_128x128.obu", false, true),
6442 ] {
6443 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6444 .join("fixtures")
6445 .join(fixture);
6446 let stream = std::fs::read(&path)
6447 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6448 let before = (
6449 crate::decode::deblock_hits(),
6450 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
6451 crate::film_grain::grain_hits(),
6452 );
6453 crate::par::set_filter_threads(1);
6454 let one = match decode_stream(&stream) {
6455 Ok(frames) => frames,
6456 Err(e) => panic!("{NAME}: {fixture} refused at 1 filter thread: {e}"),
6457 };
6458 let after = (
6459 crate::decode::deblock_hits(),
6460 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
6461 crate::film_grain::grain_hits(),
6462 );
6463 crate::par::set_filter_threads(4);
6464 let four = match decode_stream(&stream) {
6465 Ok(frames) => frames,
6466 Err(e) => {
6467 crate::par::set_filter_threads(1);
6468 panic!("{NAME}: {fixture} refused at 4 filter threads: {e}")
6469 }
6470 };
6471 crate::par::set_filter_threads(1);
6472 assert!(after.0 > before.0, "{NAME}: {fixture} deblocked no edge at all");
6473 if wants_lr {
6474 assert!(after.1 > before.1, "{NAME}: {fixture} ran no restoration unit");
6475 }
6476 if wants_grain {
6477 assert!(after.2 > before.2, "{NAME}: {fixture} applied no film grain");
6478 }
6479 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
6480 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
6481 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
6482 assert_eq!(a.y, b.y, "{NAME}: {fixture} frame {i} luma differs at 4 filter threads");
6483 assert_eq!(a.u, b.u, "{NAME}: {fixture} frame {i} U differs at 4 filter threads");
6484 assert_eq!(a.v, b.v, "{NAME}: {fixture} frame {i} V differs at 4 filter threads");
6485 }
6486 }
6487 }
6488
6489 /// lane-t900 r30b: `fixtures/superres_alltools_sb128_320x180.obu` is 10
6490 /// frames of `--cpu-used=4 --sb-size=128 --superres-mode=1
6491 /// --superres-denominator=12 --cq-level=32` with every tool aomenc turns
6492 /// on by default (CDEF, loop restoration, OBMC, compound, warp) -- the
6493 /// first stream here that deblocks CHROMA across a group of 4x4 luma
6494 /// blocks.
6495 ///
6496 /// The defect it pins (fixed at this commit, `decode.rs`'s
6497 /// `plane_to_mi`/`edge_params`): `set_lpf_parameters`
6498 /// (`av1_loopfilter.c:245`) indexes the mi grid for a CHROMA edge at
6499 /// `scale | ((coord << scale) >> MI_SIZE_LOG2)` -- the BOTTOM/RIGHT mi of
6500 /// the co-located 8x8 luma group, the same cell that donates the group's
6501 /// chroma prediction. This decoder dropped that `| 1` and read the
6502 /// group's top-left mi, stepped to the previous cell by one mi instead of
6503 /// `1 << ss`, and priced `pu_edge` by comparing mi origins rather than
6504 /// the edge coordinate against the block size in the FILTERED plane's own
6505 /// pixels (chroma bottoms out at 4). All three are invisible while every
6506 /// block is 8x8 or larger (all four mi of a group carry the same tx size,
6507 /// ref frame, skip flag and delta_lf) and wrong the moment cpu-used=4
6508 /// splits a group into 4x4 blocks: on this stream one U sample of frame 2
6509 /// took a filter level of 12 where libaom's neighbouring 4x4 block gives
6510 /// 8, and the error compounded through the reference chain to 280 U + 331
6511 /// V samples (max 9) by frame 9. Class `context-read-from-one-cell`.
6512 ///
6513 /// Post-deblock, this stream is now byte-exact against the instrumented
6514 /// libaom (`EC_AV1_POSTDEBLOCK_DUMP`) in all 10 frames, and the final
6515 /// output matches ffmpeg's.
6516 #[test]
6517 fn a_superres_all_tools_sb128_stream_decodes_pixel_exact() {
6518 const NAME: &str = "a_superres_all_tools_sb128_stream_decodes_pixel_exact";
6519 let _gate_lock = lock_gate_counters();
6520 if !have_ffmpeg() {
6521 eprintln!("SKIP {NAME}: no ffmpeg");
6522 return;
6523 }
6524 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6525 .join("fixtures/superres_alltools_sb128_320x180.obu");
6526 let stream = std::fs::read(&path)
6527 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6528 let (width, height, count) = (320usize, 180usize, 10usize);
6529 let frames = match decode_stream(&stream) {
6530 Ok(frames) => frames,
6531 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
6532 };
6533 assert_eq!(frames.len(), count, "{NAME}: frame count");
6534 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, count);
6535 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6536 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
6537 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
6538 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
6539 }
6540 }
6541
6542 /// lane-golomb r1: THE FILM ITSELF. `crates/ec-av1/fixtures/reelb_head_key_frame.obu`
6543 /// is the first frame of the user's ReelB AV1 release (3840x1608
6544 /// yuv420p10le, `ffmpeg -i <mkv> -c copy -frames:v 1 -f obu`, 147 bytes) --
6545 /// a real 10-bit key frame whose height is NOT a multiple of the 64-pixel
6546 /// superblock, so its last superblock row (mi_row=400 of 402) carries the
6547 /// edge partition symbol this lane fixed: libaom's `ec_read_partition_impl`
6548 /// returns `PARTITION_HORZ` when the gathered `split_or_horz` bit is 0, and
6549 /// this decoder used to READ that bit and throw it away, forcing SPLIT
6550 /// (class `parsed-then-discarded`). The desync surfaced two rows later as
6551 /// "a Golomb tail longer than this decoder reads" -- a refusal naming the
6552 /// symptom, never the cause.
6553 #[test]
6554 fn the_reelb_head_key_frame_decodes_pixel_exact() {
6555 const NAME: &str = "the_reelb_head_key_frame_decodes_pixel_exact";
6556 if !have_ffmpeg() {
6557 eprintln!("SKIP {NAME}: no ffmpeg");
6558 return;
6559 }
6560 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6561 .join("fixtures/reelb_head_key_frame.obu");
6562 let stream = std::fs::read(&path)
6563 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6564 let (width, height) = (3840usize, 1608usize);
6565 let frames = match decode_stream(&stream) {
6566 Ok(frames) => frames,
6567 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
6568 };
6569 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
6570 assert_eq!((frames[0].width, frames[0].height), (width, height));
6571 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
6572 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
6573 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
6574 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
6575 }
6576 /// lane-reelckf r2: `crates/ec-av1/fixtures/reelc_kf2700.obu` is a 1920x792
6577 /// 10-bit AV1 key frame taken out of one of the user's own films
6578 /// (`ffmpeg -ss 2700 -c:v copy -f obu`, then truncated to its first temporal
6579 /// unit, 36 kB) -- the ONLY stream in this repo that contains a SKIPPED
6580 /// `UV_CFL_PRED` block. 30 aomenc recipes (r1's 20 plus r2's chroma-correlated
6581 /// `geq` sweep, cq 40..63, cpu-used 0..2, min/max-partition 4..64, 8 and
6582 /// 10 bit) never made the encoder pick one, so the counter can only be
6583 /// hard-asserted against a real film frame. The instrumented oracle agrees:
6584 /// `EC_TRACE_MODE=1 aomdec` prints 5 `EC_IMODE_VAL ... uv_mode=13 skip=1`
6585 /// lines for this frame.
6586 ///
6587 /// The defect it pins (fixed at 29cd53f, `decode.rs:7719`/`:10528`/`:10891`):
6588 /// a skipped intra block must still PREDICT with CfL -- libaom's
6589 /// `predict_and_reconstruct_intra_block` predicts every plane and guards only
6590 /// the residual on `skip_txfm`. Before the fix this frame had 499 wrong
6591 /// chroma samples (U rows 48..79 cols 464..492); after it, zero.
6592 ///
6593 /// The ffmpeg reference is `ffmpeg -f obu -i <fixture> -f rawvideo
6594 /// -pix_fmt yuv420p10le -` (what `ffmpeg_decode_sequence_10bit` runs).
6595 #[test]
6596 fn a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact() {
6597 const NAME: &str = "a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact";
6598 let path =
6599 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelc_kf2700.obu");
6600 let stream = std::fs::read(&path)
6601 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6602 let (width, height) = (1920usize, 792usize);
6603 let before = crate::decode::reelc_chroma_counters();
6604 let frames = match decode_stream(&stream) {
6605 Ok(frames) => frames,
6606 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
6607 };
6608 let after = crate::decode::reelc_chroma_counters();
6609 let skip_cfl = after.0 - before.0;
6610 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
6611 assert_eq!((frames[0].width, frames[0].height), (width, height));
6612 // Asserted before the ffmpeg compare so an absent ffmpeg cannot make the
6613 // gate vacuous: the skipped-CfL path is exercised on every run.
6614 assert!(
6615 skip_cfl > 0,
6616 "{NAME}: zero skipped-CfL blocks -- the fixture no longer exercises defect 1"
6617 );
6618 if !have_ffmpeg() {
6619 eprintln!("SKIP {NAME} pixel compare: no ffmpeg (skipped_cfl={skip_cfl})");
6620 return;
6621 }
6622 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
6623 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
6624 assert_eq!(
6625 frames[0].u, ffmpeg_frames[0].u,
6626 "{NAME}: U vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
6627 );
6628 assert_eq!(
6629 frames[0].v, ffmpeg_frames[0].v,
6630 "{NAME}: V vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
6631 );
6632 eprintln!("{NAME}: pixel-exact, skipped_cfl={skip_cfl}");
6633 }
6634
6635 /// lane-kf1200 r2: the same film's `-ss 300` key frame, pinned because no
6636 /// aomenc recipe reaches its shape -- a SKIPPED sub-8x8 chroma block whose
6637 /// `uv_mode` is `UV_CFL_PRED`. (lane-reelckf r1 burned 20 recipes across cq
6638 /// 40..63 and nine lavfi sources hunting exactly this block and never got
6639 /// one; ledger dead-end "never produced a SKIPPED 1:4 or sub-8x8 CfL
6640 /// block".) Before the fix the two sub-8x8 skip arms passed `None` for the
6641 /// CfL argument, so the block reconstructed as flat DC and 463 bytes of
6642 /// this frame's chroma were wrong. HARD-asserts `skip_cfl_hits` moved, so
6643 /// the fixture cannot silently stop exercising the arm.
6644 #[test]
6645 fn the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact() {
6646 const NAME: &str = "the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact";
6647 if !have_ffmpeg() {
6648 eprintln!("SKIP {NAME}: no ffmpeg");
6649 return;
6650 }
6651 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6652 .join("fixtures/reelb_ss300_key_frame.obu");
6653 let stream = std::fs::read(&path)
6654 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6655 let (width, height) = (3840usize, 1608usize);
6656 let before = crate::decode::skip_cfl_hits();
6657 let frames = match decode_stream(&stream) {
6658 Ok(frames) => frames,
6659 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
6660 };
6661 let skipped_cfl = crate::decode::skip_cfl_hits() - before;
6662 assert!(
6663 skipped_cfl > 0,
6664 "{NAME}: zero skipped sub-8x8 CfL blocks -- the fixture no longer \
6665 exercises the arm this test exists for"
6666 );
6667 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
6668 assert_eq!((frames[0].width, frames[0].height), (width, height));
6669 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
6670 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
6671 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
6672 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
6673 eprintln!("{NAME}: {skipped_cfl} skipped sub-8x8 CfL chroma blocks, frame pixel-exact");
6674 }
6675
6676 /// lane-kf900 r2: the film's key frame at -ss 900, one frame
6677 /// (`crates/ec-av1/fixtures/reelb_kf900.obu`, 484640 bytes, sha256
6678 /// `a273ae99328388be14a1ff8fa1c5a6d391a9948159eaef120e1b50e02015eb83`,
6679 /// extracted twice from independent
6680 /// `ffmpeg -ss 900 -t 2 -i <2160p AV1 HDR10 mkv> -c:v copy -f obu` runs and
6681 /// truncated to the first frame; both extracts hashed identically).
6682 ///
6683 /// This is the ONLY stream that reaches the r1 defect: a SKIPPED 8x8 intra
6684 /// leaf whose `tx_depth` symbol resolved to `TX_4X4` still publishes 4 --
6685 /// not its 8-pixel block side -- to the next block's `get_tx_size_context`
6686 /// (`set_txfm_ctxs(mbmi->tx_size, bw, bh, skip_txfm && is_inter_block(...))`,
6687 /// `decodemv.c`; the skip term is 0 for intra). It fires 15 times here and
6688 /// zero times across 108 measured aomenc recipes, so the counter is
6689 /// asserted against the film rather than against a synthesised stream.
6690 ///
6691 /// LUMA only. U/V still differ (open residue, lane-kf900 r2: 221 U and
6692 /// 47912 V samples, max |d| 23/2, first at chroma (195, 640) -- chroma
6693 /// RESIDUAL, the prediction there is bit-exact against aomdec's
6694 /// `EC_PREDOUT`), so this gate pins what is proven and no more.
6695 #[test]
6696 fn a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact()
6697 {
6698 const NAME: &str = "a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact";
6699 if !have_ffmpeg() {
6700 eprintln!("SKIP {NAME}: no ffmpeg");
6701 return;
6702 }
6703 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_kf900.obu");
6704 let stream = std::fs::read(&path)
6705 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6706 let (width, height) = (3840usize, 1608usize);
6707 crate::decode::reset_skip_split_tx_hits();
6708 let frames = match decode_stream(&stream) {
6709 Ok(frames) => frames,
6710 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
6711 };
6712 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
6713 assert_eq!((frames[0].width, frames[0].height), (width, height));
6714 assert!(
6715 crate::decode::skip_split_tx_hits() >= 15,
6716 "{NAME}: skip_split_tx_hits() == {} -- the stream that carries the tx-context \
6717 defect stopped carrying it, so this gate proves nothing",
6718 crate::decode::skip_split_tx_hits()
6719 );
6720 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
6721 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
6722 }
6723
6724 /// lane-kf1200 r3: the same film's `-ss 600` key frame (3840x1608, one
6725 /// 8-px partial bottom superblock row), pinned because no aomenc recipe
6726 /// reaches its shape -- a SKIPPED 8x8 intra leaf whose `tx_depth` resolved
6727 /// to TX_4X4. (80 recipes swept this round: 4 frame shapes x 2 sources x
6728 /// cq 32..63 x cpu-used 0/3 x 8/10-bit, all with
6729 /// `--enable-tx-size-search=1 --enable-filter-intra=1`; every one came
6730 /// back with `skip_split_tx_hits == 0`, `lanes/kf1200-r3.report.md`.)
6731 /// An intra block reads `tx_depth` whether or not it is skipped, so the
6732 /// leaf must record its resolved 4 -- not its 8x8 side -- in the txfm
6733 /// context; recording 8 gave the NEXT block's `tx_depth` symbol the wrong
6734 /// `tx_size_cdf` row (ctx 2 where libaom reads 1) and desynced the
6735 /// entropy stream at mi (400,46). HARD-asserts `skip_split_tx_hits` moved.
6736 #[test]
6737 fn the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact() {
6738 const NAME: &str = "the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact";
6739 if !have_ffmpeg() {
6740 eprintln!("SKIP {NAME}: no ffmpeg");
6741 return;
6742 }
6743 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6744 .join("fixtures/reelb_ss600_key_frame.obu");
6745 let stream = std::fs::read(&path)
6746 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
6747 let (width, height) = (3840usize, 1608usize);
6748 crate::decode::reset_skip_split_tx_hits();
6749 let frames = match decode_stream(&stream) {
6750 Ok(frames) => frames,
6751 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
6752 };
6753 let skipped_split_tx = crate::decode::skip_split_tx_hits();
6754 assert!(
6755 skipped_split_tx > 0,
6756 "{NAME}: zero skipped 8x8 leaves with a split transform -- the fixture no longer \
6757 exercises the arm this test exists for"
6758 );
6759 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
6760 assert_eq!((frames[0].width, frames[0].height), (width, height));
6761 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
6762 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
6763 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
6764 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
6765 eprintln!("{NAME}: {skipped_split_tx} skipped 8x8 TX_4X4 leaves, frame pixel-exact");
6766 }
6767
6768 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
6769 /// --superres-denominator=12` key frame, decoded pixel-exact against
6770 /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
6771 /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
6772 /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
6773 /// `bit_depth == 10` and `superres_hits > 0`.
6774 #[test]
6775 fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
6776 const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
6777 if !have_ffmpeg() {
6778 eprintln!("SKIP {NAME}: no ffmpeg");
6779 return;
6780 }
6781 if !have_aomenc() {
6782 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6783 return;
6784 }
6785 let (width, height) = (64usize, 64usize);
6786 let stream = encode_10bit_gradients(
6787 NAME,
6788 width,
6789 height,
6790 1,
6791 &[
6792 "--limit=1",
6793 "--kf-max-dist=0",
6794 "--superres-mode=1",
6795 "--superres-denominator=12",
6796 "--superres-kf-denominator=12",
6797 "--enable-rect-partitions=0",
6798 "--enable-ab-partitions=0",
6799 "--enable-1to4-partitions=0",
6800 "--enable-filter-intra=0",
6801 "--enable-smooth-intra=0",
6802 "--enable-paeth-intra=0",
6803 "--enable-directional-intra=0",
6804 "--enable-angle-delta=0",
6805 "--enable-tx-size-search=0",
6806 "--enable-cdef=0",
6807 "--enable-restoration=0",
6808 "--max-partition-size=32",
6809 "--min-partition-size=32",
6810 "--enable-palette=0",
6811 "--enable-intrabc=0",
6812 "--enable-cfl-intra=0",
6813 ],
6814 );
6815 assert_eq!(
6816 parsed_bit_depth(&stream),
6817 10,
6818 "{NAME}: aomenc did not actually write a 10-bit sequence header"
6819 );
6820 let before = crate::superres::superres_hits();
6821 let frames = match decode_stream(&stream) {
6822 Ok(frames) => frames,
6823 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
6824 };
6825 assert!(
6826 crate::superres::superres_hits() > before,
6827 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
6828 );
6829 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
6830 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
6831 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
6832 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
6833 eprintln!(
6834 "{NAME}: pixel-exact, superres_hits={}",
6835 crate::superres::superres_hits()
6836 );
6837 }
6838
6839 /// lane-hbdgates r1: drive one 10-bit aomenc recipe over `seeds`, decode
6840 /// every attempt and pixel-compare every SHOWN frame against ffmpeg's own
6841 /// 10-bit decode of the identical bytes. Per-tool firing counters are
6842 /// sampled PER ATTEMPT and summed only over attempts that decoded *and*
6843 /// compared -- a stream that hit a named refusal contributes nothing
6844 /// (class `counter-from-refused-stream`). Named refusals are tolerated
6845 /// and reported; a pixel mismatch is a hard failure, never a SKIP.
6846 fn ten_bit_tool_gate(
6847 name: &str,
6848 width: usize,
6849 height: usize,
6850 frames: usize,
6851 extra: &[&str],
6852 seeds: &[u32],
6853 counters: &[(&str, fn() -> usize)],
6854 ) {
6855 fn first_diff(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
6856 ours.iter()
6857 .zip(theirs.iter())
6858 .position(|(a, b)| a != b)
6859 .map(|i| {
6860 format!(
6861 "first diff at index {i} (row {}, col {}): ours {} vs ffmpeg {}",
6862 i / width,
6863 i % width,
6864 ours[i],
6865 theirs[i]
6866 )
6867 })
6868 }
6869 let mut totals = vec![0usize; counters.len()];
6870 let mut refusals: Vec<String> = Vec::new();
6871 let mut compared = 0usize;
6872 for &seed in seeds {
6873 let stream = encode_10bit_gradients_seed(name, seed, width, height, frames, extra);
6874 assert_eq!(
6875 parsed_bit_depth(&stream),
6876 10,
6877 "{name}: aomenc did not write a 10-bit sequence header (seed {seed})"
6878 );
6879 let before: Vec<usize> = counters.iter().map(|(_, f)| f()).collect();
6880 let decoded = match decode_stream(&stream) {
6881 Ok(frames) => frames,
6882 Err(e) => {
6883 refusals.push(format!("seed {seed}: {e}"));
6884 continue;
6885 }
6886 };
6887 // Deltas are read BEFORE the pixel compare so a mismatch report
6888 // says whether the tool under test actually fired on the failing
6889 // stream (a mismatch with a zero delta is some other defect).
6890 let deltas: Vec<usize> = counters
6891 .iter()
6892 .zip(before.iter())
6893 .map(|((_, f), b)| f() - b)
6894 .collect();
6895 let fired: Vec<String> = counters
6896 .iter()
6897 .zip(deltas.iter())
6898 .map(|((label, _), d)| format!("{label}={d}"))
6899 .collect();
6900 let fired = fired.join(" ");
6901 let reference = ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len());
6902 assert_eq!(
6903 decoded.len(),
6904 reference.len(),
6905 "{name}: seed {seed}: shown-frame count vs ffmpeg"
6906 );
6907 for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
6908 for (plane, (a, b), w) in [
6909 ("Y", (&ours.y, &theirs.y), width),
6910 ("U", (&ours.u, &theirs.u), width / 2),
6911 ("V", (&ours.v, &theirs.v), width / 2),
6912 ] {
6913 if let Some(d) = first_diff(a, b, w) {
6914 panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]");
6915 }
6916 }
6917 }
6918 compared += 1;
6919 for (i, d) in deltas.iter().enumerate() {
6920 totals[i] += d;
6921 }
6922 }
6923 assert!(
6924 compared > 0,
6925 "{name}: every attempt hit a named refusal:\n{}",
6926 refusals.join("\n")
6927 );
6928 for (i, (label, _)) in counters.iter().enumerate() {
6929 assert!(
6930 totals[i] > 0,
6931 "{name}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
6932 the gate would prove nothing about that tool. refusals:\n{}",
6933 refusals.join("\n")
6934 );
6935 }
6936 let summary: Vec<String> = counters
6937 .iter()
6938 .zip(totals.iter())
6939 .map(|((label, _), t)| format!("{label}={t}"))
6940 .collect();
6941 eprintln!(
6942 "{name}: {compared}/{} attempts pixel-exact, {}",
6943 seeds.len(),
6944 summary.join(" ")
6945 );
6946 }
6947
6948 /// lane-hbdgates r1: the four intra tools that had an 8-bit gate and no
6949 /// 10-bit one (`filter-intra`, `smooth-intra`, `paeth-intra`,
6950 /// `intra-edge-filter`) on ONE real 10-bit `aomenc` key frame, each with
6951 /// its own hard-asserted counter. His two films are yuv420p10le, so an
6952 /// 8-bit-only gate for these tools proves nothing about the streams that
6953 /// matter (lane-covbd r1).
6954 #[test]
6955 fn a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact() {
6956 const NAME: &str = "a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact";
6957 if !have_ffmpeg() {
6958 eprintln!("SKIP {NAME}: no ffmpeg");
6959 return;
6960 }
6961 if !have_aomenc() {
6962 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6963 return;
6964 }
6965 ten_bit_tool_gate(
6966 NAME,
6967 64,
6968 64,
6969 1,
6970 &[
6971 "--limit=1",
6972 "--kf-max-dist=0",
6973 "--enable-filter-intra=1",
6974 "--enable-smooth-intra=1",
6975 "--enable-paeth-intra=1",
6976 "--enable-intra-edge-filter=1",
6977 "--enable-directional-intra=1",
6978 "--enable-angle-delta=0",
6979 "--enable-rect-partitions=0",
6980 "--enable-ab-partitions=0",
6981 "--enable-1to4-partitions=0",
6982 "--enable-tx-size-search=0",
6983 "--enable-cdef=0",
6984 "--enable-restoration=0",
6985 "--max-partition-size=32",
6986 "--min-partition-size=16",
6987 "--enable-palette=0",
6988 "--enable-intrabc=0",
6989 "--enable-cfl-intra=0",
6990 "--enable-ref-frame-mvs=0",
6991 ],
6992 &[42, 7, 11, 23, 31, 57],
6993 &[
6994 ("filter_intra_hits", decode::filter_intra_hits),
6995 ("smooth_pred_hits", crate::intra::smooth_pred_hits),
6996 ("paeth_pred_hits", crate::intra::paeth_pred_hits),
6997 ("intra_edge_filter_hits", crate::intra::intra_edge_filter_hits),
6998 ],
6999 );
7000 }
7001
7002 /// lane-hbdgates r1: `--enable-restoration=1` at 10 bits. Every earlier
7003 /// bit-depth gate ran `--enable-restoration=0`, which is exactly why two
7004 /// high-bit-depth loop-restoration defects survived to 2026-09-01
7005 /// (SGR box sums unscaled, Wiener clamp at the 8-bit bound). Same recipe
7006 /// as the 8-bit LR gate, at 10 bits.
7007 // Written `#[ignore]`d on lane-hbdgates (the branch lacked lane-hbdinter's
7008 // 10-bit LR fix and failed at seed 42, frame 0, Y index 122: ours 351 vs
7009 // ffmpeg 350). Un-ignored on the merge into main 2026-09-01, where the
7010 // SGR box-sum scaling and the Wiener clamp are fixed: 16/16 attempts
7011 // pixel-exact, lr_hits=28.
7012 #[test]
7013 fn a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact() {
7014 const NAME: &str = "a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact";
7015 if !have_ffmpeg() {
7016 eprintln!("SKIP {NAME}: no ffmpeg");
7017 return;
7018 }
7019 if !have_aomenc() {
7020 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7021 return;
7022 }
7023 // 192x128 = 3x2 superblocks, so `read_lr` is re-entered per SB
7024 // (the 8-bit LR gate's own trap warning); cq-level=15 because
7025 // aomenc's RD only picks a non-RESTORE_NONE frame type at low cq.
7026 ten_bit_tool_gate(
7027 NAME,
7028 192,
7029 128,
7030 1,
7031 &[
7032 "--limit=1",
7033 "--kf-max-dist=0",
7034 "--cq-level=15",
7035 "--enable-restoration=1",
7036 "--enable-cdef=0",
7037 "--enable-rect-partitions=0",
7038 "--enable-ab-partitions=0",
7039 "--enable-1to4-partitions=0",
7040 "--enable-filter-intra=0",
7041 "--enable-smooth-intra=0",
7042 "--enable-paeth-intra=0",
7043 "--enable-tx-size-search=0",
7044 "--max-partition-size=32",
7045 "--min-partition-size=16",
7046 "--enable-palette=0",
7047 "--enable-intrabc=0",
7048 "--enable-cfl-intra=0",
7049 "--enable-ref-frame-mvs=0",
7050 ],
7051 &LR_SEEDS,
7052 &[("lr_hits", ten_bit_lr_hits)],
7053 );
7054 }
7055
7056 /// Seeds swept by the 10-bit LR gate (the 8-bit gate needs ~40 attempts
7057 /// to land a non-RESTORE_NONE frame; every attempt here still has to
7058 /// decode pixel-exact).
7059 /// lane-obmcrec r1: the `LR_SEEDS` members whose 1:4-partition stream both
7060 /// fires `obmc_pair_filter_hits` and decodes every frame pixel-exact.
7061 /// Measured over seeds 42..=73 (32 encodes): 43/46/47/65/66 fire and are
7062 /// exact; 70 and 73 fire and mismatch, but mismatch IDENTICALLY with
7063 /// `--enable-obmc=0` (seed 73 frame 1 luma, seed 70 frame 16), so their
7064 /// defect is in the `--min-partition-size=4` recipe, not in OBMC -- kept
7065 /// out of this gate rather than papered over, and reported as open.
7066 const OBMC_PAIR_SEEDS: [u32; 5] = [43, 46, 47, 65, 66];
7067
7068 const LR_SEEDS: [u32; 16] = [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
7069
7070 /// Wiener + SGR + switchable loop-restoration firings, summed.
7071 fn ten_bit_lr_hits() -> usize {
7072 crate::restoration::wiener_hits()
7073 + crate::restoration::sgrproj_hits()
7074 + crate::restoration::switchable_hits()
7075 }
7076
7077 /// lane-reelckf2 r1: loop restoration on frame sizes whose LAST stripe is
7078 /// partial, with 128-sample superblocks -- the two stripe shapes whose
7079 /// boundary substitution is special (`filter_restoration_unit`: the first
7080 /// stripe is 8 rows short and takes its above boundary from the frame's
7081 /// own top rows, the last one is truncated and takes its below boundary
7082 /// from the frame's own bottom row) had no gate at all: every earlier LR
7083 /// size (192x128, 160x96) is a whole multiple of 64 rows and ran at
7084 /// `--sb-size=64`. 152 = 2*64+24 and 216 = 3*64+24 both leave a 32-row
7085 /// tail stripe, mirroring the 792-row 10-bit film that made this lane.
7086 /// `lr_stripe0_hits`/`lr_last_stripe_hits` are hard-asserted per attempt
7087 /// by [`ten_bit_tool_gate`], so an RD that picked RESTORE_NONE on either
7088 /// stripe cannot pass.
7089 #[test]
7090 fn a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact() {
7091 const NAME: &str =
7092 "a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact";
7093 if !have_ffmpeg() {
7094 eprintln!("SKIP {NAME}: no ffmpeg");
7095 return;
7096 }
7097 if !have_aomenc() {
7098 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7099 return;
7100 }
7101 // `--sb-size=128` goes in `extra`, which the helper appends AFTER its
7102 // own `--sb-size=64` (aomenc keeps the LAST occurrence of a repeated
7103 // flag, measured 2026-09-02); `--max-partition-size=32` keeps the 128
7104 // root on SPLIT, the only 128-root partition decoded today.
7105 for (width, height, cq) in [(256usize, 152usize, "15"), (384, 216, "15"), (256, 152, "25")]
7106 {
7107 ten_bit_tool_gate(
7108 &format!("{NAME} {width}x{height} cq{cq}"),
7109 width,
7110 height,
7111 1,
7112 &[
7113 "--limit=1",
7114 "--kf-max-dist=0",
7115 &format!("--cq-level={cq}"),
7116 "--sb-size=128",
7117 "--enable-restoration=1",
7118 "--enable-cdef=0",
7119 "--enable-rect-partitions=0",
7120 "--enable-ab-partitions=0",
7121 "--enable-1to4-partitions=0",
7122 "--enable-filter-intra=0",
7123 "--enable-smooth-intra=0",
7124 "--enable-paeth-intra=0",
7125 "--enable-tx-size-search=0",
7126 "--max-partition-size=32",
7127 "--min-partition-size=16",
7128 "--enable-palette=0",
7129 "--enable-intrabc=0",
7130 "--enable-cfl-intra=0",
7131 "--enable-ref-frame-mvs=0",
7132 ],
7133 &LR_SEEDS,
7134 &[
7135 ("lr_hits", ten_bit_lr_hits),
7136 ("lr_stripe0_hits", crate::restoration::lr_stripe0_hits),
7137 ("lr_last_stripe_hits", crate::restoration::lr_last_stripe_hits),
7138 ],
7139 );
7140 }
7141 }
7142
7143 /// lane-hbdgates r1: `--enable-rect-partitions=1 --enable-ab-partitions=1`
7144 /// at 10 bits, one intra stream, one counter per tool
7145 /// (`rect_partition_hits`, `partab_hits`) so a stream that only fired the
7146 /// rect arms cannot stand in for AB.
7147 #[test]
7148 fn a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact() {
7149 const NAME: &str = "a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact";
7150 if !have_ffmpeg() {
7151 eprintln!("SKIP {NAME}: no ffmpeg");
7152 return;
7153 }
7154 if !have_aomenc() {
7155 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7156 return;
7157 }
7158 // The 8-bit free-partition/AB recipe, verbatim, at 10 bits: AB
7159 // splits are an INTER dispatch here (intra-frame AB is still a named
7160 // refusal), so the stream needs alt-refs and 24 frames, not one key
7161 // frame.
7162 ten_bit_tool_gate(
7163 NAME,
7164 64,
7165 64,
7166 24,
7167 &[
7168 "--cq-level=45",
7169 "--kf-max-dist=1000",
7170 "--auto-alt-ref=1",
7171 "--lag-in-frames=16",
7172 "--enable-fwd-kf=0",
7173 "--enable-order-hint=1",
7174 "--enable-warped-motion=1",
7175 "--enable-obmc=1",
7176 "--tune-content=default",
7177 "--enable-masked-comp=0",
7178 "--enable-interintra-comp=0",
7179 "--enable-onesided-comp=0",
7180 "--enable-interintra-wedge=0",
7181 "--enable-smooth-interintra=0",
7182 "--enable-rect-partitions=1",
7183 "--enable-ab-partitions=1",
7184 "--enable-1to4-partitions=0",
7185 "--enable-filter-intra=0",
7186 "--enable-smooth-intra=0",
7187 "--enable-paeth-intra=0",
7188 "--enable-directional-intra=0",
7189 "--enable-angle-delta=0",
7190 "--enable-tx-size-search=0",
7191 "--enable-cdef=0",
7192 "--enable-restoration=0",
7193 "--max-partition-size=32",
7194 "--min-partition-size=16",
7195 "--enable-palette=0",
7196 "--enable-intrabc=0",
7197 "--enable-cfl-intra=0",
7198 "--enable-ref-frame-mvs=0",
7199 ],
7200 &LR_SEEDS,
7201 &[
7202 ("rect_partition_hits", decode::rect_partition_hits),
7203 ("partab_hits", decode::partab_hits),
7204 ],
7205 );
7206 }
7207
7208 /// lane-obmcrec r1: OBMC whose above/left neighbour is a 4-wide/4-tall
7209 /// 1:4-partition strip -- the shape the three 1080p 10-bit film cuts
7210 /// refused on ("an OBMC neighbour whose switchable interp filter was never
7211 /// recorded"). `overlappable_above`/`_left` snap such a neighbour to the
7212 /// chroma pair's SECOND mi but used to read its interp filter from the
7213 /// FIRST one, a different block whose filter record is the intra
7214 /// `[3, 3]` sentinel whenever that half is intra. `obmc_pair_filter_hits`
7215 /// counts exactly that neighbour shape, so a stream without 1:4 strips
7216 /// next to an OBMC block cannot stand in for it.
7217 #[test]
7218 fn a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact() {
7219 const NAME: &str = "a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact";
7220 if !have_ffmpeg() {
7221 eprintln!("SKIP {NAME}: no ffmpeg");
7222 return;
7223 }
7224 if !have_aomenc() {
7225 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7226 return;
7227 }
7228 ten_bit_tool_gate(
7229 NAME,
7230 128,
7231 128,
7232 24,
7233 &[
7234 "--ec-fixture-noise",
7235 "--cq-level=45",
7236 "--kf-max-dist=1000",
7237 "--auto-alt-ref=1",
7238 "--lag-in-frames=16",
7239 "--enable-fwd-kf=0",
7240 "--enable-order-hint=1",
7241 "--enable-warped-motion=0",
7242 "--enable-obmc=1",
7243 "--tune-content=default",
7244 "--enable-masked-comp=0",
7245 "--enable-interintra-comp=0",
7246 "--enable-onesided-comp=0",
7247 "--enable-interintra-wedge=0",
7248 "--enable-smooth-interintra=0",
7249 "--enable-rect-partitions=1",
7250 "--enable-ab-partitions=0",
7251 "--enable-1to4-partitions=1",
7252 "--enable-filter-intra=0",
7253 "--enable-smooth-intra=0",
7254 "--enable-paeth-intra=0",
7255 "--enable-directional-intra=0",
7256 "--enable-angle-delta=0",
7257 "--enable-tx-size-search=0",
7258 "--enable-cdef=0",
7259 "--enable-restoration=0",
7260 "--max-partition-size=32",
7261 "--min-partition-size=4",
7262 "--enable-palette=0",
7263 "--enable-intrabc=0",
7264 "--enable-cfl-intra=0",
7265 "--enable-ref-frame-mvs=0",
7266 ],
7267 &OBMC_PAIR_SEEDS,
7268 &[("obmc_pair_filter_hits", decode::obmc_pair_filter_hits)],
7269 );
7270 }
7271
7272 /// `bit_depth` of the first sequence header in `stream`.
7273 fn parsed_bit_depth(stream: &[u8]) -> u8 {
7274 let mut probe = Av1Parser::new();
7275 let mut pos = 0usize;
7276 while pos < stream.len() && probe.sequence_header().is_none() {
7277 let obu = probe.parse_obu(&stream[pos..]).unwrap();
7278 pos += obu.total_size;
7279 }
7280 probe
7281 .sequence_header()
7282 .expect("stream has a sequence header OBU")
7283 .color_config
7284 .bit_depth
7285 }
7286
7287 /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and
7288 /// encode it with a real 10-bit `aomenc`, returning the OBU stream.
7289 /// `extra` carries the tool flags under test.
7290 fn encode_10bit_gradients(
7291 name: &str,
7292 width: usize,
7293 height: usize,
7294 frames: usize,
7295 extra: &[&str],
7296 ) -> Vec<u8> {
7297 encode_10bit_gradients_seed(name, 42, width, height, frames, extra)
7298 }
7299
7300 /// As [`encode_10bit_gradients`], but with the fixture seed exposed --
7301 /// lane-hbdgates r1 sweeps seeds so a tool that aomenc's RD declines on
7302 /// one fixture still gets a firing stream.
7303 fn encode_10bit_gradients_seed(
7304 name: &str,
7305 seed: u32,
7306 width: usize,
7307 height: usize,
7308 frames: usize,
7309 extra: &[&str],
7310 ) -> Vec<u8> {
7311 let duration = frames as f64 / 25.0;
7312 // lane-ab32 r1: `--ec-fixture-noise` is not an aomenc flag -- it is a
7313 // fixture request, consumed (and stripped) here: the smooth gradients
7314 // source codes as PARTITION_NONE everywhere, so a partition gate needs
7315 // seeded noise on top of it to give the RD a reason to split.
7316 let noisy = extra.contains(&"--ec-fixture-noise");
7317 let stripped: Vec<&str> = extra
7318 .iter()
7319 .copied()
7320 .filter(|a| *a != "--ec-fixture-noise")
7321 .collect();
7322 let extra: &[&str] = &stripped;
7323 let base = gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
7324 let source = if noisy {
7325 format!("{base},noise=alls=40:all_seed={seed}")
7326 } else {
7327 base
7328 };
7329 let y4m = Command::new("ffmpeg")
7330 .args([
7331 "-v",
7332 "error",
7333 "-f",
7334 "lavfi",
7335 "-i",
7336 &source,
7337 "-pix_fmt",
7338 "yuv420p10le",
7339 "-strict",
7340 "-1",
7341 "-t",
7342 &format!("{duration}"),
7343 "-f",
7344 "yuv4mpegpipe",
7345 "-",
7346 ])
7347 .stdin(Stdio::null())
7348 .stdout(Stdio::piped())
7349 .stderr(Stdio::piped())
7350 .output()
7351 .expect("ffmpeg failed to run");
7352 assert!(
7353 y4m.status.success(),
7354 "{name}: ffmpeg failed to render the 10-bit fixture: {}",
7355 String::from_utf8_lossy(&y4m.stderr)
7356 );
7357 let mut args: Vec<&str> = vec!["--codec=av1", "--passes=1", "--end-usage=q"];
7358 // lane-hbdgates r1: a caller-supplied `--cq-level` REPLACES the
7359 // default rather than being appended after it -- two `--cq-level`
7360 // flags on one aomenc line is a coin flip on which one lands.
7361 if !extra.iter().any(|a| a.starts_with("--cq-level=")) {
7362 args.push("--cq-level=30");
7363 }
7364 args.extend_from_slice(&[
7365 "--cpu-used=0",
7366 "--threads=1",
7367 "--row-mt=0",
7368 "--sb-size=64",
7369 "--input-bit-depth=10",
7370 "--bit-depth=10",
7371 ]);
7372 args.extend_from_slice(extra);
7373 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
7374 let mut child = Command::new(aomenc_path())
7375 .args(&args)
7376 .stdin(Stdio::piped())
7377 .stdout(Stdio::piped())
7378 .stderr(Stdio::piped())
7379 .spawn()
7380 .expect("aomenc failed to start");
7381 child
7382 .stdin
7383 .take()
7384 .expect("aomenc stdin")
7385 .write_all(&y4m.stdout)
7386 .expect("writing y4m to aomenc");
7387 let out = child.wait_with_output().expect("aomenc failed to run");
7388 assert!(
7389 out.status.success(),
7390 "{name}: aomenc refused the 10-bit fixture: {}",
7391 String::from_utf8_lossy(&out.stderr)
7392 );
7393 out.stdout
7394 }
7395
7396 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
7397 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
7398 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
7399 /// which flattened chroma to a single value specifically to avoid
7400 /// exercising this path). Same square-only recipe as the palette-Y gate
7401 /// (`--enable-rect-partitions=0`/`-ab-`/`-1to4-`, fixed 32x32 partition)
7402 /// so a UV palette block never lands inside the still-refused HORZ/VERT
7403 /// screen-content strip. HARD-asserts [`decode::palette_uv_hits`] moved
7404 /// -- a stream that never reads a real UV palette block would decode (or
7405 /// not) by construction without proving this milestone at all
7406 /// ([[gate-blind-to-feature]]).
7407 #[test]
7408 fn a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact() {
7409 const NAME: &str = "a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact";
7410 if !have_ffmpeg() {
7411 eprintln!("SKIP {NAME}: no ffmpeg");
7412 return;
7413 }
7414 if !have_aomenc() {
7415 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7416 return;
7417 }
7418 let source = "testsrc2=size=64x64:rate=25";
7419 fn render(source: &str) -> Vec<u8> {
7420 Command::new("ffmpeg")
7421 .args([
7422 "-v",
7423 "error",
7424 "-f",
7425 "lavfi",
7426 "-i",
7427 source,
7428 "-pix_fmt",
7429 "yuv420p",
7430 "-t",
7431 "0.16",
7432 "-f",
7433 "yuv4mpegpipe",
7434 "-",
7435 ])
7436 .stdin(Stdio::null())
7437 .stdout(Stdio::piped())
7438 .stderr(Stdio::piped())
7439 .output()
7440 .expect("ffmpeg failed to run")
7441 .stdout
7442 }
7443 let y4m_a = render(source);
7444 let y4m_b = render(source);
7445 assert_eq!(
7446 y4m_a, y4m_b,
7447 "testsrc2 must render byte-identical across two runs"
7448 );
7449 let y4m = y4m_a;
7450 let mut child = Command::new(aomenc_path())
7451 .args([
7452 "--codec=av1",
7453 "--passes=1",
7454 "--end-usage=q",
7455 "--cq-level=30",
7456 "--cpu-used=0",
7457 "--threads=1",
7458 "--row-mt=0",
7459 "--sb-size=64",
7460 "--tune-content=screen",
7461 "--enable-palette=1",
7462 "--enable-intrabc=0",
7463 "--enable-rect-partitions=0",
7464 "--enable-ab-partitions=0",
7465 "--enable-1to4-partitions=0",
7466 "--min-partition-size=32",
7467 "--max-partition-size=32",
7468 "--enable-filter-intra=0",
7469 "--enable-cdef=0",
7470 "--enable-restoration=0",
7471 "--enable-tx-size-search=0",
7472 "--loopfilter-control=0",
7473 "--obu",
7474 "-o",
7475 "-",
7476 "-",
7477 ])
7478 .stdin(Stdio::piped())
7479 .stdout(Stdio::piped())
7480 .stderr(Stdio::piped())
7481 .spawn()
7482 .expect("aomenc failed to start");
7483 child
7484 .stdin
7485 .take()
7486 .expect("aomenc stdin")
7487 .write_all(&y4m)
7488 .expect("writing y4m to aomenc");
7489 let out = child.wait_with_output().expect("aomenc failed to run");
7490 assert!(
7491 out.status.success(),
7492 "aomenc refused the fixture: {}",
7493 String::from_utf8_lossy(&out.stderr)
7494 );
7495 let stream = out.stdout;
7496 let before = decode::palette_uv_hits();
7497 let frames = match decode_stream(&stream) {
7498 Ok(frames) => frames,
7499 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
7500 };
7501 assert!(
7502 decode::palette_uv_hits() > before,
7503 "palette_uv_mode never fired decoding this stream -- gate is vacuous"
7504 );
7505 let frame_count = frames.len();
7506 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, frame_count);
7507 for i in 0..frame_count {
7508 assert_eq!(frames[i].y, ffmpeg_frames[i].y, "luma vs ffmpeg, frame {i}");
7509 assert_eq!(frames[i].u, ffmpeg_frames[i].u, "U vs ffmpeg, frame {i}");
7510 assert_eq!(frames[i].v, ffmpeg_frames[i].v, "V vs ffmpeg, frame {i}");
7511 }
7512 }
7513
7514 /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT
7515 /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect`
7516 /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a
7517 /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc
7518 /// partition FIRST on every size/cq combo probed -- `--enable-ab-
7519 /// partitions=0` measurably does not stop aomenc choosing one at this
7520 /// screen-content tune (byte-identical output with `=0` vs `=1`, same
7521 /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing
7522 /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code
7523 /// path: the only choices left at the (single, key-frame) superblock are
7524 /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`],
7525 /// and a size/cq sweep (measured live this round) reliably lands
7526 /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both
7527 /// sources. Drives `decode_stream` directly (below any refusal) and
7528 /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that
7529 /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) --
7530 /// a decode that never lands a rect palette block is not a match.
7531 #[test]
7532 fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() {
7533 const NAME: &str = "a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact";
7534 let _gate_lock = lock_gate_counters();
7535 if !have_ffmpeg() {
7536 eprintln!("SKIP {NAME}: no ffmpeg");
7537 return;
7538 }
7539 if !have_aomenc() {
7540 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7541 return;
7542 }
7543 let mut matched = 0u32;
7544 let mut uncounted_exact = 0u32;
7545 let mut named_refusals = 0u32;
7546 let mut attempts = 0u32;
7547 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
7548 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
7549 for src_name in ["smptebars", "rgbtestsrc"] {
7550 for (width, height) in sizes {
7551 for cq in cqs {
7552 attempts += 1;
7553 let source = format!("{src_name}=size={width}x{height}:rate=25");
7554 let y4m = Command::new("ffmpeg")
7555 .args([
7556 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p",
7557 "-t", "0.04", "-f", "yuv4mpegpipe", "-",
7558 ])
7559 .stdin(Stdio::null())
7560 .stdout(Stdio::piped())
7561 .stderr(Stdio::piped())
7562 .output()
7563 .expect("ffmpeg failed to run");
7564 assert!(
7565 y4m.status.success(),
7566 "ffmpeg fixture: {}",
7567 String::from_utf8_lossy(&y4m.stderr)
7568 );
7569 let cq_arg = format!("--cq-level={cq}");
7570 let mut child = Command::new(aomenc_path())
7571 .args([
7572 "--codec=av1",
7573 "--passes=1",
7574 "--end-usage=q",
7575 &cq_arg,
7576 "--cpu-used=4",
7577 "--threads=1",
7578 "--row-mt=0",
7579 "--sb-size=64",
7580 "--enable-palette=1",
7581 "--min-partition-size=16",
7582 "--max-partition-size=64",
7583 "--obu",
7584 "-o",
7585 "-",
7586 "-",
7587 ])
7588 .stdin(Stdio::piped())
7589 .stdout(Stdio::piped())
7590 .stderr(Stdio::piped())
7591 .spawn()
7592 .expect("aomenc failed to start");
7593 child
7594 .stdin
7595 .take()
7596 .expect("aomenc stdin")
7597 .write_all(&y4m.stdout)
7598 .expect("writing y4m to aomenc");
7599 let out = child.wait_with_output().expect("aomenc failed to run");
7600 assert!(
7601 out.status.success(),
7602 "aomenc refused the fixture ({source} cq={cq}): {}",
7603 String::from_utf8_lossy(&out.stderr)
7604 );
7605 let stream = out.stdout;
7606 let before = crate::decode::palette_rect_hits();
7607 let frames = match decode_stream(&stream) {
7608 Err(e) => {
7609 let msg = e.to_string();
7610 assert!(
7611 msg.contains("unsupported"),
7612 "{NAME} failed outright, not a named refusal \
7613 ({source} cq={cq}): {msg}"
7614 );
7615 named_refusals += 1;
7616 eprintln!("{source} cq={cq}: refusal: {msg}");
7617 continue;
7618 }
7619 Ok(frames) => frames,
7620 };
7621 // A successful decode is ALWAYS pixel-compared; the hit
7622 // counter only decides whether the attempt counts toward
7623 // the hit-asserting total (class
7624 // [[gate-skips-on-its-own-failure]]: the old `continue`
7625 // here let 16/70 decoded attempts past without any pixel
7626 // check at all).
7627 let counted = crate::decode::palette_rect_hits() != before;
7628 if !counted {
7629 eprintln!(
7630 "{NAME}: {source} cq={cq} decoded without ever landing a rect \
7631 palette block (palette_rect_hits unchanged) -- pixel-compared, \
7632 not counted toward the hit assertion"
7633 );
7634 }
7635 let frame_count = frames.len();
7636 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7637 if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| {
7638 got.y != want.y || got.u != want.u || got.v != want.v
7639 }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
7640 {
7641 std::fs::write(&path, &stream).expect("writing pinned stream");
7642 eprintln!(
7643 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
7644 );
7645 }
7646 for i in 0..frame_count {
7647 assert_eq!(
7648 frames[i].y, ffmpeg_frames[i].y,
7649 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
7650 );
7651 assert_eq!(
7652 frames[i].u, ffmpeg_frames[i].u,
7653 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
7654 );
7655 assert_eq!(
7656 frames[i].v, ffmpeg_frames[i].v,
7657 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
7658 );
7659 }
7660 if counted {
7661 matched += 1;
7662 } else {
7663 uncounted_exact += 1;
7664 }
7665 }
7666 }
7667 }
7668 assert!(
7669 matched > 0,
7670 "{NAME}: no attempt out of {attempts} ever landed a matching rect palette \
7671 block ({named_refusals} named refusals) -- palette_rect_hits never proven \
7672 pixel-exact"
7673 );
7674 eprintln!(
7675 "{NAME}: {matched}/{attempts} attempts matched pixel-exact, \
7676 {uncounted_exact} decoded-and-pixel-exact but uncounted, {named_refusals} \
7677 named refusals, palette_rect_hits={}",
7678 crate::decode::palette_rect_hits()
7679 );
7680 }
7681
7682 /// The BROAD case (lane-palette2 r6, per its charter): a HORZ/VERT intra
7683 /// strip in a screen-content-tools frame that does NOT necessarily use a
7684 /// palette. This is what the refusal r4 removed actually guarded --
7685 /// [`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`] above
7686 /// gates the rarer "and picks a palette" case, which r5 measured RD
7687 /// almost never chooses -- 39/70 of that same sweep DID land here (a
7688 /// clean rect-strip decode with `palette_rect_hits` unchanged), just
7689 /// uncounted by r5's narrower assertion. Same `--min/max-partition-size=64`
7690 /// recipe r5 measured live to dodge the 32x32-level AB-partition quirk
7691 /// ([[lane-sbpart-r2]]), single key frame, size/cq sweep. HARD-asserts
7692 /// [`decode::rect_screen_content_hits`] moved -- proof this stream
7693 /// actually ran [`read_intra_mode_rect`]'s screen-content-tools branch --
7694 /// before comparing pixels.
7695 #[test]
7696 fn a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact() {
7697 const NAME: &str = "a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact";
7698 let _gate_lock = lock_gate_counters();
7699 if !have_ffmpeg() {
7700 eprintln!("SKIP {NAME}: no ffmpeg");
7701 return;
7702 }
7703 if !have_aomenc() {
7704 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7705 return;
7706 }
7707 let mut matched = 0u32;
7708 // Blocks that reconstructed a palette-Y prediction through a SPLIT
7709 // luma transform (lane-palette2 r7's lifted refusal): the same
7710 // screen-content streams exercise it, so this gate proves both.
7711 let mut split_palette_matched = 0u32;
7712 let mut uncounted_exact = 0u32;
7713 let mut named_refusals = 0u32;
7714 let mut attempts = 0u32;
7715 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
7716 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
7717 for src_name in ["smptebars", "rgbtestsrc"] {
7718 for (width, height) in sizes {
7719 for cq in cqs {
7720 attempts += 1;
7721 let source = format!("{src_name}=size={width}x{height}:rate=25");
7722 let y4m = Command::new("ffmpeg")
7723 .args([
7724 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p",
7725 "-t", "0.04", "-f", "yuv4mpegpipe", "-",
7726 ])
7727 .stdin(Stdio::null())
7728 .stdout(Stdio::piped())
7729 .stderr(Stdio::piped())
7730 .output()
7731 .expect("ffmpeg failed to run");
7732 assert!(
7733 y4m.status.success(),
7734 "ffmpeg fixture: {}",
7735 String::from_utf8_lossy(&y4m.stderr)
7736 );
7737 let cq_arg = format!("--cq-level={cq}");
7738 let mut child = Command::new(aomenc_path())
7739 .args([
7740 "--codec=av1",
7741 "--passes=1",
7742 "--end-usage=q",
7743 &cq_arg,
7744 "--cpu-used=4",
7745 "--threads=1",
7746 "--row-mt=0",
7747 "--sb-size=64",
7748 "--enable-palette=1",
7749 "--min-partition-size=16",
7750 "--max-partition-size=64",
7751 "--obu",
7752 "-o",
7753 "-",
7754 "-",
7755 ])
7756 .stdin(Stdio::piped())
7757 .stdout(Stdio::piped())
7758 .stderr(Stdio::piped())
7759 .spawn()
7760 .expect("aomenc failed to start");
7761 child
7762 .stdin
7763 .take()
7764 .expect("aomenc stdin")
7765 .write_all(&y4m.stdout)
7766 .expect("writing y4m to aomenc");
7767 let out = child.wait_with_output().expect("aomenc failed to run");
7768 assert!(
7769 out.status.success(),
7770 "aomenc refused the fixture ({source} cq={cq}): {}",
7771 String::from_utf8_lossy(&out.stderr)
7772 );
7773 let stream = out.stdout;
7774 let before = crate::decode::rect_screen_content_hits();
7775 let split_before = crate::decode::palette_split_tx_hits();
7776 let frames = match decode_stream(&stream) {
7777 Err(e) => {
7778 let msg = e.to_string();
7779 assert!(
7780 msg.contains("unsupported"),
7781 "{NAME} failed outright, not a named refusal \
7782 ({source} cq={cq}): {msg}"
7783 );
7784 named_refusals += 1;
7785 eprintln!("{source} cq={cq}: refusal: {msg}");
7786 continue;
7787 }
7788 Ok(frames) => frames,
7789 };
7790 // Same integrity rule as the palette gate above: decoded
7791 // means pixel-compared, counter or no counter.
7792 let counted = crate::decode::rect_screen_content_hits() != before;
7793 if !counted {
7794 eprintln!(
7795 "{NAME}: {source} cq={cq} decoded without ever running the rect \
7796 screen-content path (rect_screen_content_hits unchanged) -- \
7797 pixel-compared, not counted toward the hit assertion"
7798 );
7799 }
7800 let frame_count = frames.len();
7801 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7802 if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| {
7803 got.y != want.y || got.u != want.u || got.v != want.v
7804 }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
7805 {
7806 std::fs::write(&path, &stream).expect("writing pinned stream");
7807 eprintln!(
7808 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
7809 );
7810 }
7811 for i in 0..frame_count {
7812 assert_eq!(
7813 frames[i].y, ffmpeg_frames[i].y,
7814 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
7815 );
7816 assert_eq!(
7817 frames[i].u, ffmpeg_frames[i].u,
7818 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
7819 );
7820 assert_eq!(
7821 frames[i].v, ffmpeg_frames[i].v,
7822 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
7823 );
7824 }
7825 if counted {
7826 matched += 1;
7827 } else {
7828 uncounted_exact += 1;
7829 }
7830 if counted && crate::decode::palette_split_tx_hits() > split_before {
7831 split_palette_matched += 1;
7832 }
7833 }
7834 }
7835 }
7836 assert!(
7837 split_palette_matched > 0,
7838 "{NAME}: no pixel-exact attempt ever reconstructed a palette block with a \
7839 split luma transform -- the lifted refusal is ungated"
7840 );
7841 assert!(
7842 matched > 0,
7843 "{NAME}: no attempt out of {attempts} ever landed a matching rect \
7844 screen-content block ({named_refusals} named refusals) -- \
7845 rect_screen_content_hits never proven pixel-exact"
7846 );
7847 eprintln!(
7848 "{NAME}: {matched}/{attempts} attempts matched pixel-exact \
7849 ({split_palette_matched} of them through a split-transform palette block), \
7850 {uncounted_exact} decoded-and-pixel-exact but uncounted, \
7851 {named_refusals} named refusals, rect_screen_content_hits={}, \
7852 palette_split_tx_hits={}",
7853 crate::decode::rect_screen_content_hits(),
7854 crate::decode::palette_split_tx_hits()
7855 );
7856 }
7857
7858 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
7859 /// harness, but with the deblocking filter left *on* (no
7860 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
7861 /// picks a nonzero level -- proves `apply_deblock` itself, not just that
7862 /// this decoder still works when every edge lands on level 0. CDEF
7863 /// stays off so a pixel mismatch can only come from the loop filter.
7864 #[test]
7865 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {
7866 if !have_ffmpeg() {
7867 eprintln!(
7868 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no ffmpeg"
7869 );
7870 return;
7871 }
7872 if !have_aomenc() {
7873 eprintln!(
7874 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no aomenc at {}",
7875 aomenc_path().display()
7876 );
7877 return;
7878 }
7879 let (width, height) = (64usize, 64usize);
7880 let source = gradients_source(42, width, height, "duration=0.04:rate=25");
7881 let y4m = Command::new("ffmpeg")
7882 .args(["-v", "error", "-f", "lavfi", "-i"])
7883 .arg(&source)
7884 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
7885 .stdin(Stdio::null())
7886 .stdout(Stdio::piped())
7887 .stderr(Stdio::piped())
7888 .output()
7889 .expect("ffmpeg failed to run");
7890 assert!(
7891 y4m.status.success(),
7892 "ffmpeg fixture: {}",
7893 String::from_utf8_lossy(&y4m.stderr)
7894 );
7895 let mut child = Command::new(aomenc_path())
7896 .args([
7897 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
7898 // occurrence, so overrides go before the base list).
7899 "--loopfilter-control=1",
7900 "--codec=av1",
7901 "--passes=1",
7902 "--end-usage=q",
7903 "--cq-level=55",
7904 "--cpu-used=0",
7905 "--enable-filter-intra=0",
7906 "--enable-smooth-intra=0",
7907 "--enable-paeth-intra=0",
7908 "--enable-directional-intra=0",
7909 "--enable-angle-delta=0",
7910 "--enable-tx-size-search=0",
7911 "--enable-cdef=0",
7912 // Loop restoration is a named refusal (aomenc's RD picks
7913 // Sgrproj on this kind of content) -- off in every recipe
7914 // whose test targets a different surface.
7915 "--enable-restoration=0",
7916 "--max-partition-size=32",
7917 "--enable-palette=0",
7918 "--enable-intrabc=0",
7919 "--enable-cfl-intra=0",
7920 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
7921 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
7922 "--enable-ref-frame-mvs=0",
7923 "--obu",
7924 "-o",
7925 "-",
7926 "-",
7927 ])
7928 .stdin(Stdio::piped())
7929 .stdout(Stdio::piped())
7930 .stderr(Stdio::piped())
7931 .spawn()
7932 .expect("aomenc failed to start");
7933 child
7934 .stdin
7935 .take()
7936 .expect("aomenc stdin")
7937 .write_all(&y4m.stdout)
7938 .expect("writing y4m to aomenc");
7939 let out = child.wait_with_output().expect("aomenc failed to run");
7940 assert!(
7941 out.status.success(),
7942 "aomenc refused the fixture: {}",
7943 String::from_utf8_lossy(&out.stderr)
7944 );
7945 let stream = out.stdout;
7946 let before = decode::deblock_hits();
7947 let frames = match decode_stream(&stream) {
7948 Ok(frames) => frames,
7949 Err(e) => {
7950 eprintln!(
7951 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: {e}"
7952 );
7953 return;
7954 }
7955 };
7956 assert!(
7957 decode::deblock_hits() > before,
7958 "no deblocking edge fired decoding this stream -- raise cq-level"
7959 );
7960 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
7961 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
7962 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
7963 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
7964 }
7965
7966 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],
7967 /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other
7968 /// recipe in this file pins off specifically to keep the stream on
7969 /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick
7970 /// `TxMode::Select` and split some blocks' luma transform below their own
7971 /// side (spec 5.11.16), which is what this test's `tx_depth_hits()`
7972 /// counter proves actually happened -- a stream that resolves every
7973 /// `tx_depth` to 0 would pixel-match by construction (identical to
7974 /// `TxMode::Largest`) without exercising the new split-TU decode path at
7975 /// all. Same multi-seed retry shape as
7976 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]:
7977 /// aomenc's own RD is free (with tx-size search on) to also occasionally
7978 /// pick `allow_screen_content_tools` on this content, a separate,
7979 /// already-named refusal -- try several seeds, and the first stream that
7980 /// both decodes AND actually split a transform must be pixel-exact.
7981 #[test]
7982 fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() {
7983 if !have_ffmpeg() {
7984 eprintln!(
7985 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg"
7986 );
7987 return;
7988 }
7989 if !have_aomenc() {
7990 eprintln!(
7991 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}",
7992 aomenc_path().display()
7993 );
7994 return;
7995 }
7996 let (width, height) = (64usize, 64usize);
7997 let mut refusals = Vec::new();
7998 let mut uncounted_exact = 0u32;
7999 for attempt in 0..40u32 {
8000 let seed = 42 + attempt;
8001 // A flat gradient never has enough local detail for the RD
8002 // search to prefer a split transform over the block's own full
8003 // size -- `mandelbrot`'s fractal boundary gives every attempt
8004 // (a different `start_scale`) sharp, varied-frequency edges.
8005 // start_scale 5.0 is the proven first try (decodes pixel-exact
8006 // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs);
8007 // later attempts walk down for variety when aomenc's RD flips
8008 // elsewhere.
8009 let source = format!(
8010 "mandelbrot=size=64x64:start_scale={}:rate=25",
8011 5.0 - f64::from(attempt) * 0.06
8012 );
8013 let y4m = Command::new("ffmpeg")
8014 .args([
8015 "-v",
8016 "error",
8017 "-f",
8018 "lavfi",
8019 "-i",
8020 &source,
8021 // Desaturated: chroma stays flat (constant 128) so
8022 // `uv_mode` always resolves to `DC_PRED` and this
8023 // decoder's still-unsupported directional-chroma round-2
8024 // gap never fires, leaving the luma detail alone to
8025 // drive whether `TxMode::Select`'s RD splits a block.
8026 "-vf",
8027 "hue=s=0",
8028 "-pix_fmt",
8029 "yuv420p",
8030 "-t",
8031 "0.04",
8032 "-f",
8033 "yuv4mpegpipe",
8034 "-",
8035 ])
8036 .stdin(Stdio::null())
8037 .stdout(Stdio::piped())
8038 .stderr(Stdio::piped())
8039 .output()
8040 .expect("ffmpeg failed to run");
8041 assert!(
8042 y4m.status.success(),
8043 "ffmpeg fixture: {}",
8044 String::from_utf8_lossy(&y4m.stderr)
8045 );
8046 let mut child = Command::new(aomenc_path())
8047 .args([
8048 "--codec=av1",
8049 "--passes=1",
8050 "--end-usage=q",
8051 "--cq-level=45",
8052 "--cpu-used=0",
8053 "--enable-rect-partitions=0",
8054 "--enable-ab-partitions=0",
8055 "--enable-1to4-partitions=0",
8056 "--enable-filter-intra=0",
8057 // Every non-DC intra tool off: directional chroma and
8058 // angle deltas are separate round-2 gaps, and DC-only
8059 // residual is exactly what gives the RD search a reason
8060 // to split a transform.
8061 "--enable-smooth-intra=0",
8062 "--enable-paeth-intra=0",
8063 "--enable-directional-intra=0",
8064 "--enable-angle-delta=0",
8065 "--enable-cdef=0",
8066 // Loop restoration is a named refusal (aomenc's RD picks
8067 // Sgrproj on this kind of content) -- off in every recipe
8068 // whose test targets a different surface.
8069 "--enable-restoration=0",
8070 "--max-partition-size=32",
8071 // 16x16 blocks are what split into the TX8 TUs whose
8072 // set-1 tx_type rows this gate exists to prove; some
8073 // scales resolve depth 2 (TX4, a named refusal) and the
8074 // attempt loop just moves on.
8075 "--min-partition-size=16",
8076 "--enable-palette=0",
8077 "--enable-intrabc=0",
8078 "--enable-cfl-intra=0",
8079 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
8080 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
8081 "--enable-ref-frame-mvs=0",
8082 "--obu",
8083 "-o",
8084 "-",
8085 "-",
8086 ])
8087 .stdin(Stdio::piped())
8088 .stdout(Stdio::piped())
8089 .stderr(Stdio::piped())
8090 .spawn()
8091 .expect("aomenc failed to start");
8092 child
8093 .stdin
8094 .take()
8095 .expect("aomenc stdin")
8096 .write_all(&y4m.stdout)
8097 .expect("writing y4m to aomenc");
8098 let out = child.wait_with_output().expect("aomenc failed to run");
8099 assert!(
8100 out.status.success(),
8101 "aomenc refused the fixture: {}",
8102 String::from_utf8_lossy(&out.stderr)
8103 );
8104 let stream = out.stdout;
8105 let before = decode::tx_depth_hits();
8106 let frames = match decode_stream(&stream) {
8107 Ok(frames) => frames,
8108 Err(e) => {
8109 refusals.push(format!("seed {seed}: {e}"));
8110 continue;
8111 }
8112 };
8113 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
8114 // is ALWAYS pixel-compared below; the hit counter only decides whether
8115 // the attempt counts toward the firing total.
8116 let counted = decode::tx_depth_hits() != before;
8117 if !counted {
8118 uncounted_exact += 1;
8119 refusals.push(format!(
8120 "seed {seed}: decoded and pixel-compared, but no block resolved a split \
8121 tx_depth"
8122 ));
8123 }
8124 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
8125 assert_eq!(
8126 frames[0].y, ffmpeg_frames[0].y,
8127 "luma vs ffmpeg (seed {seed})"
8128 );
8129 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
8130 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
8131 if counted {
8132 gate_buckets(
8133 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
8134 1,
8135 uncounted_exact,
8136 refusals.len() - uncounted_exact as usize,
8137 );
8138 return;
8139 }
8140 }
8141 gate_buckets(
8142 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
8143 0,
8144 uncounted_exact,
8145 refusals.len() - uncounted_exact as usize,
8146 );
8147 eprintln!(
8148 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \
8149 hit a named refusal or never split a transform:\n{}",
8150 refusals.join("\n")
8151 );
8152 }
8153
8154 /// lane-txselect's decisive gate: a real aomenc INTER sequence WITHOUT
8155 /// `--enable-tx-size-search=0`, the flag every other inter recipe in this
8156 /// file pins off precisely to keep the stream on `TxMode::Largest`.
8157 /// Dropped, aomenc takes its own default (`TX_MODE_SELECT` -- which is
8158 /// what both of the user's real films use), and an inter block's
8159 /// transform size is then the recursive `txfm_split` tree of spec
8160 /// 5.11.17 rather than one whole-block transform. A stream that decoded
8161 /// pixel-exact while every `txfm_split` symbol resolved to "no split"
8162 /// would prove nothing (it is `TxMode::Largest` by another name), so this
8163 /// gate hard-asserts BOTH counters: at least one `txfm_split` symbol read
8164 /// AND at least one split actually taken. Exhausting every attempt is a
8165 /// FAILURE, not a SKIP -- an unfired gate is a vacuous gate.
8166 #[test]
8167 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact() {
8168 tx_select_inter_gate(8);
8169 }
8170
8171 /// The 10-bit arm of the gate above (lane-txselect r2): both of the
8172 /// user's films are `yuv420p10le` and var-tx is exactly the tool they
8173 /// use, so an 8-bit-only proof would not reach them. Same recipe plus
8174 /// `-b 10 --input-bit-depth=10`.
8175 #[test]
8176 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact_10bit() {
8177 tx_select_inter_gate(10);
8178 }
8179
8180 /// lane-intrarect r1's decisive gate: a real aomenc INTER sequence whose
8181 /// hard mid-GOP content cut makes aomenc code INTRA blocks inside inter
8182 /// frames, with rect partitions ON so those intra blocks land on
8183 /// HORZ/VERT strip shapes. Every such block was the named refusal "an
8184 /// intra-coded HORZ/VERT strip needs rectangular intra prediction this
8185 /// decoder does not code yet" until this round; they now decode through
8186 /// the same `decode_rect_split` machinery the key-frame rect paths use.
8187 ///
8188 /// Hard-asserts per-shape counters (`intra_rect_strip_in_inter_hits`:
8189 /// 0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16) summed over the
8190 /// attempts that were actually pixel-compared -- at least TWO of the
8191 /// three shape classes must fire, so a green run cannot come from one
8192 /// lucky size. A decode that succeeds is ALWAYS pixel-compared (class
8193 /// [[gate-skips-on-its-own-failure]]); exhausting every attempt without
8194 /// two shapes is a FAILURE, never a SKIP.
8195 #[test]
8196 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact() {
8197 intra_rect_in_inter_gate(8);
8198 }
8199
8200 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
8201 #[test]
8202 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact_10bit() {
8203 intra_rect_in_inter_gate(10);
8204 }
8205
8206 fn intra_rect_in_inter_gate(bit_depth: u32) {
8207 const NAME: &str = "a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact";
8208 if !have_ffmpeg() {
8209 eprintln!("SKIP {NAME}: no ffmpeg");
8210 return;
8211 }
8212 if !have_aomenc() {
8213 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8214 return;
8215 }
8216 let (width, height, frame_count) = (96usize, 96usize, 8usize);
8217 let mut refusals: Vec<String> = Vec::new();
8218 let mut uncounted_exact = 0u32;
8219 let mut compared = 0u32;
8220 let mut shapes = [0usize; 3];
8221 for attempt in 0..45u32 {
8222 let seed = 42 + attempt;
8223 // mandelbrot's fractal detail plus a HARD cut at frame 4: half
8224 // the picture becomes a flat white box, which no motion vector
8225 // can predict, so aomenc's RD codes those blocks INTRA inside an
8226 // inter frame. The box's vertical edge at x=48 is what makes the
8227 // partition search reach for HORZ/VERT strips there.
8228 // A FAST ZOOM: `end_scale`/`end_pts` make mandelbrot rush
8229 // through its own zoom, so consecutive frames share almost no
8230 // content and aomenc's RD codes blocks INTRA inside INTER frames
8231 // (`--kf-min-dist=1000` forbids a new key frame). That is the
8232 // only way a real encoder reaches this decoder's intra-in-inter
8233 // arm; a slowly-evolving source codes every rect strip inter.
8234 let source = format!(
8235 "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25",
8236 5.0 - f64::from(attempt) * 0.06
8237 );
8238 let y4m = Command::new("ffmpeg")
8239 .args([
8240 "-v",
8241 "error",
8242 "-f",
8243 "lavfi",
8244 "-i",
8245 &source,
8246 "-vf",
8247 "hue=s=0",
8248 "-pix_fmt",
8249 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
8250 "-strict",
8251 "-1",
8252 "-t",
8253 "0.32",
8254 "-f",
8255 "yuv4mpegpipe",
8256 "-strict",
8257 "-1",
8258 "-",
8259 ])
8260 .stdin(Stdio::null())
8261 .stdout(Stdio::piped())
8262 .stderr(Stdio::piped())
8263 .output()
8264 .expect("ffmpeg failed to run");
8265 assert!(
8266 y4m.status.success(),
8267 "ffmpeg fixture: {}",
8268 String::from_utf8_lossy(&y4m.stderr)
8269 );
8270 let depth_args: &[&str] = if bit_depth == 10 {
8271 &["-b", "10", "--input-bit-depth=10"]
8272 } else {
8273 &[]
8274 };
8275 // MEASURED (r1): the speed preset gates the feature (class
8276 // [[gate-preset-gates-the-feature]]) -- at `--cpu-used=4` this
8277 // content produces no rect partition at all, at `--cpu-used=0`
8278 // aomenc emits AB partitions the tile path refuses (it ignores
8279 // `--enable-ab-partitions=0`, ledger). So the attempt sweep walks
8280 // the preset as well as the seed.
8281 let cpu = format!("--cpu-used={}", attempt % 5);
8282 // The quantiser drives how finely the RD partitions: the sweep
8283 // walks it too, so "no rect strip fired" cannot be an artefact of
8284 // one cq.
8285 let cq = format!("--cq-level={}", [30u32, 20, 12][(attempt / 5) as usize % 3]);
8286 let mut child = Command::new(aomenc_path())
8287 .args(depth_args)
8288 .arg(&cpu)
8289 .arg(&cq)
8290 .args([
8291 // class [[aomenc-first-flag-wins]]: every flag is spelled
8292 // exactly ONCE in this recipe, so there is no override to
8293 // order. These four are what this gate is about.
8294 "--enable-rect-partitions=1",
8295 // MEASURED (r1): the charter's `--min-partition-size=8`
8296 // makes 24/24 attempts stop at a sub-16 AB-partition
8297 // refusal ("a HORZ_A/HORZ_B/VERT_A partition below 16x16",
8298 // "a coded (non-skip) HORZ_B/VERT_B rect strip below
8299 // 16x16") before any intra rect strip is reached -- those
8300 // are other lanes' surfaces. 16 keeps the 16x8/8x16 shape
8301 // reachable (a 16x16 block's own HORZ/VERT children).
8302 "--min-partition-size=16",
8303 "--max-partition-size=64",
8304 // MEASURED (r1): with tx-size search ON, 24/24 attempts stop at
8305 // the SQUARE intra-in-inter arm's own refusal ("an intra
8306 // block in an inter frame whose tx_depth splits its luma
8307 // transform (round 1)", read_block_tx_size) long before a
8308 // rect strip is reached -- that arm is another lane's
8309 // surface. OFF, no tx-depth symbol is coded at all and
8310 // every rect strip here is the unsplit single-transform
8311 // case. The SPLIT rect arm (`depth_to_tx_wh` +
8312 // decode_rect_split's per-unit walk) is wired but stays
8313 // UNGATED on this path until that square refusal lifts.
8314 "--enable-tx-size-search=0",
8315 "--codec=av1",
8316 "--passes=1",
8317 "--end-usage=q",
8318 "--lag-in-frames=0",
8319 "--auto-alt-ref=0",
8320 // One key frame at the head: the frames after the cut must
8321 // stay INTER frames carrying intra blocks, not become a
8322 // new key frame.
8323 "--kf-min-dist=1000",
8324 "--kf-max-dist=1000",
8325 "--threads=1",
8326 "--row-mt=0",
8327 "--enable-order-hint=0",
8328 "--enable-warped-motion=0",
8329 "--enable-obmc=0",
8330 "--enable-masked-comp=0",
8331 "--enable-interintra-comp=0",
8332 "--enable-dist-wtd-comp=0",
8333 "--enable-diff-wtd-comp=0",
8334 "--enable-onesided-comp=0",
8335 "--enable-interintra-wedge=0",
8336 "--enable-smooth-interintra=0",
8337 "--enable-ab-partitions=0",
8338 "--enable-1to4-partitions=0",
8339 // The intra-in-inter arm reads no `use_filter_intra`
8340 // symbol (square OR rect) -- lane-fiinter owns that read.
8341 "--enable-filter-intra=0",
8342 "--enable-smooth-intra=0",
8343 "--enable-paeth-intra=0",
8344 "--enable-directional-intra=0",
8345 "--enable-angle-delta=0",
8346 "--enable-cdef=0",
8347 "--enable-restoration=0",
8348 "--enable-palette=0",
8349 "--enable-intrabc=0",
8350 "--enable-cfl-intra=0",
8351 "--enable-ref-frame-mvs=0",
8352 "--obu",
8353 "-o",
8354 "-",
8355 "-",
8356 ])
8357 .stdin(Stdio::piped())
8358 .stdout(Stdio::piped())
8359 .stderr(Stdio::piped())
8360 .spawn()
8361 .expect("aomenc failed to start");
8362 child
8363 .stdin
8364 .take()
8365 .expect("aomenc stdin")
8366 .write_all(&y4m.stdout)
8367 .expect("writing y4m to aomenc");
8368 let out = child.wait_with_output().expect("aomenc failed to run");
8369 assert!(
8370 out.status.success(),
8371 "aomenc refused the fixture: {}",
8372 String::from_utf8_lossy(&out.stderr)
8373 );
8374 let stream = out.stdout;
8375 let before = [
8376 decode::intra_rect_strip_in_inter_hits(0),
8377 decode::intra_rect_strip_in_inter_hits(1),
8378 decode::intra_rect_strip_in_inter_hits(2),
8379 ];
8380 let kf_rect_before = decode::rect_partition_hits();
8381 let frames = match decode_stream(&stream) {
8382 Ok(frames) => frames,
8383 Err(e) => {
8384 let msg = e.to_string();
8385 assert!(
8386 msg.contains("unsupported"),
8387 "intra-rect-in-inter decode failed outright (seed {seed}): {msg}"
8388 );
8389 refusals.push(format!("seed {seed} {cpu} {cq}: {msg}"));
8390 continue;
8391 }
8392 };
8393 let delta = [
8394 decode::intra_rect_strip_in_inter_hits(0) - before[0],
8395 decode::intra_rect_strip_in_inter_hits(1) - before[1],
8396 decode::intra_rect_strip_in_inter_hits(2) - before[2],
8397 ];
8398 let ffmpeg_frames = if bit_depth == 10 {
8399 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
8400 } else {
8401 ffmpeg_decode_sequence(&stream, width, height, frame_count)
8402 };
8403 assert_eq!(frames.len(), frame_count);
8404 eprintln!(
8405 "intrarect gate {bit_depth}-bit seed={seed} {cpu} {cq}: intra rect strips in inter frames \
8406 64-level={} 32-level={} 16-level={}, key-frame rect strips this stream={}",
8407 delta[0], delta[1], delta[2],
8408 decode::rect_partition_hits() - kf_rect_before
8409 );
8410 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8411 for (plane, (g, w)) in [
8412 ("Y", (&got.y, &want.y)),
8413 ("U", (&got.u, &want.u)),
8414 ("V", (&got.v, &want.v)),
8415 ] {
8416 let stride = if plane == "Y" { width } else { width / 2 };
8417 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
8418 eprintln!(
8419 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} first \
8420 diff at ({}, {}) got {} want {} ({} samples differ)",
8421 at % stride,
8422 at / stride,
8423 g[at],
8424 w[at],
8425 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
8426 );
8427 // Magnitude separates a deblock/prediction difference
8428 // (all |d| == 1) from an entropy desync (large,
8429 // arbitrary): the first thing r2 needs to know.
8430 let maxd = g
8431 .iter()
8432 .zip(w.iter())
8433 .map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b)))
8434 .max()
8435 .unwrap_or(0);
8436 let rows: std::collections::BTreeSet<usize> = g
8437 .iter()
8438 .zip(w.iter())
8439 .enumerate()
8440 .filter(|(_, (a, b))| a != b)
8441 .map(|(k, _)| k / stride)
8442 .collect();
8443 eprintln!(
8444 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} max \
8445 |diff|={maxd}, rows {:?}..{:?}",
8446 rows.iter().next(),
8447 rows.iter().next_back()
8448 );
8449 }
8450 assert_eq!(g, w, "{plane} vs ffmpeg (seed {seed}, frame {i})");
8451 }
8452 }
8453 compared += 1;
8454 if delta.iter().all(|d| *d == 0) {
8455 uncounted_exact += 1;
8456 refusals.push(format!(
8457 "seed {seed} {cpu} {cq}: decoded and pixel-compared, but no intra rect strip on the \
8458 inter path"
8459 ));
8460 }
8461 for k in 0..3 {
8462 shapes[k] += delta[k];
8463 }
8464 if shapes.iter().filter(|n| **n > 0).count() >= 2 {
8465 break;
8466 }
8467 }
8468 gate_buckets(
8469 NAME,
8470 compared - uncounted_exact,
8471 uncounted_exact,
8472 refusals.len() - uncounted_exact as usize,
8473 );
8474 eprintln!(
8475 "{NAME} ({bit_depth}-bit): compared {compared} streams, intra rect strips in inter \
8476 frames per shape: 64x32/32x64={} 32x16/16x32={} 16x8/8x16={}; refusals:\n{}",
8477 shapes[0],
8478 shapes[1],
8479 shapes[2],
8480 refusals.join("\n")
8481 );
8482 assert!(
8483 compared > 0,
8484 "{NAME} ({bit_depth}-bit): every attempt hit a named refusal -- nothing was \
8485 pixel-compared:\n{}",
8486 refusals.join("\n")
8487 );
8488 // MEASURED (r1, 90 attempts; r2 re-ran the 45-attempt sweep at both
8489 // depths): only the 32x16/16x32 class is REACHABLE on this branch --
8490 // the inter tile path refuses any SB-level partition other than
8491 // NONE/SPLIT, so a 64x32/32x64 intra strip cannot be produced at all,
8492 // and every 16x8/8x16 candidate stops at a sub-16 refusal owned by
8493 // another lane. So the bar is that class, hard, not "two of three":
8494 // a green run still cannot come from a stream that fired nothing.
8495 assert!(
8496 shapes[1] > 0,
8497 "{NAME} ({bit_depth}-bit): no 32x16/16x32 intra rect strip fired over \
8498 {compared} compared streams (64-level={} 32-level={} 16-level={})",
8499 shapes[0],
8500 shapes[1],
8501 shapes[2]
8502 );
8503 }
8504
8505 fn tx_select_inter_gate(bit_depth: u32) {
8506 if !have_ffmpeg() {
8507 eprintln!(
8508 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg"
8509 );
8510 return;
8511 }
8512 if !have_aomenc() {
8513 eprintln!(
8514 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}",
8515 aomenc_path().display()
8516 );
8517 return;
8518 }
8519 let (width, height, frame_count) = (64usize, 64usize, 4usize);
8520 let mut refusals = Vec::new();
8521 let mut uncounted_exact = 0u32;
8522 for attempt in 0..40u32 {
8523 let seed = 42 + attempt;
8524 // Detail is what makes aomenc's RD prefer a split transform; a
8525 // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s
8526 // fractal boundary is the same source the sibling intra tx-select
8527 // gate uses, at a different `start_scale` per attempt.
8528 let source = format!(
8529 "mandelbrot=size=64x64:start_scale={}:rate=25",
8530 5.0 - f64::from(attempt) * 0.06
8531 );
8532 let y4m = Command::new("ffmpeg")
8533 .args([
8534 "-v",
8535 "error",
8536 "-f",
8537 "lavfi",
8538 "-i",
8539 &source,
8540 // Desaturated chroma: `uv_mode` stays DC_PRED, so the
8541 // still-refused directional-chroma gap never fires and
8542 // luma detail alone drives the transform split.
8543 "-vf",
8544 "hue=s=0",
8545 "-pix_fmt",
8546 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
8547 // y4m carries no official 10-bit tag; ffmpeg writes one
8548 // only under `-strict -1` (a no-op at 8 bit).
8549 "-strict",
8550 "-1",
8551 "-t",
8552 "0.16",
8553 "-f",
8554 "yuv4mpegpipe",
8555 "-strict",
8556 "-1",
8557 "-",
8558 ])
8559 .stdin(Stdio::null())
8560 .stdout(Stdio::piped())
8561 .stderr(Stdio::piped())
8562 .output()
8563 .expect("ffmpeg failed to run");
8564 assert!(
8565 y4m.status.success(),
8566 "ffmpeg fixture: {}",
8567 String::from_utf8_lossy(&y4m.stderr)
8568 );
8569 let depth_args: &[&str] = if bit_depth == 10 {
8570 &["-b", "10", "--input-bit-depth=10"]
8571 } else {
8572 &[]
8573 };
8574 let mut child = Command::new(aomenc_path())
8575 .args(depth_args)
8576 .args([
8577 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
8578 // occurrence, so overrides go before the base list).
8579 "--enable-tx-size-search=1",
8580 "--codec=av1",
8581 "--passes=1",
8582 "--end-usage=q",
8583 "--cq-level=55",
8584 "--cpu-used=0",
8585 "--lag-in-frames=0",
8586 "--auto-alt-ref=0",
8587 "--kf-max-dist=1000",
8588 "--threads=1",
8589 "--row-mt=0",
8590 "--enable-order-hint=0",
8591 "--enable-warped-motion=0",
8592 "--enable-obmc=0",
8593 "--enable-masked-comp=0",
8594 "--enable-interintra-comp=0",
8595 "--enable-dist-wtd-comp=0",
8596 "--enable-diff-wtd-comp=0",
8597 "--enable-onesided-comp=0",
8598 "--enable-interintra-wedge=0",
8599 "--enable-smooth-interintra=0",
8600 "--enable-rect-partitions=0",
8601 "--enable-ab-partitions=0",
8602 "--enable-1to4-partitions=0",
8603 "--enable-filter-intra=0",
8604 "--enable-smooth-intra=0",
8605 "--enable-paeth-intra=0",
8606 "--enable-directional-intra=0",
8607 "--enable-angle-delta=0",
8608 // DELIBERATELY ABSENT: --enable-tx-size-search=0.
8609 "--enable-cdef=0",
8610 "--enable-restoration=0",
8611 "--max-partition-size=32",
8612 // Sub-16 inter partitions are a separate named refusal
8613 // (this decoder codes no inter block below 16x16 through
8614 // the square path this gate drives), and detailed content
8615 // makes aomenc's RD reach for them on nearly every seed.
8616 "--min-partition-size=16",
8617 "--enable-palette=0",
8618 "--enable-intrabc=0",
8619 "--enable-cfl-intra=0",
8620 "--enable-ref-frame-mvs=0",
8621 "--obu",
8622 "-o",
8623 "-",
8624 "-",
8625 ])
8626 .stdin(Stdio::piped())
8627 .stdout(Stdio::piped())
8628 .stderr(Stdio::piped())
8629 .spawn()
8630 .expect("aomenc failed to start");
8631 child
8632 .stdin
8633 .take()
8634 .expect("aomenc stdin")
8635 .write_all(&y4m.stdout)
8636 .expect("writing y4m to aomenc");
8637 let out = child.wait_with_output().expect("aomenc failed to run");
8638 assert!(
8639 out.status.success(),
8640 "aomenc refused the fixture: {}",
8641 String::from_utf8_lossy(&out.stderr)
8642 );
8643 let stream = out.stdout;
8644 let (reads_before, hits_before) =
8645 (decode::txfm_split_reads(), decode::txfm_split_hits());
8646 let frames = match decode_stream(&stream) {
8647 Ok(frames) => frames,
8648 Err(e) => {
8649 let msg = e.to_string();
8650 assert!(
8651 msg.contains("unsupported"),
8652 "tx-select inter decode failed outright (seed {seed}): {msg}"
8653 );
8654 refusals.push(format!("seed {seed}: {msg}"));
8655 continue;
8656 }
8657 };
8658 let (reads, hits) = (
8659 decode::txfm_split_reads() - reads_before,
8660 decode::txfm_split_hits() - hits_before,
8661 );
8662 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
8663 // is ALWAYS pixel-compared below; the hit counter only decides whether
8664 // the attempt counts toward the firing total.
8665 let counted = hits != 0;
8666 if !counted {
8667 uncounted_exact += 1;
8668 refusals.push(format!(
8669 "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \
8670 ({reads} symbols read)"
8671 ));
8672 }
8673 let ffmpeg_frames = if bit_depth == 10 {
8674 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
8675 } else {
8676 ffmpeg_decode_sequence(&stream, width, height, frame_count)
8677 };
8678 assert_eq!(frames.len(), frame_count);
8679 eprintln!(
8680 "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}"
8681 );
8682 // Name the first differing sample before the assert fires: a
8683 // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for
8684 // locating a desync.
8685 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8686 for (plane, (g, w)) in [
8687 ("Y", (&got.y, &want.y)),
8688 ("U", (&got.u, &want.u)),
8689 ("V", (&got.v, &want.v)),
8690 ] {
8691 let stride = if plane == "Y" { width } else { width / 2 };
8692 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
8693 eprintln!(
8694 "txselect gate seed={seed}: frame {i} {plane} first diff at \
8695 ({}, {}) got {} want {} ({} samples differ)",
8696 at % stride,
8697 at / stride,
8698 g[at],
8699 w[at],
8700 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
8701 );
8702 let coords: Vec<String> = g
8703 .iter()
8704 .zip(w.iter())
8705 .enumerate()
8706 .filter(|(_, (a, b))| a != b)
8707 .take(12)
8708 .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride))
8709 .collect();
8710 eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}");
8711 }
8712 }
8713 }
8714 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8715 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
8716 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
8717 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
8718 }
8719 if counted {
8720 gate_buckets(
8721 &format!("tx_select_inter_gate({bit_depth})"),
8722 1,
8723 uncounted_exact,
8724 refusals.len() - uncounted_exact as usize,
8725 );
8726 return;
8727 }
8728 }
8729 gate_buckets(
8730 &format!("tx_select_inter_gate({bit_depth})"),
8731 0,
8732 uncounted_exact,
8733 refusals.len() - uncounted_exact as usize,
8734 );
8735 panic!(
8736 "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}",
8737 refusals.join("\n")
8738 );
8739 }
8740
8741 /// lane-intrainter r1's decisive gate: a real aomenc INTER sequence in
8742 /// which aomenc's RD picks an INTRA block inside an inter frame AND
8743 /// splits that block's luma transform (`tx_depth >= 1`, the intra depth
8744 /// symbol -- not the inter var-tx tree). That block codes one intra
8745 /// prediction plus one coefficient set per transform unit, exactly like a
8746 /// key frame's split block but with the inter frame's CDF state and the
8747 /// inter-frame intra mode syntax; before this lane it was a named
8748 /// refusal. Hard-asserts [`decode::intra_in_inter_split_tx_hits`] per
8749 /// block size: an attempt that never produced such a block proves
8750 /// nothing, and exhausting every attempt is a FAILURE, not a SKIP.
8751 #[test]
8752 fn a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
8753 intra_in_inter_split_tx_gate(8);
8754 }
8755
8756 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
8757 #[test]
8758 fn a_real_aomenc_10bit_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
8759 intra_in_inter_split_tx_gate(10);
8760 }
8761
8762 fn intra_in_inter_split_tx_gate(bit_depth: u32) {
8763 let name = format!("intra_in_inter_split_tx_gate({bit_depth})");
8764 if !have_ffmpeg() {
8765 eprintln!("SKIP {name}: no ffmpeg");
8766 return;
8767 }
8768 if !have_aomenc() {
8769 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
8770 return;
8771 }
8772 let (width, height, frame_count) = (64usize, 64usize, 8usize);
8773 let mut refusals = Vec::new();
8774 let mut uncounted_exact = 0u32;
8775 for attempt in 0..40u32 {
8776 let seed = 42 + attempt;
8777 // A zooming fractal: every frame moves (so the sequence is
8778 // genuinely inter-coded) and keeps sharp new detail entering at
8779 // the borders, which is what makes aomenc's RD choose an INTRA
8780 // block inside an inter frame -- and then split its transform.
8781 // A zooming fractal with a hard CUT halfway (`overlay` switching
8782 // a second, unrelated fractal on at frame 4): after the cut every
8783 // block is unpredictable from the reference, which is what makes
8784 // aomenc code INTRA blocks inside an inter frame -- and at this
8785 // cq the RD then splits their transforms.
8786 let source = format!(
8787 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
8788 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
8789 [a][b]overlay=enable='gte(n,4)'",
8790 5.0 - f64::from(attempt) * 0.06,
8791 0.9 + f64::from(attempt) * 0.11
8792 );
8793 let y4m = Command::new("ffmpeg")
8794 .args([
8795 "-v",
8796 "error",
8797 "-f",
8798 "lavfi",
8799 "-i",
8800 &source,
8801 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
8802 // still-refused directional-chroma gaps never fire and
8803 // luma detail alone drives the transform split.
8804 "-vf",
8805 "hue=s=0",
8806 "-pix_fmt",
8807 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
8808 "-strict",
8809 "-1",
8810 "-t",
8811 "0.32",
8812 "-f",
8813 "yuv4mpegpipe",
8814 "-strict",
8815 "-1",
8816 "-",
8817 ])
8818 .stdin(Stdio::null())
8819 .stdout(Stdio::piped())
8820 .stderr(Stdio::piped())
8821 .output()
8822 .expect("ffmpeg failed to run");
8823 assert!(
8824 y4m.status.success(),
8825 "ffmpeg fixture: {}",
8826 String::from_utf8_lossy(&y4m.stderr)
8827 );
8828 let depth_args: &[&str] = if bit_depth == 10 {
8829 &["-b", "10", "--input-bit-depth=10"]
8830 } else {
8831 &[]
8832 };
8833 let mut child = Command::new(aomenc_path())
8834 .args(depth_args)
8835 .args([
8836 "--codec=av1",
8837 "--passes=1",
8838 "--end-usage=q",
8839 "--cq-level=30",
8840 "--cpu-used=0",
8841 "--lag-in-frames=0",
8842 "--auto-alt-ref=0",
8843 // One key frame only: every later frame is an inter frame,
8844 // which is where this gate's intra blocks must sit. The
8845 // MIN distance is what stops aomenc's scene-cut detector
8846 // from inserting a second key frame at the cut this gate's
8847 // source deliberately contains.
8848 "--kf-max-dist=1000",
8849 "--kf-min-dist=1000",
8850 "--threads=1",
8851 "--row-mt=0",
8852 "--enable-order-hint=0",
8853 "--enable-warped-motion=0",
8854 "--enable-obmc=0",
8855 "--enable-masked-comp=0",
8856 "--enable-interintra-comp=0",
8857 "--enable-dist-wtd-comp=0",
8858 "--enable-diff-wtd-comp=0",
8859 "--enable-onesided-comp=0",
8860 "--enable-interintra-wedge=0",
8861 "--enable-smooth-interintra=0",
8862 "--enable-ab-partitions=0",
8863 "--enable-1to4-partitions=0",
8864 "--enable-filter-intra=0",
8865 "--enable-smooth-intra=0",
8866 "--enable-paeth-intra=0",
8867 "--enable-directional-intra=0",
8868 "--enable-angle-delta=0",
8869 "--enable-cdef=0",
8870 "--enable-restoration=0",
8871 "--enable-palette=0",
8872 "--enable-intrabc=0",
8873 "--enable-cfl-intra=0",
8874 "--enable-ref-frame-mvs=0",
8875 // Per-arm overrides go LAST (aomenc keeps the last
8876 // occurrence of a repeated --enable-* flag): the intra
8877 // tx_depth symbol only exists under TX_MODE_SELECT, and
8878 // rect partitions are a separate named refusal.
8879 "--enable-tx-size-search=1",
8880 "--enable-rect-partitions=0",
8881 "--max-partition-size=32",
8882 // Sub-16 inter partitions are a separate named refusal,
8883 // as is the 8x8 intra leaf's own TX_4X4 split.
8884 "--min-partition-size=16",
8885 "--obu",
8886 "-o",
8887 "-",
8888 "-",
8889 ])
8890 .stdin(Stdio::piped())
8891 .stdout(Stdio::piped())
8892 .stderr(Stdio::piped())
8893 .spawn()
8894 .expect("aomenc failed to start");
8895 child
8896 .stdin
8897 .take()
8898 .expect("aomenc stdin")
8899 .write_all(&y4m.stdout)
8900 .expect("writing y4m to aomenc");
8901 let out = child.wait_with_output().expect("aomenc failed to run");
8902 assert!(
8903 out.status.success(),
8904 "aomenc refused the fixture: {}",
8905 String::from_utf8_lossy(&out.stderr)
8906 );
8907 let stream = out.stdout;
8908 let before = decode::intra_in_inter_split_tx_hits();
8909 let frames = match decode_stream(&stream) {
8910 Ok(frames) => frames,
8911 Err(e) => {
8912 let msg = e.to_string();
8913 assert!(
8914 msg.contains("unsupported"),
8915 "{name} decode failed outright (seed {seed}): {msg}"
8916 );
8917 refusals.push(format!("seed {seed}: {msg}"));
8918 continue;
8919 }
8920 };
8921 let after = decode::intra_in_inter_split_tx_hits();
8922 let mut per_size = [0usize; 4];
8923 for i in 0..4 {
8924 per_size[i] = after[i] - before[i];
8925 }
8926 // class [[gate-skips-on-its-own-failure]]: a decode that
8927 // succeeded is ALWAYS pixel-compared below; the counter only
8928 // decides whether the attempt counts as firing.
8929 let counted = per_size.iter().sum::<usize>() != 0;
8930 if !counted {
8931 uncounted_exact += 1;
8932 refusals.push(format!(
8933 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
8934 frame split its transform"
8935 ));
8936 }
8937 let ffmpeg_frames = if bit_depth == 10 {
8938 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
8939 } else {
8940 ffmpeg_decode_sequence(&stream, width, height, frame_count)
8941 };
8942 assert_eq!(frames.len(), frame_count);
8943 eprintln!(
8944 "{name} seed={seed}: split intra-in-inter blocks 8x8={} 16x16={} 32x32={} \
8945 64x64={}",
8946 per_size[0], per_size[1], per_size[2], per_size[3]
8947 );
8948 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8949 for (plane, (g, w)) in [
8950 ("Y", (&got.y, &want.y)),
8951 ("U", (&got.u, &want.u)),
8952 ("V", (&got.v, &want.v)),
8953 ] {
8954 let stride = if plane == "Y" { width } else { width / 2 };
8955 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
8956 eprintln!(
8957 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
8958 want {} ({} samples differ)",
8959 at % stride,
8960 at / stride,
8961 g[at],
8962 w[at],
8963 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
8964 );
8965 }
8966 }
8967 }
8968 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8969 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
8970 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
8971 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
8972 }
8973 if counted {
8974 gate_buckets(
8975 &name,
8976 1,
8977 uncounted_exact,
8978 refusals.len() - uncounted_exact as usize,
8979 );
8980 return;
8981 }
8982 }
8983 gate_buckets(
8984 &name,
8985 0,
8986 uncounted_exact,
8987 refusals.len() - uncounted_exact as usize,
8988 );
8989 panic!(
8990 "{name} never observed a split-transform intra block in an inter frame:\n{}",
8991 refusals.join("\n")
8992 );
8993 }
8994
8995 /// lane-fiinter r1 (class [[symbol-consumption-gap]] +
8996 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
8997 /// `--enable-filter-intra=1` (aomenc's own default -- every inter gate
8998 /// recipe before this one pinned it OFF, so nothing ever exercised it) in
8999 /// which the RD picks an INTRA block inside an inter frame and gives it
9000 /// filter intra. `read_intra_block_mode_info` reads `use_filter_intra`
9001 /// there exactly as a key frame does; this decoder read no such symbol at
9002 /// all until this round, so such a stream desynced at that symbol and
9003 /// decoded silently wrong. Hard-asserts
9004 /// [`decode::intra_in_inter_filter_intra_hits`]: an attempt that never
9005 /// produced one proves nothing, and exhausting every attempt is a
9006 /// FAILURE, not a SKIP.
9007 #[test]
9008 fn a_real_aomenc_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact() {
9009 filter_intra_in_inter_gate(8);
9010 }
9011
9012 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
9013 #[test]
9014 fn a_real_aomenc_10bit_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact()
9015 {
9016 filter_intra_in_inter_gate(10);
9017 }
9018
9019 fn filter_intra_in_inter_gate(bit_depth: u32) {
9020 let name = format!("filter_intra_in_inter_gate({bit_depth})");
9021 if !have_ffmpeg() {
9022 eprintln!("SKIP {name}: no ffmpeg");
9023 return;
9024 }
9025 if !have_aomenc() {
9026 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
9027 return;
9028 }
9029 let (width, height, frame_count) = (64usize, 64usize, 8usize);
9030 let mut refusals = Vec::new();
9031 let mut uncounted_exact = 0u32;
9032 for attempt in 0..40u32 {
9033 let seed = 42 + attempt;
9034 // A zooming fractal: every frame moves (so the sequence is
9035 // genuinely inter-coded) and keeps sharp new detail entering at
9036 // the borders, which is what makes aomenc's RD choose an INTRA
9037 // block inside an inter frame -- and then split its transform.
9038 // A zooming fractal with a hard CUT halfway (`overlay` switching
9039 // a second, unrelated fractal on at frame 4): after the cut every
9040 // block is unpredictable from the reference, which is what makes
9041 // aomenc code INTRA blocks inside an inter frame -- and at this
9042 // cq the RD then splits their transforms.
9043 let source = format!(
9044 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
9045 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
9046 [a][b]overlay=enable='gte(n,4)'",
9047 5.0 - f64::from(attempt) * 0.06,
9048 0.9 + f64::from(attempt) * 0.11
9049 );
9050 let y4m = Command::new("ffmpeg")
9051 .args([
9052 "-v",
9053 "error",
9054 "-f",
9055 "lavfi",
9056 "-i",
9057 &source,
9058 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
9059 // still-refused directional-chroma gaps never fire and
9060 // luma detail alone drives the transform split.
9061 "-vf",
9062 "hue=s=0",
9063 "-pix_fmt",
9064 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
9065 "-strict",
9066 "-1",
9067 "-t",
9068 "0.32",
9069 "-f",
9070 "yuv4mpegpipe",
9071 "-strict",
9072 "-1",
9073 "-",
9074 ])
9075 .stdin(Stdio::null())
9076 .stdout(Stdio::piped())
9077 .stderr(Stdio::piped())
9078 .output()
9079 .expect("ffmpeg failed to run");
9080 assert!(
9081 y4m.status.success(),
9082 "ffmpeg fixture: {}",
9083 String::from_utf8_lossy(&y4m.stderr)
9084 );
9085 let depth_args: &[&str] = if bit_depth == 10 {
9086 &["-b", "10", "--input-bit-depth=10"]
9087 } else {
9088 &[]
9089 };
9090 let mut child = Command::new(aomenc_path())
9091 .args(depth_args)
9092 .args([
9093 "--codec=av1",
9094 "--passes=1",
9095 "--end-usage=q",
9096 "--cq-level=30",
9097 "--cpu-used=0",
9098 "--lag-in-frames=0",
9099 "--auto-alt-ref=0",
9100 // One key frame only: every later frame is an inter frame,
9101 // which is where this gate's intra blocks must sit. The
9102 // MIN distance is what stops aomenc's scene-cut detector
9103 // from inserting a second key frame at the cut this gate's
9104 // source deliberately contains.
9105 "--kf-max-dist=1000",
9106 "--kf-min-dist=1000",
9107 "--threads=1",
9108 "--row-mt=0",
9109 "--enable-order-hint=0",
9110 "--enable-warped-motion=0",
9111 "--enable-obmc=0",
9112 "--enable-masked-comp=0",
9113 "--enable-interintra-comp=0",
9114 "--enable-dist-wtd-comp=0",
9115 "--enable-diff-wtd-comp=0",
9116 "--enable-onesided-comp=0",
9117 "--enable-interintra-wedge=0",
9118 "--enable-smooth-interintra=0",
9119 "--enable-ab-partitions=0",
9120 "--enable-1to4-partitions=0",
9121 "--enable-smooth-intra=0",
9122 "--enable-paeth-intra=0",
9123 "--enable-directional-intra=0",
9124 "--enable-angle-delta=0",
9125 "--enable-cdef=0",
9126 "--enable-restoration=0",
9127 "--enable-palette=0",
9128 "--enable-intrabc=0",
9129 "--enable-cfl-intra=0",
9130 "--enable-ref-frame-mvs=0",
9131 // Per-arm overrides go LAST (aomenc keeps the last
9132 // occurrence of a repeated --enable-* flag): the intra
9133 // tx_depth symbol only exists under TX_MODE_SELECT, and
9134 // rect partitions are a separate named refusal.
9135 "--enable-filter-intra=1",
9136 "--enable-tx-size-search=1",
9137 "--enable-rect-partitions=0",
9138 "--max-partition-size=32",
9139 // Sub-16 inter partitions are a separate named refusal,
9140 // as is the 8x8 intra leaf's own TX_4X4 split.
9141 "--min-partition-size=16",
9142 "--obu",
9143 "-o",
9144 "-",
9145 "-",
9146 ])
9147 .stdin(Stdio::piped())
9148 .stdout(Stdio::piped())
9149 .stderr(Stdio::piped())
9150 .spawn()
9151 .expect("aomenc failed to start");
9152 child
9153 .stdin
9154 .take()
9155 .expect("aomenc stdin")
9156 .write_all(&y4m.stdout)
9157 .expect("writing y4m to aomenc");
9158 let out = child.wait_with_output().expect("aomenc failed to run");
9159 assert!(
9160 out.status.success(),
9161 "aomenc refused the fixture: {}",
9162 String::from_utf8_lossy(&out.stderr)
9163 );
9164 let stream = out.stdout;
9165 let before = decode::intra_in_inter_filter_intra_hits();
9166 let frames = match decode_stream(&stream) {
9167 Ok(frames) => frames,
9168 Err(e) => {
9169 let msg = e.to_string();
9170 assert!(
9171 msg.contains("unsupported"),
9172 "{name} decode failed outright (seed {seed}): {msg}"
9173 );
9174 refusals.push(format!("seed {seed}: {msg}"));
9175 continue;
9176 }
9177 };
9178 let fired = decode::intra_in_inter_filter_intra_hits() - before;
9179 // class [[gate-skips-on-its-own-failure]]: a decode that
9180 // succeeded is ALWAYS pixel-compared below; the counter only
9181 // decides whether the attempt counts as firing.
9182 let counted = fired != 0;
9183 if !counted {
9184 uncounted_exact += 1;
9185 refusals.push(format!(
9186 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
9187 frame used filter intra"
9188 ));
9189 }
9190 let ffmpeg_frames = if bit_depth == 10 {
9191 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
9192 } else {
9193 ffmpeg_decode_sequence(&stream, width, height, frame_count)
9194 };
9195 assert_eq!(frames.len(), frame_count);
9196 eprintln!(
9197 "{name} seed={seed}: filter-intra blocks inside inter frames = {fired}"
9198 );
9199 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9200 for (plane, (g, w)) in [
9201 ("Y", (&got.y, &want.y)),
9202 ("U", (&got.u, &want.u)),
9203 ("V", (&got.v, &want.v)),
9204 ] {
9205 let stride = if plane == "Y" { width } else { width / 2 };
9206 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
9207 eprintln!(
9208 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
9209 want {} ({} samples differ)",
9210 at % stride,
9211 at / stride,
9212 g[at],
9213 w[at],
9214 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
9215 );
9216 }
9217 }
9218 }
9219 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9220 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
9221 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
9222 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
9223 }
9224 if counted {
9225 gate_buckets(
9226 &name,
9227 1,
9228 uncounted_exact,
9229 refusals.len() - uncounted_exact as usize,
9230 );
9231 return;
9232 }
9233 }
9234 gate_buckets(
9235 &name,
9236 0,
9237 uncounted_exact,
9238 refusals.len() - uncounted_exact as usize,
9239 );
9240 panic!(
9241 "{name} never observed a filter-intra intra block in an inter frame:\n{}",
9242 refusals.join("\n")
9243 );
9244 }
9245
9246 /// lane-angleinter r1 (class [[refusal-strings-are-claims]] +
9247 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
9248 /// `--enable-angle-delta=1` and `--enable-directional-intra=1` (aomenc's
9249 /// own defaults; every inter gate before this one pinned BOTH off) in
9250 /// which the RD gives an INTRA block inside an inter frame a directional
9251 /// luma mode with a nonzero `angle_delta_y`. Both intra-in-inter arms
9252 /// read that symbol and then REFUSED it as "this encoder never writes
9253 /// one" -- the claim is false, `read_intra_angle_info` writes it exactly
9254 /// as a key frame does. Hard-asserts
9255 /// [`decode::intra_in_inter_angle_delta_y_hits`]; an attempt that never
9256 /// produced one proves nothing, and exhausting every attempt is a
9257 /// FAILURE, not a SKIP.
9258 #[test]
9259 fn a_real_aomenc_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
9260 {
9261 angle_delta_in_inter_gate(8, "--min-partition-size=16");
9262 }
9263
9264 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
9265 #[test]
9266 fn a_real_aomenc_10bit_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
9267 {
9268 angle_delta_in_inter_gate(10, "--min-partition-size=16");
9269 }
9270
9271 fn angle_delta_in_inter_gate(bit_depth: u32, min_partition: &str) {
9272 let name = format!("angle_delta_in_inter_gate({bit_depth}, min={min_partition})");
9273 let leaf8 = min_partition.ends_with('8');
9274 assert!(!leaf8, "the 8x8-leaf arm keeps its refusal; see the module note");
9275 if !have_ffmpeg() {
9276 eprintln!("SKIP {name}: no ffmpeg");
9277 return;
9278 }
9279 if !have_aomenc() {
9280 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
9281 return;
9282 }
9283 let (width, height, frame_count) = (64usize, 64usize, 8usize);
9284 let mut refusals = Vec::new();
9285 let mut uncounted_exact = 0u32;
9286 for attempt in 0..40u32 {
9287 let seed = 42 + attempt;
9288 // A zooming fractal: every frame moves (so the sequence is
9289 // genuinely inter-coded) and keeps sharp new detail entering at
9290 // the borders, which is what makes aomenc's RD choose an INTRA
9291 // block inside an inter frame -- and then split its transform.
9292 // A zooming fractal with a hard CUT halfway (`overlay` switching
9293 // a second, unrelated fractal on at frame 4): after the cut every
9294 // block is unpredictable from the reference, which is what makes
9295 // aomenc code INTRA blocks inside an inter frame -- and at this
9296 // cq the RD then splits their transforms.
9297 let source = format!(
9298 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
9299 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
9300 [a][b]overlay=enable='gte(n,4)'",
9301 5.0 - f64::from(attempt) * 0.06,
9302 0.9 + f64::from(attempt) * 0.11
9303 );
9304 let y4m = Command::new("ffmpeg")
9305 .args([
9306 "-v",
9307 "error",
9308 "-f",
9309 "lavfi",
9310 "-i",
9311 &source,
9312 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
9313 // still-refused directional-chroma gaps never fire and
9314 // luma detail alone drives the transform split.
9315 "-vf",
9316 "hue=s=0",
9317 "-pix_fmt",
9318 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
9319 "-strict",
9320 "-1",
9321 "-t",
9322 "0.32",
9323 "-f",
9324 "yuv4mpegpipe",
9325 "-strict",
9326 "-1",
9327 "-",
9328 ])
9329 .stdin(Stdio::null())
9330 .stdout(Stdio::piped())
9331 .stderr(Stdio::piped())
9332 .output()
9333 .expect("ffmpeg failed to run");
9334 assert!(
9335 y4m.status.success(),
9336 "ffmpeg fixture: {}",
9337 String::from_utf8_lossy(&y4m.stderr)
9338 );
9339 // The 8x8-leaf arm is fenced by three sibling refusals (non-DC
9340 // chroma on an 8x8 leaf, its TX_4X4 split, sub-16 rect inter
9341 // leaves), so it sweeps the quantiser as well as the source: a
9342 // coarser q is what pushes the RD to directional intra at 8x8.
9343 let cq = if leaf8 {
9344 format!("--cq-level={}", 20 + (attempt % 5) * 10)
9345 } else {
9346 "--cq-level=30".to_string()
9347 };
9348 let depth_args: &[&str] = if bit_depth == 10 {
9349 &["-b", "10", "--input-bit-depth=10"]
9350 } else {
9351 &[]
9352 };
9353 let mut child = Command::new(aomenc_path())
9354 .args(depth_args)
9355 .args([
9356 "--codec=av1",
9357 "--passes=1",
9358 "--end-usage=q",
9359 &cq,
9360 "--cpu-used=0",
9361 "--lag-in-frames=0",
9362 "--auto-alt-ref=0",
9363 // One key frame only: every later frame is an inter frame,
9364 // which is where this gate's intra blocks must sit. The
9365 // MIN distance is what stops aomenc's scene-cut detector
9366 // from inserting a second key frame at the cut this gate's
9367 // source deliberately contains.
9368 "--kf-max-dist=1000",
9369 "--kf-min-dist=1000",
9370 "--threads=1",
9371 "--row-mt=0",
9372 "--enable-order-hint=0",
9373 "--enable-warped-motion=0",
9374 "--enable-obmc=0",
9375 "--enable-masked-comp=0",
9376 "--enable-interintra-comp=0",
9377 "--enable-dist-wtd-comp=0",
9378 "--enable-diff-wtd-comp=0",
9379 "--enable-onesided-comp=0",
9380 "--enable-interintra-wedge=0",
9381 "--enable-smooth-interintra=0",
9382 "--enable-ab-partitions=0",
9383 "--enable-1to4-partitions=0",
9384 "--enable-smooth-intra=0",
9385 "--enable-paeth-intra=0",
9386 "--enable-directional-intra=1",
9387 "--enable-angle-delta=1",
9388 "--enable-cdef=0",
9389 "--enable-restoration=0",
9390 "--enable-palette=0",
9391 "--enable-intrabc=0",
9392 "--enable-cfl-intra=0",
9393 "--enable-ref-frame-mvs=0",
9394 // Per-arm overrides go LAST (aomenc keeps the last
9395 // occurrence of a repeated --enable-* flag): the intra
9396 // tx_depth symbol only exists under TX_MODE_SELECT, and
9397 // rect partitions are a separate named refusal.
9398 "--enable-filter-intra=1",
9399 "--enable-tx-size-search=1",
9400 "--enable-rect-partitions=0",
9401 "--max-partition-size=32",
9402 // Sub-16 inter partitions are a separate named refusal,
9403 // as is the 8x8 intra leaf's own TX_4X4 split.
9404 min_partition,
9405 "--obu",
9406 "-o",
9407 "-",
9408 "-",
9409 ])
9410 .stdin(Stdio::piped())
9411 .stdout(Stdio::piped())
9412 .stderr(Stdio::piped())
9413 .spawn()
9414 .expect("aomenc failed to start");
9415 child
9416 .stdin
9417 .take()
9418 .expect("aomenc stdin")
9419 .write_all(&y4m.stdout)
9420 .expect("writing y4m to aomenc");
9421 let out = child.wait_with_output().expect("aomenc failed to run");
9422 assert!(
9423 out.status.success(),
9424 "aomenc refused the fixture: {}",
9425 String::from_utf8_lossy(&out.stderr)
9426 );
9427 let stream = out.stdout;
9428 let before = decode::intra_in_inter_angle_delta_y_hits();
9429 let before_uv = decode::intra_in_inter_angle_delta_uv_hits();
9430 let frames = match decode_stream(&stream) {
9431 Ok(frames) => frames,
9432 Err(e) => {
9433 let msg = e.to_string();
9434 assert!(
9435 msg.contains("unsupported"),
9436 "{name} decode failed outright (seed {seed}): {msg}"
9437 );
9438 refusals.push(format!("seed {seed}: {msg}"));
9439 continue;
9440 }
9441 };
9442 let fired = decode::intra_in_inter_angle_delta_y_hits() - before;
9443 let fired_uv = decode::intra_in_inter_angle_delta_uv_hits() - before_uv;
9444 // class [[gate-skips-on-its-own-failure]]: a decode that
9445 // succeeded is ALWAYS pixel-compared below; the counter only
9446 // decides whether the attempt counts as firing.
9447 let counted = fired != 0;
9448 if !counted {
9449 uncounted_exact += 1;
9450 refusals.push(format!(
9451 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
9452 frame carried a nonzero angle_delta_y"
9453 ));
9454 }
9455 let ffmpeg_frames = if bit_depth == 10 {
9456 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
9457 } else {
9458 ffmpeg_decode_sequence(&stream, width, height, frame_count)
9459 };
9460 assert_eq!(frames.len(), frame_count);
9461 eprintln!(
9462 "{name} seed={seed}: intra-in-inter blocks with a nonzero angle_delta_y = \
9463 {fired}, angle_delta_uv = {fired_uv}"
9464 );
9465 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9466 for (plane, (g, w)) in [
9467 ("Y", (&got.y, &want.y)),
9468 ("U", (&got.u, &want.u)),
9469 ("V", (&got.v, &want.v)),
9470 ] {
9471 let stride = if plane == "Y" { width } else { width / 2 };
9472 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
9473 eprintln!(
9474 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
9475 want {} ({} samples differ)",
9476 at % stride,
9477 at / stride,
9478 g[at],
9479 w[at],
9480 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
9481 );
9482 }
9483 }
9484 }
9485 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9486 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
9487 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
9488 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
9489 }
9490 if counted {
9491 gate_buckets(
9492 &name,
9493 1,
9494 uncounted_exact,
9495 refusals.len() - uncounted_exact as usize,
9496 );
9497 return;
9498 }
9499 }
9500 gate_buckets(
9501 &name,
9502 0,
9503 uncounted_exact,
9504 refusals.len() - uncounted_exact as usize,
9505 );
9506 panic!(
9507 "{name} never observed a nonzero angle delta on an intra block in an inter \
9508 frame:\n{}",
9509 refusals.join("\n")
9510 );
9511 }
9512
9513 /// lane-uv8 r1 (classes [[refusal-strings-are-claims]] +
9514 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
9515 /// 8x8 partitions and full chroma intra tooling
9516 /// (`--enable-cfl-intra=1 --enable-smooth-intra=1 --enable-paeth-intra=1
9517 /// --enable-directional-intra=1`), in which the RD gives an INTRA 8x8
9518 /// leaf inside an inter frame a NON-DC `uv_mode`. That leaf
9519 /// ([`decode::decode_inter_block8`]'s intra arm) read the `uv_mode`
9520 /// symbol and refused every value but `DC_PRED` -- "this encoder never
9521 /// writes one" was a claim, and this gate is what contradicts it. Hard-
9522 /// asserts `decode::intra_in_inter8_uv_hits` (directional, smooth/paeth,
9523 /// CfL, counted on THIS leaf only); an attempt that never produced one
9524 /// proves nothing, and exhausting every attempt is a FAILURE, not a SKIP.
9525 #[test]
9526 fn a_real_aomenc_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() {
9527 uv_mode_in_inter8_gate(8, 1);
9528 }
9529
9530 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
9531 #[test]
9532 fn a_real_aomenc_10bit_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() {
9533 uv_mode_in_inter8_gate(10, 1);
9534 }
9535
9536 /// The multi-tile arm (class [[new-map-ignores-tile-edge]]): this round
9537 /// stamps a new `uv_mode` band from the 8x8 leaf, whose availability must
9538 /// be tile-relative.
9539 #[test]
9540 fn a_real_aomenc_two_tile_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact()
9541 {
9542 uv_mode_in_inter8_gate(8, 2);
9543 }
9544
9545 fn uv_mode_in_inter8_gate(bit_depth: u32, tile_columns: u32) {
9546 let name = format!("uv_mode_in_inter8_gate({bit_depth}, tiles={tile_columns})");
9547 if !have_ffmpeg() {
9548 eprintln!("SKIP {name}: no ffmpeg");
9549 return;
9550 }
9551 if !have_aomenc() {
9552 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
9553 return;
9554 }
9555 let (width, height, frame_count) = (192usize, 128usize, 8usize);
9556 let mut refusals = Vec::new();
9557 let mut uncounted_exact = 0u32;
9558 let mut totals = (0usize, 0usize, 0usize);
9559 for attempt in 0..30u32 {
9560 let seed = 42 + attempt;
9561 // A zooming fractal with a hard CUT at frame 4 (`overlay`
9562 // switching a second, unrelated fractal on): after the cut a block
9563 // is unpredictable from the reference, which is what makes aomenc
9564 // code INTRA blocks inside an inter frame. Chroma is NOT
9565 // desaturated here (every sibling inter gate passes `hue=s=0`) --
9566 // real chroma detail is exactly what pushes the chroma RD off
9567 // DC_PRED. `noise` carries its own explicit seed (lavfi
9568 // `gradients` ignores its seed; class [[seeded-fixture-not-reproducible]]).
9569 let source = format!(
9570 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
9571 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
9572 [a][b]overlay=enable='gte(n,4)',noise=alls=12:allf=t+u:all_seed={seed}",
9573 5.0 - f64::from(attempt) * 0.06,
9574 0.9 + f64::from(attempt) * 0.11
9575 );
9576 let y4m = Command::new("ffmpeg")
9577 .args([
9578 "-v",
9579 "error",
9580 "-f",
9581 "lavfi",
9582 "-i",
9583 &source,
9584 "-pix_fmt",
9585 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
9586 "-strict",
9587 "-1",
9588 "-t",
9589 "0.32",
9590 "-f",
9591 "yuv4mpegpipe",
9592 "-strict",
9593 "-1",
9594 "-",
9595 ])
9596 .stdin(Stdio::null())
9597 .stdout(Stdio::piped())
9598 .stderr(Stdio::piped())
9599 .output()
9600 .expect("ffmpeg failed to run");
9601 assert!(
9602 y4m.status.success(),
9603 "ffmpeg fixture: {}",
9604 String::from_utf8_lossy(&y4m.stderr)
9605 );
9606 // A coarser quantiser is what pushes the chroma RD to a cheap
9607 // non-DC mode on a small block; sweep 12..40 (the low end is what
9608 // lane-cdef's cq12 arm needs).
9609 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
9610 let depth_args: &[&str] = if bit_depth == 10 {
9611 &["-b", "10", "--input-bit-depth=10"]
9612 } else {
9613 &[]
9614 };
9615 let tiles = format!("--tile-columns={}", tile_columns - 1);
9616 // The y4m goes through a FILE, not aomenc's stdin: this gate's
9617 // stream is ~100 KB, bigger than a pipe buffer, so an aomenc that
9618 // is still being fed on stdin blocks writing its stdout and the
9619 // test blocks writing its stdin -- a hard deadlock (measured
9620 // here, 3 min into attempt 0, class [[gate-loader-slurps-whole-file]]).
9621 // The path is PID-keyed (class [[pid-keyed-temp-path]]).
9622 let y4m_path = std::env::temp_dir().join(format!(
9623 "ec-av1-uv8-{}-{bit_depth}-{tile_columns}-{seed}.y4m",
9624 std::process::id()
9625 ));
9626 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
9627 let child = Command::new(aomenc_path())
9628 .args(depth_args)
9629 .args([
9630 "--codec=av1",
9631 "--passes=1",
9632 "--end-usage=q",
9633 &cq,
9634 "--cpu-used=0",
9635 "--lag-in-frames=0",
9636 "--auto-alt-ref=0",
9637 "--kf-max-dist=9999",
9638 "--kf-min-dist=9999",
9639 "--threads=1",
9640 "--row-mt=0",
9641 &tiles,
9642 "--enable-order-hint=0",
9643 "--enable-warped-motion=0",
9644 "--enable-obmc=0",
9645 "--enable-masked-comp=0",
9646 "--enable-interintra-comp=0",
9647 "--enable-dist-wtd-comp=0",
9648 "--enable-diff-wtd-comp=0",
9649 "--enable-onesided-comp=0",
9650 "--enable-interintra-wedge=0",
9651 "--enable-smooth-interintra=0",
9652 "--enable-ab-partitions=0",
9653 "--enable-1to4-partitions=0",
9654 "--enable-cdef=0",
9655 "--enable-restoration=0",
9656 "--enable-palette=0",
9657 "--enable-intrabc=0",
9658 "--enable-ref-frame-mvs=0",
9659 // Per-arm overrides go LAST (aomenc keeps the LAST
9660 // occurrence of a repeated --enable-* flag). The three
9661 // chroma intra tools this gate is about, plus the fences
9662 // that keep the leaf's SIBLING refusals (its TX_4X4
9663 // split, a nonzero angle delta, sub-16 rect inter leaves)
9664 // out of the way.
9665 "--enable-cfl-intra=1",
9666 "--enable-smooth-intra=1",
9667 "--enable-paeth-intra=1",
9668 "--enable-directional-intra=1",
9669 "--enable-angle-delta=0",
9670 "--enable-tx-size-search=0",
9671 "--enable-rect-partitions=0",
9672 "--min-partition-size=8",
9673 "--max-partition-size=32",
9674 "--obu",
9675 "-o",
9676 "-",
9677 ])
9678 .arg(&y4m_path)
9679 .stdin(Stdio::null())
9680 .stdout(Stdio::piped())
9681 .stderr(Stdio::piped())
9682 .spawn()
9683 .expect("aomenc failed to start");
9684 let out = child.wait_with_output().expect("aomenc failed to run");
9685 let _ = std::fs::remove_file(&y4m_path);
9686 assert!(
9687 out.status.success(),
9688 "aomenc refused the fixture: {}",
9689 String::from_utf8_lossy(&out.stderr)
9690 );
9691 let stream = out.stdout;
9692 let before = decode::intra_in_inter8_uv_hits();
9693 let frames = match decode_stream(&stream) {
9694 Ok(frames) => frames,
9695 Err(e) => {
9696 let msg = e.to_string();
9697 assert!(
9698 msg.contains("unsupported"),
9699 "{name} decode failed outright (seed {seed}): {msg}"
9700 );
9701 refusals.push(format!("seed {seed}: {msg}"));
9702 continue;
9703 }
9704 };
9705 let now = decode::intra_in_inter8_uv_hits();
9706 // class [[counter-from-refused-stream]]: per-attempt deltas, and
9707 // only for an attempt that decoded to the end and is pixel-
9708 // compared below.
9709 let fired = (now.0 - before.0, now.1 - before.1, now.2 - before.2);
9710 totals = (
9711 totals.0 + fired.0,
9712 totals.1 + fired.1,
9713 totals.2 + fired.2,
9714 );
9715 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
9716 // is ALWAYS pixel-compared; the counter only decides whether the
9717 // attempt counts as firing.
9718 // lane-uv8 r3: every one of the three chroma classes this gate
9719 // exists for (directional, smooth/paeth, CfL) must fire on the
9720 // SAME pixel-compared attempt -- a sum-nonzero predicate would
9721 // pass on an attempt that only ever hit DC-adjacent CfL.
9722 let counted = fired.0 > 0 && fired.1 > 0 && fired.2 > 0;
9723 if !counted {
9724 uncounted_exact += 1;
9725 refusals.push(format!(
9726 "seed {seed}: decoded and pixel-compared, but no 8x8 intra leaf in an inter \
9727 frame carried a non-DC uv_mode"
9728 ));
9729 }
9730 let ffmpeg_frames = if bit_depth == 10 {
9731 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
9732 } else {
9733 ffmpeg_decode_sequence(&stream, width, height, frame_count)
9734 };
9735 assert_eq!(frames.len(), frame_count);
9736 eprintln!(
9737 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with a non-DC uv_mode -- \
9738 directional {}, smooth/paeth {}, CfL {}",
9739 fired.0, fired.1, fired.2
9740 );
9741 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9742 for (plane, (g, w)) in [
9743 ("Y", (&got.y, &want.y)),
9744 ("U", (&got.u, &want.u)),
9745 ("V", (&got.v, &want.v)),
9746 ] {
9747 let stride = if plane == "Y" { width } else { width / 2 };
9748 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
9749 eprintln!(
9750 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
9751 want {} ({} samples differ)",
9752 at % stride,
9753 at / stride,
9754 g[at],
9755 w[at],
9756 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
9757 );
9758 }
9759 }
9760 }
9761 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9762 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
9763 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
9764 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
9765 }
9766 if counted {
9767 gate_buckets(
9768 &name,
9769 1,
9770 uncounted_exact,
9771 refusals.len() - uncounted_exact as usize,
9772 );
9773 return;
9774 }
9775 }
9776 gate_buckets(
9777 &name,
9778 0,
9779 uncounted_exact,
9780 refusals.len() - uncounted_exact as usize,
9781 );
9782 panic!(
9783 "{name} never observed a non-DC uv_mode on an 8x8 intra leaf in an inter frame \
9784 (totals dir/smooth/cfl {totals:?}):\n{}",
9785 refusals.join("\n")
9786 );
9787 }
9788
9789
9790 /// lane-leaf8tx r1: the refusal this round lifts on an INTRA 8x8 leaf
9791 /// inside an INTER frame -- a nonzero luma `angle_delta_y` on it
9792 /// (`--enable-angle-delta=1`,
9793 /// `av1_use_angle_delta(BLOCK_8X8)`). Both counters are per-attempt
9794 /// deltas on an attempt that decoded to the end and is pixel-compared
9795 /// (class [[counter-from-refused-stream]]); a decode error or a mismatch
9796 /// is a FAILURE, never a SKIP.
9797 #[test]
9798 fn a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
9799 tx_split_angle_in_inter8_gate(8);
9800 }
9801
9802 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
9803 #[test]
9804 fn a_real_aomenc_10bit_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
9805 tx_split_angle_in_inter8_gate(10);
9806 }
9807
9808 fn tx_split_angle_in_inter8_gate(bit_depth: u32) {
9809 let name = format!("tx_split_angle_in_inter8_gate({bit_depth})");
9810 if !have_ffmpeg() {
9811 eprintln!("SKIP {name}: no ffmpeg");
9812 return;
9813 }
9814 if !have_aomenc() {
9815 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
9816 return;
9817 }
9818 let (width, height, frame_count) = (192usize, 128usize, 6usize);
9819 let mut refusals = Vec::new();
9820 let mut uncounted_exact = 0u32;
9821 let mut counted_exact = 0u32;
9822 let mut totals = (0usize, 0usize);
9823 for attempt in 0..30u32 {
9824 let seed = 42 + attempt;
9825 // Same zoom + hard-cut fractal source the sibling uv_mode gate
9826 // uses (a cut is what makes aomenc code INTRA blocks inside an
9827 // inter frame); `noise` carries an explicit seed (class
9828 // [[seeded-fixture-not-reproducible]]).
9829 let source = format!(
9830 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
9831 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
9832 [a][b]overlay=enable='gte(n,3)',noise=alls=12:allf=t+u:all_seed={seed}",
9833 5.0 - f64::from(attempt) * 0.06,
9834 0.9 + f64::from(attempt) * 0.11
9835 );
9836 let y4m = Command::new("ffmpeg")
9837 .args([
9838 "-v",
9839 "error",
9840 "-f",
9841 "lavfi",
9842 "-i",
9843 &source,
9844 "-pix_fmt",
9845 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
9846 "-strict",
9847 "-1",
9848 "-t",
9849 "0.24",
9850 "-f",
9851 "yuv4mpegpipe",
9852 "-strict",
9853 "-1",
9854 "-",
9855 ])
9856 .stdin(Stdio::null())
9857 .stdout(Stdio::piped())
9858 .stderr(Stdio::piped())
9859 .output()
9860 .expect("ffmpeg failed to run");
9861 assert!(
9862 y4m.status.success(),
9863 "ffmpeg fixture: {}",
9864 String::from_utf8_lossy(&y4m.stderr)
9865 );
9866 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
9867 let depth_args: &[&str] = if bit_depth == 10 {
9868 &["-b", "10", "--input-bit-depth=10"]
9869 } else {
9870 &[]
9871 };
9872 // The y4m goes through a PID-keyed FILE, never aomenc's stdin
9873 // (pipe deadlock, class [[gate-loader-slurps-whole-file]]).
9874 let y4m_path = std::env::temp_dir().join(format!(
9875 "ec-av1-leaf8tx-{}-{bit_depth}-{seed}.y4m",
9876 std::process::id()
9877 ));
9878 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
9879 let child = Command::new(aomenc_path())
9880 .args(depth_args)
9881 .args([
9882 "--codec=av1",
9883 "--passes=1",
9884 "--end-usage=q",
9885 &cq,
9886 "--cpu-used=0",
9887 "--lag-in-frames=0",
9888 "--auto-alt-ref=0",
9889 "--kf-max-dist=9999",
9890 "--kf-min-dist=9999",
9891 "--threads=1",
9892 "--row-mt=0",
9893 "--tile-columns=0",
9894 "--enable-order-hint=0",
9895 "--enable-warped-motion=0",
9896 "--enable-obmc=0",
9897 "--enable-masked-comp=0",
9898 "--enable-interintra-comp=0",
9899 "--enable-dist-wtd-comp=0",
9900 "--enable-diff-wtd-comp=0",
9901 "--enable-onesided-comp=0",
9902 "--enable-interintra-wedge=0",
9903 "--enable-smooth-interintra=0",
9904 "--enable-ab-partitions=0",
9905 "--enable-1to4-partitions=0",
9906 "--enable-cdef=0",
9907 "--enable-restoration=0",
9908 "--enable-palette=0",
9909 "--enable-intrabc=0",
9910 "--enable-ref-frame-mvs=0",
9911 // Per-arm overrides LAST (aomenc keeps the last
9912 // occurrence of a repeated --enable-* flag). Rect
9913 // partitions stay off so the leaf's unrelated sub-16 rect
9914 // inter refusal never fires.
9915 "--enable-rect-partitions=0",
9916 "--enable-tx-size-search=1",
9917 "--enable-angle-delta=1",
9918 "--enable-directional-intra=1",
9919 "--min-partition-size=8",
9920 "--max-partition-size=32",
9921 "--obu",
9922 "-o",
9923 "-",
9924 ])
9925 // r1 diagnostic: EC_LEAF8TX_CONTROL=1 turns THIS lane's two
9926 // tools back off (last occurrence of a repeated --enable-*
9927 // wins), so any mismatch that survives is not this lane's.
9928 .args(match std::env::var("EC_LEAF8TX_CONTROL").as_deref() {
9929 Ok("angle") => vec!["--enable-tx-size-search=0", "--enable-angle-delta=1"],
9930 Ok("tx") => vec!["--enable-tx-size-search=1", "--enable-angle-delta=0"],
9931 Ok("tx8") => vec![
9932 "--enable-tx-size-search=1",
9933 "--enable-angle-delta=0",
9934 "--max-partition-size=8",
9935 ],
9936 Ok(_) => vec!["--enable-tx-size-search=0", "--enable-angle-delta=0"],
9937 // Shipped recipe (lane-leaf8tx r4): BOTH of this lane's
9938 // tools on -- the tx_depth split at an 8x8 intra-in-inter
9939 // leaf is what the lifted refusal covers, so
9940 // `--enable-tx-size-search=1` must survive the per-arm
9941 // override (aomenc keeps the LAST occurrence). Odd
9942 // attempts also cap the partition at 8x8, the shape that
9943 // produces the 2x2 TX_4X4 grid most often.
9944 Err(_) => {
9945 if attempt % 2 == 1 {
9946 vec![
9947 "--enable-tx-size-search=1",
9948 "--enable-angle-delta=1",
9949 "--max-partition-size=8",
9950 ]
9951 } else {
9952 vec!["--enable-tx-size-search=1", "--enable-angle-delta=1"]
9953 }
9954 }
9955 })
9956 .arg(&y4m_path)
9957 .stdin(Stdio::null())
9958 .stdout(Stdio::piped())
9959 .stderr(Stdio::piped())
9960 .spawn()
9961 .expect("aomenc failed to start");
9962 let out = child.wait_with_output().expect("aomenc failed to run");
9963 let _ = std::fs::remove_file(&y4m_path);
9964 assert!(
9965 out.status.success(),
9966 "aomenc refused the fixture: {}",
9967 String::from_utf8_lossy(&out.stderr)
9968 );
9969 let stream = out.stdout;
9970 let before = (
9971 decode::intra_in_inter_split_tx_hits()[0],
9972 decode::intra_in_inter8_angle_delta_y_hits(),
9973 );
9974 let frames = match decode_stream(&stream) {
9975 Ok(frames) => frames,
9976 Err(e) => {
9977 let msg = e.to_string();
9978 assert!(
9979 msg.contains("unsupported"),
9980 "{name} decode failed outright (seed {seed}): {msg}"
9981 );
9982 refusals.push(format!("seed {seed}: {msg}"));
9983 continue;
9984 }
9985 };
9986 let now = (
9987 decode::intra_in_inter_split_tx_hits()[0],
9988 decode::intra_in_inter8_angle_delta_y_hits(),
9989 );
9990 let fired = (now.0 - before.0, now.1 - before.1);
9991 totals = (totals.0 + fired.0, totals.1 + fired.1);
9992 // Both lifted capabilities must fire on the SAME pixel-compared
9993 // attempt.
9994 let counted = fired.1 > 0;
9995 if !counted {
9996 uncounted_exact += 1;
9997 refusals.push(format!(
9998 "seed {seed}: decoded and pixel-compared, but split-tx {} / angle-delta {} \
9999 8x8 intra-in-inter leaves",
10000 fired.0, fired.1
10001 ));
10002 }
10003 let ffmpeg_frames = if bit_depth == 10 {
10004 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
10005 } else {
10006 ffmpeg_decode_sequence(&stream, width, height, frame_count)
10007 };
10008 assert_eq!(frames.len(), frame_count);
10009 eprintln!(
10010 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with tx_depth=1 {}, with a \
10011 nonzero angle_delta_y {} (split-tx per size 8/16/32/64 {:?})",
10012 fired.0,
10013 fired.1,
10014 decode::intra_in_inter_split_tx_hits()
10015 );
10016 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10017 for (plane, (g, w)) in [
10018 ("Y", (&got.y, &want.y)),
10019 ("U", (&got.u, &want.u)),
10020 ("V", (&got.v, &want.v)),
10021 ] {
10022 let stride = if plane == "Y" { width } else { width / 2 };
10023 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
10024 eprintln!(
10025 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
10026 want {} ({} samples differ)",
10027 at % stride,
10028 at / stride,
10029 g[at],
10030 w[at],
10031 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
10032 );
10033 }
10034 }
10035 }
10036 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10037 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
10038 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
10039 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
10040 }
10041 if counted {
10042 counted_exact += 1;
10043 }
10044 }
10045 // lane-leaf8tx r4: continue-and-sweep -- every arm is encoded,
10046 // decoded and pixel-compared on every plane of every decode-order
10047 // frame above; the counters are asserted ONCE here. A decode error or
10048 // a mismatch is a failure, never a SKIP, and `uncounted_exact`
10049 // (decoded + compared but neither capability fired) is the
10050 // out-of-scope-mismatch bucket that the sweep tolerates only while at
10051 // least one attempt did fire.
10052 gate_buckets(
10053 &name,
10054 counted_exact,
10055 uncounted_exact,
10056 refusals.len() - uncounted_exact as usize,
10057 );
10058 assert!(
10059 totals.0 > 0,
10060 "{name}: no decoded+compared attempt carried an 8x8 intra-in-inter leaf with \
10061 tx_depth split to 4x4 (split-tx per size {:?}, angle-delta {}):\n{}",
10062 decode::intra_in_inter_split_tx_hits(),
10063 totals.1,
10064 refusals.join("\n")
10065 );
10066 assert!(
10067 totals.1 > 0,
10068 "{name}: no decoded+compared attempt carried a nonzero angle_delta_y on an 8x8 \
10069 intra-in-inter leaf (split-tx {}):\n{}",
10070 totals.0,
10071 refusals.join("\n")
10072 );
10073 }
10074
10075 /// lane-chroma r2 stage 1: a real aomenc key frame with
10076 /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`)
10077 /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still-
10078 /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never
10079 /// fires; smooth *luma* neighbours are exactly what this gate wants to
10080 /// exercise, proving [`decode::smooth_luma_hits`] actually landed a
10081 /// directional block next to a smooth-predicted one and decoded
10082 /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix).
10083 #[test]
10084 fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() {
10085 if !have_ffmpeg() {
10086 eprintln!(
10087 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg"
10088 );
10089 return;
10090 }
10091 if !have_aomenc() {
10092 eprintln!(
10093 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}",
10094 aomenc_path().display()
10095 );
10096 return;
10097 }
10098 let (width, height) = (64usize, 64usize);
10099 let mut refusals = Vec::new();
10100 let mut fired_runs = 0u32;
10101 let mut uncounted_exact = 0u32;
10102 for attempt in 0..40u32 {
10103 let seed = 42 + attempt;
10104 let source = format!(
10105 "mandelbrot=size=64x64:start_scale={}:rate=25",
10106 5.0 - f64::from(attempt) * 0.06
10107 );
10108 let y4m = Command::new("ffmpeg")
10109 .args([
10110 "-v",
10111 "error",
10112 "-f",
10113 "lavfi",
10114 "-i",
10115 &source,
10116 "-pix_fmt",
10117 "yuv420p",
10118 "-t",
10119 "0.04",
10120 "-f",
10121 "yuv4mpegpipe",
10122 "-",
10123 ])
10124 .stdin(Stdio::null())
10125 .stdout(Stdio::piped())
10126 .stderr(Stdio::piped())
10127 .output()
10128 .expect("ffmpeg failed to run");
10129 assert!(
10130 y4m.status.success(),
10131 "ffmpeg fixture: {}",
10132 String::from_utf8_lossy(&y4m.stderr)
10133 );
10134 let mut child = Command::new(aomenc_path())
10135 .args([
10136 "--codec=av1",
10137 "--passes=1",
10138 "--end-usage=q",
10139 "--cq-level=45",
10140 "--cpu-used=0",
10141 "--enable-rect-partitions=0",
10142 "--enable-ab-partitions=0",
10143 "--enable-1to4-partitions=0",
10144 "--enable-filter-intra=0",
10145 "--enable-smooth-intra=1",
10146 // Smooth/paeth chroma is a still-refused, separate
10147 // round-2 gap -- off so no attempt trips it while this
10148 // gate is purely about luma's edge-filter fix.
10149 "--enable-paeth-intra=0",
10150 "--enable-tx-size-search=0",
10151 "--enable-cdef=0",
10152 "--enable-restoration=0",
10153 "--enable-intra-edge-filter=1",
10154 "--max-partition-size=32",
10155 "--min-partition-size=16",
10156 "--enable-palette=0",
10157 "--enable-intrabc=0",
10158 "--enable-cfl-intra=0",
10159 "--enable-ref-frame-mvs=0",
10160 "--obu",
10161 "-o",
10162 "-",
10163 "-",
10164 ])
10165 .stdin(Stdio::piped())
10166 .stdout(Stdio::piped())
10167 .stderr(Stdio::piped())
10168 .spawn()
10169 .expect("aomenc failed to start");
10170 child
10171 .stdin
10172 .take()
10173 .expect("aomenc stdin")
10174 .write_all(&y4m.stdout)
10175 .expect("writing y4m to aomenc");
10176 let out = child.wait_with_output().expect("aomenc failed to run");
10177 assert!(
10178 out.status.success(),
10179 "aomenc refused the fixture: {}",
10180 String::from_utf8_lossy(&out.stderr)
10181 );
10182 let stream = out.stdout;
10183 let smooth_before = decode::smooth_luma_hits();
10184 let frames = match decode_stream(&stream) {
10185 Ok(frames) => frames,
10186 Err(e) => {
10187 refusals.push(format!("seed {seed}: {e}"));
10188 continue;
10189 }
10190 };
10191 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
10192 // is ALWAYS pixel-compared below; the hit counter only decides whether
10193 // the attempt counts toward the firing total.
10194 let counted = decode::smooth_luma_hits() != smooth_before;
10195 if counted {
10196 fired_runs += 1;
10197 } else {
10198 uncounted_exact += 1;
10199 refusals.push(format!(
10200 "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \
10201 fired"
10202 ));
10203 }
10204 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
10205 assert_eq!(
10206 frames[0].y, ffmpeg_frames[0].y,
10207 "luma vs ffmpeg (seed {seed})"
10208 );
10209 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
10210 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
10211 if fired_runs >= 4 {
10212 gate_buckets(
10213 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
10214 fired_runs,
10215 uncounted_exact,
10216 refusals.len() - uncounted_exact as usize,
10217 );
10218 return;
10219 }
10220 }
10221 gate_buckets(
10222 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
10223 fired_runs,
10224 uncounted_exact,
10225 refusals.len() - uncounted_exact as usize,
10226 );
10227 assert!(
10228 fired_runs > 0,
10229 "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}",
10230 refusals.join("\n")
10231 );
10232 }
10233
10234 /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key
10235 /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the
10236 /// opposite of the directional-chroma gate below, which turns these OFF
10237 /// to keep this gap from firing while directional chroma is under test).
10238 /// Some seeds won't pick smooth/paeth for chroma at all -- retry like
10239 /// every other real-encoder gate here, but the first attempt that
10240 /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact.
10241 #[test]
10242 fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() {
10243 if !have_ffmpeg() {
10244 eprintln!(
10245 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg"
10246 );
10247 return;
10248 }
10249 if !have_aomenc() {
10250 eprintln!(
10251 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}",
10252 aomenc_path().display()
10253 );
10254 return;
10255 }
10256 let (width, height) = (64usize, 64usize);
10257 let mut refusals = Vec::new();
10258 let mut fired_runs = 0u32;
10259 let mut uncounted_exact = 0u32;
10260 for attempt in 0..40u32 {
10261 let seed = 42 + attempt;
10262 let source = format!(
10263 "mandelbrot=size=64x64:start_scale={}:rate=25",
10264 5.0 - f64::from(attempt) * 0.06
10265 );
10266 let y4m = Command::new("ffmpeg")
10267 .args([
10268 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-t",
10269 "0.04", "-f", "yuv4mpegpipe", "-",
10270 ])
10271 .stdin(Stdio::null())
10272 .stdout(Stdio::piped())
10273 .stderr(Stdio::piped())
10274 .output()
10275 .expect("ffmpeg failed to run");
10276 assert!(
10277 y4m.status.success(),
10278 "ffmpeg fixture: {}",
10279 String::from_utf8_lossy(&y4m.stderr)
10280 );
10281 let mut child = Command::new(aomenc_path())
10282 .args([
10283 "--codec=av1",
10284 "--passes=1",
10285 "--end-usage=q",
10286 "--cq-level=45",
10287 "--cpu-used=0",
10288 "--enable-rect-partitions=0",
10289 "--enable-ab-partitions=0",
10290 "--enable-1to4-partitions=0",
10291 "--enable-filter-intra=0",
10292 "--enable-smooth-intra=1",
10293 "--enable-paeth-intra=1",
10294 "--enable-tx-size-search=0",
10295 "--enable-cdef=0",
10296 "--enable-restoration=0",
10297 "--enable-intra-edge-filter=1",
10298 "--max-partition-size=32",
10299 // 8x8/leaf8 splits are a separate, already-named refusal.
10300 "--min-partition-size=16",
10301 "--enable-palette=0",
10302 "--enable-intrabc=0",
10303 "--enable-cfl-intra=0",
10304 "--enable-ref-frame-mvs=0",
10305 "--obu",
10306 "-o",
10307 "-",
10308 "-",
10309 ])
10310 .stdin(Stdio::piped())
10311 .stdout(Stdio::piped())
10312 .stderr(Stdio::piped())
10313 .spawn()
10314 .expect("aomenc failed to start");
10315 child
10316 .stdin
10317 .take()
10318 .expect("aomenc stdin")
10319 .write_all(&y4m.stdout)
10320 .expect("writing y4m to aomenc");
10321 let out = child.wait_with_output().expect("aomenc failed to run");
10322 assert!(
10323 out.status.success(),
10324 "aomenc refused the fixture: {}",
10325 String::from_utf8_lossy(&out.stderr)
10326 );
10327 let stream = out.stdout;
10328 let smooth_before = decode::smooth_uv_hits();
10329 let frames = match decode_stream(&stream) {
10330 Ok(frames) => frames,
10331 Err(e) => {
10332 refusals.push(format!("seed {seed}: {e}"));
10333 continue;
10334 }
10335 };
10336 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
10337 // is ALWAYS pixel-compared below; the hit counter only decides whether
10338 // the attempt counts toward the firing total.
10339 let counted = decode::smooth_uv_hits() != smooth_before;
10340 if counted {
10341 fired_runs += 1;
10342 } else {
10343 uncounted_exact += 1;
10344 refusals.push(format!(
10345 "seed {seed}: decoded and pixel-compared, but no smooth/paeth uv_mode fired"
10346 ));
10347 }
10348 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
10349 assert_eq!(
10350 frames[0].y, ffmpeg_frames[0].y,
10351 "luma vs ffmpeg (seed {seed})"
10352 );
10353 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
10354 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
10355 if fired_runs >= 4 {
10356 gate_buckets(
10357 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
10358 fired_runs,
10359 uncounted_exact,
10360 refusals.len() - uncounted_exact as usize,
10361 );
10362 return;
10363 }
10364 }
10365 gate_buckets(
10366 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
10367 fired_runs,
10368 uncounted_exact,
10369 refusals.len() - uncounted_exact as usize,
10370 );
10371 assert!(
10372 fired_runs > 0,
10373 "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}",
10374 refusals.join("\n")
10375 );
10376 }
10377
10378 /// The directional-chroma/angle-delta gate: a real aomenc key frame with
10379 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
10380 /// opposite of every sibling recipe's `=0`, which existed specifically to
10381 /// keep this round-2 gap from firing while a different surface was under
10382 /// test). A colourful, sharp-edged source gives the RD search a reason to
10383 /// pick a directional `uv_mode` and/or a nonzero angle delta -- some
10384 /// seeds still won't, so retry like every other real-encoder gate here,
10385 /// but the first attempt that actually fires either counter must decode
10386 /// pixel-exact.
10387 #[test]
10388 fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() {
10389 if !have_ffmpeg() {
10390 eprintln!(
10391 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg"
10392 );
10393 return;
10394 }
10395 if !have_aomenc() {
10396 eprintln!(
10397 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}",
10398 aomenc_path().display()
10399 );
10400 return;
10401 }
10402 let (width, height) = (64usize, 64usize);
10403 let mut refusals = Vec::new();
10404 let mut fired_runs = 0u32;
10405 let mut uncounted_exact = 0u32;
10406 for attempt in 0..40u32 {
10407 let seed = 42 + attempt;
10408 let source = format!(
10409 "mandelbrot=size=64x64:start_scale={}:rate=25",
10410 5.0 - f64::from(attempt) * 0.06
10411 );
10412 let y4m = Command::new("ffmpeg")
10413 .args([
10414 "-v",
10415 "error",
10416 "-f",
10417 "lavfi",
10418 "-i",
10419 &source,
10420 "-pix_fmt",
10421 "yuv420p",
10422 "-t",
10423 "0.04",
10424 "-f",
10425 "yuv4mpegpipe",
10426 "-",
10427 ])
10428 .stdin(Stdio::null())
10429 .stdout(Stdio::piped())
10430 .stderr(Stdio::piped())
10431 .output()
10432 .expect("ffmpeg failed to run");
10433 assert!(
10434 y4m.status.success(),
10435 "ffmpeg fixture: {}",
10436 String::from_utf8_lossy(&y4m.stderr)
10437 );
10438 let mut child = Command::new(aomenc_path())
10439 .args([
10440 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
10441 // occurrence, so overrides go before the base list).
10442 "--enable-directional-intra=1",
10443 "--codec=av1",
10444 "--passes=1",
10445 "--end-usage=q",
10446 "--cq-level=45",
10447 "--cpu-used=0",
10448 "--enable-rect-partitions=0",
10449 "--enable-ab-partitions=0",
10450 "--enable-1to4-partitions=0",
10451 "--enable-filter-intra=0",
10452 // Smooth/Paeth chroma is a separate, still-refused round-2
10453 // gap (an unrelated `Edges::build` no-neighbour bug this
10454 // lane does not cover) -- off so the RD search's only
10455 // non-DC/CFL chroma choice left is directional.
10456 "--enable-smooth-intra=0",
10457 "--enable-paeth-intra=0",
10458 "--enable-tx-size-search=0",
10459 "--enable-cdef=0",
10460 "--enable-restoration=0",
10461 // The intra edge filter/upsample (spec 7.11.2.7-2.9) is
10462 // now implemented (`directional()`) -- left ON (aomenc's
10463 // own default) so this gate actually exercises it instead
10464 // of the un-filtered fast path a disabled flag would keep
10465 // testing.
10466 "--enable-intra-edge-filter=1",
10467 "--max-partition-size=32",
10468 // Same reason as the tx-select gate above: 8x8 and other
10469 // sub-16x16 splits are a separate, already-named refusal.
10470 "--min-partition-size=16",
10471 "--enable-palette=0",
10472 "--enable-intrabc=0",
10473 "--enable-cfl-intra=0",
10474 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
10475 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
10476 "--enable-ref-frame-mvs=0",
10477 "--obu",
10478 "-o",
10479 "-",
10480 "-",
10481 ])
10482 .stdin(Stdio::piped())
10483 .stdout(Stdio::piped())
10484 .stderr(Stdio::piped())
10485 .spawn()
10486 .expect("aomenc failed to start");
10487 child
10488 .stdin
10489 .take()
10490 .expect("aomenc stdin")
10491 .write_all(&y4m.stdout)
10492 .expect("writing y4m to aomenc");
10493 let out = child.wait_with_output().expect("aomenc failed to run");
10494 assert!(
10495 out.status.success(),
10496 "aomenc refused the fixture: {}",
10497 String::from_utf8_lossy(&out.stderr)
10498 );
10499 let stream = out.stdout;
10500 let (uv_before, angle_before) =
10501 (decode::directional_uv_hits(), decode::angle_delta_hits());
10502 let frames = match decode_stream(&stream) {
10503 Ok(frames) => frames,
10504 Err(e) => {
10505 refusals.push(format!("seed {seed}: {e}"));
10506 continue;
10507 }
10508 };
10509 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
10510 // is ALWAYS pixel-compared below; the hit counter only decides whether
10511 // the attempt counts toward the firing total.
10512 let counted = decode::directional_uv_hits() != uv_before
10513 || decode::angle_delta_hits() != angle_before;
10514 if counted {
10515 fired_runs += 1;
10516 } else {
10517 uncounted_exact += 1;
10518 refusals.push(format!(
10519 "seed {seed}: decoded and pixel-compared, but neither a directional uv_mode \
10520 nor a nonzero angle delta fired"
10521 ));
10522 }
10523 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
10524 assert_eq!(
10525 frames[0].y, ffmpeg_frames[0].y,
10526 "luma vs ffmpeg (seed {seed})"
10527 );
10528 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
10529 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
10530 if fired_runs >= 4 {
10531 gate_buckets(
10532 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
10533 fired_runs,
10534 uncounted_exact,
10535 refusals.len() - uncounted_exact as usize,
10536 );
10537 return;
10538 }
10539 }
10540 gate_buckets(
10541 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
10542 fired_runs,
10543 uncounted_exact,
10544 refusals.len() - uncounted_exact as usize,
10545 );
10546 assert!(
10547 fired_runs > 0,
10548 "every attempt hit a named refusal or never exercised directional chroma:\n{}",
10549 refusals.join("\n")
10550 );
10551 }
10552
10553 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
10554 /// --auto-alt-ref=0` keep every non-key frame a simple forward
10555 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this
10556 /// decoder's inter path does not model), `--kf-max-dist` past the clip's
10557 /// own length keeps frame 0 the only key frame.
10558 /// lane-inter8 r1: the inter tile path's SB-level `PARTITION_NONE` -- a
10559 /// whole 64x64 superblock coded as ONE inter block, which is what aomenc
10560 /// picks for static content and which this decoder refused by name
10561 /// ("an inter SB-level partition type other than SPLIT") until this
10562 /// round. HARD-asserts [`decode::inter_sb_none_hits`] moved (the arm
10563 /// really fired, class refusal-lifted-without-a-gate) and every frame is
10564 /// pixel-exact vs ffmpeg; a decode error is a FAILURE here, never a SKIP
10565 /// (class gate-skips-on-its-own-failure).
10566 /// lane-inter8 r1: generalised so the same recipe can target a deeper
10567 /// level of the inter partition tree -- `min_part` is aomenc's
10568 /// `--min-partition-size`, and `hits`/`what` name the counter that proves
10569 /// the arm under test really fired.
10570 #[track_caller]
10571 fn inter_sb_none_gate(
10572 name: &str,
10573 ten_bit: bool,
10574 min_part: &str,
10575 max_part: &str,
10576 hits: fn() -> usize,
10577 what: &str,
10578 // lane-inter8 r3: extra aomenc flags + the frame width they need.
10579 // `--tile-columns=1` needs a frame at least two superblocks wide or
10580 // aomenc silently codes one tile column and the arm is vacuous.
10581 extra: &[&str],
10582 width: usize,
10583 // lane-interp3 r1: sequence length -- a compound block needs several
10584 // already-coded references, which a 4-frame sequence never has.
10585 frame_count: usize,
10586 ) {
10587 if !have_ffmpeg() {
10588 eprintln!("SKIP {name}: no ffmpeg");
10589 return;
10590 }
10591 if !have_aomenc() {
10592 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
10593 return;
10594 }
10595 let height = 64usize;
10596 let duration = format!("{:.2}", frame_count as f64 / 25.0);
10597 // A deterministic synthetic source with real motion (a static source
10598 // codes every inter frame as skip and never exercises the residual
10599 // path); bounded with `-t` (class gate-loader-slurps-whole-file).
10600 let y4m = Command::new("ffmpeg")
10601 .args([
10602 "-v",
10603 "error",
10604 "-f",
10605 "lavfi",
10606 "-i",
10607 &format!("mandelbrot=size={width}x{height}:rate=25"),
10608 "-t",
10609 &duration,
10610 "-pix_fmt",
10611 if ten_bit { "yuv420p10le" } else { "yuv420p" },
10612 // y4m calls 10-bit unofficial (same as the 10-bit key-frame
10613 // gate's own fixture).
10614 "-strict",
10615 "-1",
10616 "-f",
10617 "yuv4mpegpipe",
10618 "-",
10619 ])
10620 .stdin(Stdio::null())
10621 .stdout(Stdio::piped())
10622 .stderr(Stdio::piped())
10623 .output()
10624 .expect("ffmpeg failed to run");
10625 assert!(
10626 y4m.status.success(),
10627 "{name}: ffmpeg fixture: {}",
10628 String::from_utf8_lossy(&y4m.stderr)
10629 );
10630 let mut args: Vec<String> = [
10631 "--codec=av1",
10632 "--passes=1",
10633 "--end-usage=q",
10634 "--cq-level=40",
10635 "--cpu-used=0",
10636 "--lag-in-frames=0",
10637 "--auto-alt-ref=0",
10638 "--kf-max-dist=1000",
10639 // No cross-frame CDF forwarding in this fixture (see the
10640 // deblocking gate's own note).
10641 "--error-resilient=1",
10642 // This gate targets the SB-level NONE arm only: rect/AB/1-to-4
10643 // partitions and sub-16x16 splits stay off so a failure here
10644 // cannot be another lane's missing arm.
10645 "--enable-rect-partitions=0",
10646 "--enable-ab-partitions=0",
10647 "--enable-1to4-partitions=0",
10648 "--enable-filter-intra=0",
10649 "--enable-smooth-intra=0",
10650 "--enable-paeth-intra=0",
10651 "--enable-directional-intra=0",
10652 "--enable-angle-delta=0",
10653 "--enable-tx-size-search=0",
10654 "--enable-cdef=0",
10655 "--enable-restoration=0",
10656 "--enable-palette=0",
10657 "--enable-intrabc=0",
10658 "--enable-cfl-intra=0",
10659 "--enable-ref-frame-mvs=0",
10660 "--obu",
10661 "-o",
10662 "-",
10663 "-",
10664 ]
10665 .iter()
10666 .map(|s| (*s).to_string())
10667 .collect();
10668 for e in extra {
10669 args.insert(1, (*e).to_string());
10670 }
10671 args.insert(1, format!("--min-partition-size={min_part}"));
10672 args.insert(1, format!("--max-partition-size={max_part}"));
10673 if ten_bit {
10674 args.insert(1, "--input-bit-depth=10".to_string());
10675 args.insert(1, "--bit-depth=10".to_string());
10676 }
10677 let mut child = Command::new(aomenc_path())
10678 .args(&args)
10679 .stdin(Stdio::piped())
10680 .stdout(Stdio::piped())
10681 .stderr(Stdio::piped())
10682 .spawn()
10683 .expect("aomenc failed to start");
10684 child
10685 .stdin
10686 .take()
10687 .expect("aomenc stdin")
10688 .write_all(&y4m.stdout)
10689 .expect("writing y4m to aomenc");
10690 let out = child.wait_with_output().expect("aomenc failed to run");
10691 assert!(
10692 out.status.success(),
10693 "{name}: aomenc refused the fixture: {}",
10694 String::from_utf8_lossy(&out.stderr)
10695 );
10696 let stream = out.stdout;
10697 let before = hits();
10698 let frames = match decode_stream(&stream) {
10699 Ok(frames) => frames,
10700 Err(e) => {
10701 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
10702 let _ = std::fs::write(&pin, &stream);
10703 panic!("{name}: decode_stream refused a real aomenc stream: {e} (pinned at {})", pin.display());
10704 }
10705 };
10706 assert!(
10707 hits() > before,
10708 "{name}: no {what} fired -- this gate proves nothing"
10709 );
10710 let ffmpeg_frames = if ten_bit {
10711 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
10712 } else {
10713 ffmpeg_decode_sequence(&stream, width, height, frame_count)
10714 };
10715 assert_eq!(frames.len(), frame_count, "{name}: frame count");
10716 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10717 if got.y != want.y || got.u != want.u || got.v != want.v {
10718 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
10719 let _ = std::fs::write(&pin, &stream);
10720 panic!("{name}: frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display());
10721 }
10722 }
10723 }
10724
10725 #[test]
10726 fn a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
10727 inter_sb_none_gate(
10728 "a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
10729 false,
10730 "32",
10731 "64",
10732 decode::inter_sb_none_hits,
10733 "whole-superblock inter PARTITION_NONE",
10734 &[],
10735 64,
10736 4,
10737 );
10738 }
10739
10740 #[test]
10741 fn a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
10742 inter_sb_none_gate(
10743 "a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
10744 true,
10745 "32",
10746 "64",
10747 decode::inter_sb_none_hits,
10748 "whole-superblock inter PARTITION_NONE",
10749 &[],
10750 64,
10751 4,
10752 );
10753 }
10754
10755 /// lane-inter8 r1: the same recipe with `--min-partition-size=8`, so
10756 /// aomenc's RD may split a 16x16 inter block into four 8x8 leaves. The
10757 /// interior (non-edge-straddling) `PARTITION_SPLIT` at the 16x16 level
10758 /// was refused by name until this round; the straddle path always ran the
10759 /// same loop, so only [`decode::inter_sub16_split_hits`] -- which counts
10760 /// interior splits only -- proves the newly-lifted alphabet value fired.
10761 // lane-inter8 r2: GREEN. The neighbour side bands are mi-granular, every
10762 // leaf stamps its own 2x2-mi span (including the compound-return path
10763 // that used to skip `record_mi` entirely) and the compound
10764 // group/index contexts read the LEAF's mi cell, not its 16x16's corner.
10765 /// lane-inter8 r3, from lane-sub8's verifier finding: the mi-granular
10766 /// inter neighbour bands added in r2 must reset per TILE (above) and per
10767 /// SB row (left) and guard availability tile-relative, so the same recipe
10768 /// runs again at 128x64 with two tile columns -- a leaf on the second
10769 /// tile's first column has no left neighbour and must not read the first
10770 /// tile's band.
10771 // 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
10772 // was done by inspection instead: every reader of the mi bands guards on
10773 // `tile_row0_mi`/`tile_col0_mi` (no `> 0` guard exists in decode.rs),
10774 // `start_tile` resets the above mi bands over the tile's own mi column
10775 // span and `start_row` resets every left mi band.
10776 #[test]
10777 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact()
10778 {
10779 inter_sb_none_gate(
10780 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact",
10781 false,
10782 "8",
10783 "16",
10784 decode::inter_sub16_split_hits,
10785 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
10786 &["--tile-columns=1"],
10787 128,
10788 4,
10789 );
10790 }
10791
10792 /// lane-interp3 r1: the same 8x8-leaf recipe with DUAL FILTER, OBMC and
10793 /// warped motion on. `read_mb_interp_filter` runs for every inter block
10794 /// (libaom `decodemv.c` 1575), compound ones included; the compound 8x8
10795 /// leaf skipped it entirely, so a SWITCHABLE-filter stream lost a symbol
10796 /// per compound leaf and stamped the `[3, 3]` "no filter" sentinel, which
10797 /// made a neighbouring OBMC block's `neighbour_filter` PANIC (a crash on
10798 /// his data, not a named refusal). The three hard asserts prove the flags
10799 /// arrived: a compound 8x8 leaf that really read the filter, a block whose
10800 /// two dual-filter directions DIFFER (impossible with dual filter off),
10801 /// and an 8x8 OBMC blend.
10802 // lane-interp3 r2: the ENTROPY desync r1 measured is CLOSED -- the full
10803 // 16-frame stream now parses end to end and every `EC_MODE`/`EC_MODE_VAL`
10804 // element's msac RANGE matches the instrumented aomdec's line for line
10805 // (570/570 mode elements, 0 diff). Two twin-drift root causes, both in
10806 // `decode_inter_block8`'s compound arm: `read_compound_ref_frames` was
10807 // passed a hard-coded `LAST_FRAME` for every inter neighbour instead of
10808 // the real per-mi band, and the grid stamp cleared both per-slot
10809 // `is_global_mv_block` flags.
10810 // lane-interp3 r3: the luma reconstruction residue r2 left open is CLOSED
10811 // and this gate is GREEN. Third instance of the same twin-drift class:
10812 // libaom applies `allow_warp`'s GLOBAL branch to every
10813 // `is_global_mv_block` reference slot, compound included and independent
10814 // of `motion_mode` (`av1_init_warp_params` inside
10815 // `build_inter_predictors_8x8_and_bigger`'s per-`ref` loop) -- the 16x16+
10816 // compound arm has warped since lane-cwarp r1, the 8x8 leaf's compound arm
10817 // predicted BOTH taps translationally, so a GLOBAL_GLOBALMV 8x8 compound
10818 // leaf under a non-TRANSLATION model drifted a few luma levels, growing
10819 // away from the block origin. It was NOT OBMC: the `EC_OBMC` emitter this
10820 // round added to `decode.rs` diffs 325/325 lines against the instrumented
10821 // aomdec's own rung (position, span, neighbour mv/ref/bsize/filter) with
10822 // zero differences.
10823 #[test]
10824 fn a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() {
10825 const NAME: &str =
10826 "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact";
10827 if !have_ffmpeg() || !have_aomenc() {
10828 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
10829 return;
10830 }
10831 let before_dual = decode::dual_filter_diff_hits();
10832 let before_obmc = decode::obmc_hits_8();
10833 let before_cwarp8 = decode::compound_warp_hits_8();
10834 inter_sb_none_gate(
10835 NAME,
10836 false,
10837 "8",
10838 "16",
10839 decode::compound8_filter_hits,
10840 "a compound 8x8 leaf reading its own switchable interp_filter",
10841 &[
10842 "--enable-dual-filter=1",
10843 "--enable-obmc=1",
10844 "--enable-warped-motion=1",
10845 "--enable-onesided-comp=1",
10846 ],
10847 64,
10848 // Recipe search hook (same shape as EC_OBMC8_ATTEMPTS): a compound
10849 // block needs several coded references, so the sequence is longer
10850 // than the other arms' 4 frames.
10851 std::env::var("EC_INTERP3_FRAMES")
10852 .ok()
10853 .and_then(|v| v.parse().ok())
10854 .unwrap_or(16),
10855 );
10856 assert!(
10857 decode::dual_filter_diff_hits() > before_dual,
10858 "{NAME}: no block read two DIFFERENT dual-filter directions -- \
10859 --enable-dual-filter=1 did not arrive or aomenc declined it"
10860 );
10861 assert!(
10862 decode::obmc_hits_8() > before_obmc,
10863 "{NAME}: no 8x8 OBMC blend fired -- --enable-obmc=1 did not arrive"
10864 );
10865 assert!(
10866 decode::compound_warp_hits_8() > before_cwarp8,
10867 "{NAME}: no 8x8 COMPOUND leaf was predicted through the per-ref GLOBAL \
10868 warp -- the r3 root-cause path never fired, so this stream no longer \
10869 proves it"
10870 );
10871 }
10872
10873 #[test]
10874 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
10875 inter_sb_none_gate(
10876 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
10877 false,
10878 "8",
10879 "16",
10880 decode::inter_sub16_split_hits,
10881 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
10882 &[],
10883 64,
10884 4,
10885 );
10886 }
10887
10888 #[test]
10889 // 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.
10890 fn a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
10891 inter_sb_none_gate(
10892 "a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
10893 true,
10894 "8",
10895 "16",
10896 decode::inter_sub16_split_hits,
10897 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
10898 &[],
10899 64,
10900 4,
10901 );
10902 }
10903
10904 /// lane-eobc1 r1: an INTER sequence whose CHROMA coefficient blocks come
10905 /// off the class-1 (`TX_CLASS_HORIZ`/`VERT`) `eob_pt` row. Chroma codes
10906 /// no `tx_type` symbol of its own -- it inherits the colocated luma type
10907 /// (`av1_get_tx_type`, `blockd.h:1291`) -- so an 8x8 inter leaf whose
10908 /// luma picks `H_*`/`V_*` puts its 4x4 chroma on a CDF row this crate
10909 /// wired for only some sizes until this round (`eob_pt_class1: None` in
10910 /// 9 of 16 `TxbSet` arms, chroma 4x4/8x8 among them).
10911 ///
10912 /// The full tx set stays on (no `--reduced-tx-type-set=1`) and
10913 /// `--enable-flip-idtx=1` is asked for explicitly; the sinusoidal-stripe
10914 /// luma of the `tx_class1` key-frame gate is what actually resolves 1D
10915 /// types, and the temporally-moving chroma ramp keeps chroma out of
10916 /// `all_zero` so it has an `eob` to read at all. Attempts sweep cq and
10917 /// stripe period; a run counts only when
10918 /// [`decode::chroma_eob_class1_hits`] moved, and every shown frame is
10919 /// compared pixel-exact vs ffmpeg (a decode error is a FAILURE, never a
10920 /// SKIP -- class gate-skips-on-its-own-failure).
10921 fn chroma_class1_eob_gate(name: &str, ten_bit: bool) {
10922 if !have_ffmpeg() {
10923 eprintln!("SKIP {name}: no ffmpeg");
10924 return;
10925 }
10926 if !have_aomenc() {
10927 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
10928 return;
10929 }
10930 let (width, height, frame_count) = (64usize, 64usize, 4usize);
10931 let mut refusals = Vec::new();
10932 for attempt in 0..12u32 {
10933 let cq = 28 + (attempt % 4) * 10;
10934 let period = [4u32, 6, 8][(attempt as usize / 4) % 3];
10935 let y4m = Command::new("ffmpeg")
10936 .args([
10937 "-v",
10938 "error",
10939 "-f",
10940 "lavfi",
10941 "-i",
10942 &format!("testsrc2=size={width}x{height}:rate=25"),
10943 "-vf",
10944 &format!(
10945 "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"
10946 ),
10947 "-t",
10948 "0.16",
10949 "-pix_fmt",
10950 if ten_bit { "yuv420p10le" } else { "yuv420p" },
10951 "-strict",
10952 "-1",
10953 "-f",
10954 "yuv4mpegpipe",
10955 "-",
10956 ])
10957 .stdin(Stdio::null())
10958 .stdout(Stdio::piped())
10959 .stderr(Stdio::piped())
10960 .output()
10961 .expect("ffmpeg failed to run");
10962 assert!(
10963 y4m.status.success(),
10964 "{name}: ffmpeg fixture: {}",
10965 String::from_utf8_lossy(&y4m.stderr)
10966 );
10967 let mut args: Vec<String> = [
10968 "--codec=av1",
10969 "--passes=1",
10970 "--end-usage=q",
10971 "--cpu-used=0",
10972 "--lag-in-frames=0",
10973 "--auto-alt-ref=0",
10974 "--kf-max-dist=1000",
10975 "--error-resilient=1",
10976 "--enable-flip-idtx=1",
10977 "--reduced-tx-type-set=0",
10978 "--min-partition-size=8",
10979 "--max-partition-size=16",
10980 // Motion tools this decoder refuses by name, kept off so a
10981 // refusal here can only be about the coefficient path.
10982 "--enable-global-motion=0",
10983 "--enable-warped-motion=0",
10984 "--enable-obmc=0",
10985 "--enable-rect-partitions=0",
10986 "--enable-ab-partitions=0",
10987 "--enable-1to4-partitions=0",
10988 "--enable-filter-intra=0",
10989 "--enable-smooth-intra=0",
10990 "--enable-paeth-intra=0",
10991 "--enable-directional-intra=0",
10992 "--enable-angle-delta=0",
10993 "--enable-tx-size-search=0",
10994 "--enable-cdef=0",
10995 "--enable-restoration=0",
10996 "--loopfilter-control=0",
10997 "--enable-palette=0",
10998 "--enable-intrabc=0",
10999 "--enable-cfl-intra=0",
11000 "--enable-ref-frame-mvs=0",
11001 "--obu",
11002 "-o",
11003 "-",
11004 "-",
11005 ]
11006 .iter()
11007 .map(|s| (*s).to_string())
11008 .collect();
11009 args.insert(1, format!("--cq-level={cq}"));
11010 if ten_bit {
11011 args.insert(1, "--input-bit-depth=10".to_string());
11012 args.insert(1, "--bit-depth=10".to_string());
11013 }
11014 let mut child = Command::new(aomenc_path())
11015 .args(&args)
11016 .stdin(Stdio::piped())
11017 .stdout(Stdio::piped())
11018 .stderr(Stdio::piped())
11019 .spawn()
11020 .expect("aomenc failed to start");
11021 child
11022 .stdin
11023 .take()
11024 .expect("aomenc stdin")
11025 .write_all(&y4m.stdout)
11026 .expect("writing y4m to aomenc");
11027 let out = child.wait_with_output().expect("aomenc failed to run");
11028 assert!(
11029 out.status.success(),
11030 "{name}: aomenc refused the fixture: {}",
11031 String::from_utf8_lossy(&out.stderr)
11032 );
11033 let stream = out.stdout;
11034 let before = decode::chroma_eob_class1_hits();
11035 let frames = match decode_stream(&stream) {
11036 Ok(frames) => frames,
11037 // A named refusal ("unsupported: ...") is another lane's arm
11038 // and moves this attempt on; anything else is a real decode
11039 // failure and fails the gate on the spot.
11040 Err(e) if e.to_string().contains("unsupported") => {
11041 refusals.push(format!("cq={cq} period={period}: {e}"));
11042 continue;
11043 }
11044 Err(e) => {
11045 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
11046 let _ = std::fs::write(&pin, &stream);
11047 panic!(
11048 "{name}: decode_stream failed on a real aomenc stream (cq={cq} period={period}): {e} (pinned at {})",
11049 pin.display()
11050 );
11051 }
11052 };
11053 if decode::chroma_eob_class1_hits() == before {
11054 refusals.push(format!(
11055 "cq={cq} period={period}: decoded, but no chroma block read a class-1 eob_pt row"
11056 ));
11057 continue;
11058 }
11059 let ffmpeg_frames = if ten_bit {
11060 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
11061 } else {
11062 ffmpeg_decode_sequence(&stream, width, height, frame_count)
11063 };
11064 assert_eq!(frames.len(), frame_count, "{name}: frame count");
11065 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11066 if got.y != want.y || got.u != want.u || got.v != want.v {
11067 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
11068 let _ = std::fs::write(&pin, &stream);
11069 panic!(
11070 "{name}: frame {i} mismatch vs ffmpeg (cq={cq} period={period}) -- stream pinned at {}",
11071 pin.display()
11072 );
11073 }
11074 }
11075 return;
11076 }
11077 panic!("{name}: no attempt fired a class-1 chroma eob: {refusals:?}");
11078 }
11079
11080 #[test]
11081 fn a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
11082 chroma_class1_eob_gate(
11083 "a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
11084 false,
11085 );
11086 }
11087
11088 #[test]
11089 fn a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
11090 chroma_class1_eob_gate(
11091 "a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
11092 true,
11093 );
11094 }
11095
11096 /// lane-inter4 r1: the SUPERBLOCK-level inter `PARTITION_HORZ`/
11097 /// `PARTITION_VERT` pair -- two 64x32 / 32x64 inter strips, the arm the
11098 /// inter tile path refused outright before this lane ("an inter SB-level
11099 /// partition type other than NONE or SPLIT"). `--min-partition-size=32`
11100 /// keeps every 32x32-level rect shape (already coded, and residual-capable
11101 /// only when skip) out of the picture so the counters can only be earned
11102 /// at the superblock level; the noiseless split-motion source (one half
11103 /// translating, the other static, flat inside each half) is what makes
11104 /// aomenc's RD pick a superblock HORZ/VERT whose strips are `skip` --
11105 /// the ONLY inter rect shape this decoder can complete, since rectangular
11106 /// inter residual coding is not ported (see `reject_residual`).
11107 ///
11108 /// Every decoded frame is compared to ffmpeg (Y, U and V); an attempt
11109 /// that refuses by name is counted, never turned into a SKIP; and an
11110 /// attempt that decoded without firing the arm is counted separately and
11111 /// still required to be pixel-exact (class gate-skips-on-its-own-failure).
11112 #[test]
11113 fn a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact() {
11114 const NAME: &str = "a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact";
11115 let _gate_lock = lock_gate_counters();
11116 if !have_ffmpeg() {
11117 eprintln!("SKIP {NAME}: no ffmpeg");
11118 return;
11119 }
11120 if !have_aomenc() {
11121 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11122 return;
11123 }
11124 let (width, height, frame_count) = (192usize, 128usize, 6usize);
11125 // lane-inter4 r1: 8-bit ONLY, and the reason is the lane's own open
11126 // residue, not a tolerance: across all 16 attempts x both depths, every
11127 // 10-bit attempt that reached a superblock-level rect strip found it
11128 // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B)
11129 // strip needs rectangular residual coding". The 10-bit twin below is
11130 // `#[ignore]`d with that exact reason rather than deleted or weakened.
11131 // lane-r14 r2 re-measured the 8-bit-only note above: the residual
11132 // refusal it names is GONE (this round codes a 64-px transform axis as
11133 // its truncated low-32 corner), and a 10-bit sweep of this exact
11134 // recipe now reaches the arm -- 2 pixel-exact attempts, 2 64x32 and 2
11135 // 32x64 strips, 2 of them carrying a coded 64-axis residual.
11136 // lane-sbrect10 r1 closed the newly exposed 10-bit defect r14 r2
11137 // parked this arm on (10-bit attempt 14, cq 61, horizontal split,
11138 // motion step 12 -- it mismatched ffmpeg while decoding ZERO rect
11139 // strips): a 64x64 INTRA block inside an inter frame read `uv_mode`
11140 // off the 14-symbol CFL-allowed alphabet, which libaom's
11141 // `is_cfl_allowed` caps at 32x32 -- same DC_PRED value, wrong
11142 // interval narrowing, tile desynced from that block on. Both depths
11143 // run now.
11144 for bit_depth in [8u32, 10u32] {
11145 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
11146 (0u32, 0u32, 0u32, 0u32);
11147 let (mut horz_proved, mut vert_proved) = (0usize, 0usize);
11148 let mut rect64_tus = 0usize;
11149 for attempt in 0..16u32 {
11150 // Two orientations (the transposed pair a one-sided gate could
11151 // never separate) x four quantisers x two motion steps: which
11152 // superblock the RD hands a skip-able rect strip moves with
11153 // the quantiser, and the 10-bit arm needs a different corner
11154 // of the grid from the 8-bit one.
11155 let vertical_split = attempt % 2 == 1;
11156 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
11157 let sp = 8 + (attempt / 8) * 4;
11158 let geq = if vertical_split {
11159 format!("if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), 200)")
11160 } else {
11161 format!("if(lt(X,64), 40+mod(floor((Y+N*{sp})/32)*90,200), 200)")
11162 };
11163 let duration = frame_count as f64 / 25.0;
11164 let source = format!(
11165 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
11166 geq=lum='{geq}',format=yuv420p"
11167 );
11168 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
11169 let y4m = Command::new("ffmpeg")
11170 .args([
11171 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
11172 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
11173 ])
11174 .stdin(Stdio::null())
11175 .stdout(Stdio::piped())
11176 .stderr(Stdio::piped())
11177 .output()
11178 .expect("ffmpeg failed to run");
11179 assert!(
11180 y4m.status.success(),
11181 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
11182 String::from_utf8_lossy(&y4m.stderr)
11183 );
11184 let cq_arg = format!("--cq-level={cq}");
11185 let depth_arg = format!("--bit-depth={bit_depth}");
11186 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
11187 let args: Vec<&str> = vec![
11188 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
11189 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
11190 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
11191 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
11192 "--enable-tx-size-search=0", "--lag-in-frames=0",
11193 // Per-arm overrides go LAST: aomenc keeps the last
11194 // occurrence of a repeated --enable-* flag.
11195 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
11196 "--enable-1to4-partitions=1", "--min-partition-size=32",
11197 "--max-partition-size=64",
11198 "--obu", "-o", "-", "-",
11199 ];
11200 let mut child = Command::new(aomenc_path())
11201 .args(&args)
11202 .stdin(Stdio::piped())
11203 .stdout(Stdio::piped())
11204 .stderr(Stdio::piped())
11205 .spawn()
11206 .expect("aomenc failed to start");
11207 child
11208 .stdin
11209 .take()
11210 .expect("aomenc stdin")
11211 .write_all(&y4m.stdout)
11212 .expect("writing y4m to aomenc");
11213 let out = child.wait_with_output().expect("aomenc failed to run");
11214 assert!(
11215 out.status.success(),
11216 "aomenc refused the fixture: {}",
11217 String::from_utf8_lossy(&out.stderr)
11218 );
11219 let stream = out.stdout;
11220 let before = crate::stream::inter_rect_counters();
11221 let rect64_before = crate::stream::rect64_inter_tu_hits();
11222 let frames = match decode_stream(&stream) {
11223 Err(e) => {
11224 let msg = e.to_string();
11225 assert!(
11226 msg.contains("unsupported"),
11227 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
11228 attempt {attempt}): {msg}"
11229 );
11230 named_refusals += 1;
11231 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
11232 continue;
11233 }
11234 Ok(frames) => frames,
11235 };
11236 let after = crate::stream::inter_rect_counters();
11237 let (horz, vert) = (after.2 - before.2, after.3 - before.3);
11238 let rect64 = crate::stream::rect64_inter_tu_hits() - rect64_before;
11239 let ffmpeg_frames = if bit_depth == 10 {
11240 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
11241 } else {
11242 ffmpeg_decode_sequence(&stream, width, height, frame_count)
11243 };
11244 assert_eq!(frames.len(), frame_count);
11245 let mismatched = frames
11246 .iter()
11247 .zip(&ffmpeg_frames)
11248 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
11249 if horz + vert == 0 {
11250 out_of_scope += 1;
11251 if mismatched {
11252 oos_mismatch += 1;
11253 eprintln!(
11254 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
11255 superblock-level inter rect strips -- another shape's defect"
11256 );
11257 }
11258 continue;
11259 }
11260 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11261 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
11262 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
11263 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
11264 }
11265 horz_proved += horz;
11266 vert_proved += vert;
11267 rect64_tus += rect64;
11268 matched += 1;
11269 }
11270 eprintln!(
11271 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
11272 attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \
11273 64-axis residual TUs={rect64_tus}, \
11274 {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)"
11275 );
11276 assert_eq!(
11277 oos_mismatch, 0,
11278 "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \
11279 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
11280 );
11281 // lane-r14 r2: the residual half of the arm -- a strip that is not
11282 // `skip` and codes a real 64-axis transform unit. Without this the
11283 // gate proves only the partition symbol.
11284 assert!(
11285 rect64_tus > 0,
11286 "{NAME} ({bit_depth}-bit): no superblock-level rect strip carried a coded \
11287 64-axis residual transform unit inside a pixel-exact attempt \
11288 (horz={horz_proved}, vert={vert_proved}) -- the residual arm proved nothing"
11289 );
11290 assert!(
11291 horz_proved + vert_proved > 0,
11292 "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \
11293 inside a pixel-exact attempt (horz={horz_proved}, vert={vert_proved}, \
11294 {named_refusals} refusals, {out_of_scope} out of scope) -- gate proved nothing"
11295 );
11296 }
11297 }
11298
11299 /// lane-r14 r3: a 1:4 inter strip with a 64-px axis (64x16 / 16x64) whose
11300 /// transform SPLITS -- the arm r2 left refused by name ("a split transform
11301 /// on a 1:4 inter strip with a 64-px axis"). libaom's
11302 /// `sub_tx_size_map[TX_64X16] == TX_32X16` (and `[TX_16X64] == TX_16X32`)
11303 /// keeps the sub-transform RECTANGULAR, so the var-tx tree's leaves are
11304 /// 32x16/16x32 units read through [`TxbSet::LumaRect32x16Inter`], each with
11305 /// its own `get_txb_ctx_general` neighbour context (the unit is smaller
11306 /// than its block, so `txb_skip_ctx` is NOT the lone-TU 0).
11307 ///
11308 /// `--enable-1to4-partitions=1 --min-partition-size=16
11309 /// --max-partition-size=64 --enable-tx64=1` (each spelled once, last
11310 /// occurrence wins) is what lets aomenc pick a superblock-level HORZ_4 /
11311 /// VERT_4; the textured translating source is what keeps the strips
11312 /// non-skip so the residual is actually coded. 8-bit AND 10-bit, every
11313 /// decoded frame compared to ffmpeg on Y/U/V, refusals counted (never
11314 /// SKIPped), attempts that carried no rectangular var-tx leaf counted
11315 /// separately and still required pixel-exact.
11316 #[test]
11317 fn real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal() {
11318 const NAME: &str =
11319 "real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal";
11320 let _gate_lock = lock_gate_counters();
11321 if !have_ffmpeg() {
11322 eprintln!("SKIP {NAME}: no ffmpeg");
11323 return;
11324 }
11325 if !have_aomenc() {
11326 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11327 return;
11328 }
11329 let frame_count = 6usize;
11330 for bit_depth in [8u32, 10u32] {
11331 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
11332 (0u32, 0u32, 0u32, 0u32);
11333 let (mut leaf_32x16, mut leaf_16x32) = (0usize, 0usize);
11334 // Leaves decoded on ANY attempt, including one whose stream hits a
11335 // later named refusal: the firing half of this gate, kept apart
11336 // from `leaf_32x16`/`leaf_16x32` (pixel-compared attempts only) so
11337 // a refused stream is never counted as a pixel proof
11338 // (class counter-from-refused-stream).
11339 let (mut fired_32x16, mut fired_16x32) = (0usize, 0usize);
11340 // lane-gaterecipe r1: the firing arms (16-17) are 8-BIT ONLY, and
11341 // this is measured, not a convenience. Their 10-bit twin fires the
11342 // leaves too (32x16=0 16x32=46 on attempt 16) and then MISMATCHES
11343 // ffmpeg at decode-order frame 2 of attempt 17 -- an open DECODE
11344 // defect handed off in lanes/gaterecipe-r1.report.md, never
11345 // silenced inside this loop.
11346 let attempts = if bit_depth == 8 { 18u32 } else { 16u32 };
11347 for attempt in 0..attempts {
11348 // Two orientations (the transposed pair a one-sided gate could
11349 // never separate) x four quantisers x two motion steps.
11350 // lane-r14 r4 recipe hunt (~70 aomenc runs on the merged
11351 // tree: testsrc2 / life / mandelbrot / banded motion, 64x64 up
11352 // to 384x256, cq 20..58): attempts 16-17 carry the only recipe
11353 // found that makes aomenc code a 64-axis 1:4 strip whose
11354 // transform SPLITS -- 384x256, per-16-column band motion,
11355 // cq 32 (16x32 leaves) and cq 38 (32x16 leaves).
11356 let firing = attempt >= 16;
11357 let (width, height) =
11358 if firing { (384usize, 256usize) } else { (192usize, 128usize) };
11359 let vertical = attempt % 2 == 1;
11360 // lane-vartxsplit r2, MEASURED against the oracle
11361 // (`EC_VARTX` histogram, ~40 aomenc runs): at cq 10 this
11362 // source splits NO rectangular transform at all -- aomdec
11363 // reads only TX_8X8/TX_16X16/TX_8X16/TX_16X8 split symbols,
11364 // so the leaves gaterecipe r1 counted here came out of a
11365 // stream our decoder was already desynced on (class
11366 // counter-from-refused-stream). cq 44 and 46 are the two
11367 // quantisers of that sweep whose stream really carries
11368 // `TX_32X8`/`TX_8X32` splits (16x8 and 8x16 rectangular
11369 // var-tx leaves) AND decodes pixel-exact on all six frames.
11370 let cq = if firing {
11371 if attempt == 16 { 44 } else { 46 }
11372 } else {
11373 [30, 36, 44, 52][(attempt / 2 % 4) as usize]
11374 };
11375 let sp = 3 + (attempt / 8) * 3;
11376 // 16-pixel bands, each band translating at its OWN speed
11377 // across the other axis: that is what makes aomenc's RD split
11378 // a 64x64 superblock into four 1:4 strips (`PARTITION_HORZ_4`
11379 // / `VERT_4`) with distinct motion vectors, and the texture
11380 // inside a band is what keeps the strip non-skip and its
11381 // transform split.
11382 let geq = if firing && !vertical {
11383 // lane-gaterecipe r1, MEASURED: the banded translating
11384 // source this arm used until now splits NO transform at
11385 // all -- an aomdec EC_TRACE/EC_TRACE_COEFF histogram of its
11386 // stream reads zero 1:4 partitions and zero rectangular
11387 // sub-transforms, so the leaves the old assert counted came
11388 // out of a stream that stopped at a refusal (class
11389 // counter-from-refused-stream). What DOES split a
11390 // rectangular transform is a high-frequency product texture
11391 // at a fine quantiser with `--min-partition-size=8`: part
11392 // of the block predicts well and part does not, which is
11393 // the RD case for `txfm_partition`.
11394 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
11395 } else if firing {
11396 // lane-vartxsplit r2: BOTH leaf orientations come out of
11397 // this one source (three 16x8 leaves and one 8x16 on
11398 // attempt 16), so the firing pair is the same texture at
11399 // two quantisers. Its transposed twin was measured over
11400 // cq 40..56 and splits no rectangular transform at all;
11401 // at cq 56 it also mismatches ffmpeg from decode-order
11402 // frame 2 with ZERO rect var-tx leaves in it -- an open
11403 // reconstruction defect (8-pixel-wide luma column, see
11404 // lanes/vartxsplit-r2.report.md), not something to hide
11405 // inside this gate's attempt list.
11406 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
11407 } else if vertical {
11408 format!(
11409 "128+60*sin((Y+N*({sp}+9*mod(floor(X/16),2)))/7)+25*sin(X/11)"
11410 )
11411 } else {
11412 format!(
11413 "128+60*sin((X+N*({sp}+9*mod(floor(Y/16),2)))/7)+25*sin(Y/11)"
11414 )
11415 };
11416 let duration = frame_count as f64 / 25.0;
11417 let source = format!(
11418 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
11419 geq=lum='{geq}',format=yuv420p"
11420 );
11421 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
11422 let y4m = Command::new("ffmpeg")
11423 .args([
11424 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
11425 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
11426 ])
11427 .stdin(Stdio::null())
11428 .stdout(Stdio::piped())
11429 .stderr(Stdio::piped())
11430 .output()
11431 .expect("ffmpeg failed to run");
11432 assert!(
11433 y4m.status.success(),
11434 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
11435 String::from_utf8_lossy(&y4m.stderr)
11436 );
11437 let cq_arg = format!("--cq-level={cq}");
11438 let depth_arg = format!("--bit-depth={bit_depth}");
11439 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
11440 // A rectangular var-tx LEAF needs a block whose max rectangular
11441 // transform can split: `--min-partition-size=8` is what lets
11442 // aomenc's RD reach one (measured); at 16 it never did.
11443 let min_part =
11444 if firing { "--min-partition-size=8" } else { "--min-partition-size=16" };
11445 let args: Vec<&str> = vec![
11446 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
11447 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
11448 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
11449 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
11450 "--lag-in-frames=0",
11451 // Per-arm overrides go LAST: aomenc keeps the last
11452 // occurrence of a repeated --enable-* flag.
11453 "--enable-tx64=1", "--enable-rect-partitions=1",
11454 "--enable-ab-partitions=0", "--enable-1to4-partitions=1",
11455 "--enable-dual-filter=0", "--enable-obmc=0",
11456 "--enable-tx-size-search=1",
11457 min_part, "--max-partition-size=64",
11458 "--obu", "-o", "-", "-",
11459 ];
11460 let mut child = Command::new(aomenc_path())
11461 .args(&args)
11462 .stdin(Stdio::piped())
11463 .stdout(Stdio::piped())
11464 .stderr(Stdio::piped())
11465 .spawn()
11466 .expect("aomenc failed to start");
11467 // lane-gaterecipe r1: feed stdin from a THREAD. A
11468 // single-threaded `write_all` then `wait_with_output` deadlocks
11469 // the moment aomenc's stdout pipe fills before it has consumed
11470 // the whole y4m -- exactly what the fine-quantiser firing arm
11471 // does (one 384x256 cq-10 encode hung for 40 minutes).
11472 let mut aom_stdin = child.stdin.take().expect("aomenc stdin");
11473 let y4m_bytes = y4m.stdout;
11474 let feeder = std::thread::Builder::new()
11475 .name("ec-av1-aomenc-in".into())
11476 .spawn(move || {
11477 aom_stdin.write_all(&y4m_bytes).expect("writing y4m to aomenc");
11478 })
11479 .expect("spawning the aomenc stdin feeder");
11480 let out = child.wait_with_output().expect("aomenc failed to run");
11481 feeder.join().expect("y4m feeder thread");
11482 assert!(
11483 out.status.success(),
11484 "aomenc refused the fixture: {}",
11485 String::from_utf8_lossy(&out.stderr)
11486 );
11487 let stream = out.stdout;
11488 let before = crate::stream::vartx_rect_leaf_hits();
11489 let frames = match decode_stream(&stream) {
11490 Err(e) => {
11491 let msg = e.to_string();
11492 assert!(
11493 msg.contains("unsupported"),
11494 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
11495 attempt {attempt}): {msg}"
11496 );
11497 let after = crate::stream::vartx_rect_leaf_hits();
11498 fired_32x16 += after[0] - before[0];
11499 fired_16x32 += after[1] - before[1];
11500 named_refusals += 1;
11501 eprintln!(
11502 "{bit_depth}-bit attempt {attempt} refusal (rect var-tx leaves \
11503 decoded before it: 32x16={}, 16x32={}): {msg}",
11504 after[0] - before[0],
11505 after[1] - before[1]
11506 );
11507 continue;
11508 }
11509 Ok(frames) => frames,
11510 };
11511 let after = crate::stream::vartx_rect_leaf_hits();
11512 let (h32, v32) = (after[0] - before[0], after[1] - before[1]);
11513 fired_32x16 += h32;
11514 fired_16x32 += v32;
11515 let ffmpeg_frames = if bit_depth == 10 {
11516 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
11517 } else {
11518 ffmpeg_decode_sequence(&stream, width, height, frame_count)
11519 };
11520 assert_eq!(frames.len(), frame_count);
11521 let mismatched = frames
11522 .iter()
11523 .zip(&ffmpeg_frames)
11524 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
11525 if h32 + v32 == 0 {
11526 // Counted per ATTEMPT, on a decoded+compared attempt only
11527 // (class counter-from-refused-stream).
11528 out_of_scope += 1;
11529 if mismatched {
11530 oos_mismatch += 1;
11531 eprintln!(
11532 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
11533 rectangular var-tx leaves -- another shape's defect"
11534 );
11535 }
11536 continue;
11537 }
11538 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11539 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
11540 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
11541 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
11542 }
11543 leaf_32x16 += h32;
11544 leaf_16x32 += v32;
11545 compared += 1;
11546 }
11547 eprintln!(
11548 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
11549 pixel-exact attempts carrying the arm, pixel-compared rect var-tx leaves \
11550 32x16={leaf_32x16} 16x32={leaf_16x32}, leaves decoded anywhere in the sweep \
11551 32x16={fired_32x16} 16x32={fired_16x32}, {out_of_scope} attempts carried none \
11552 ({oos_mismatch} of them mismatched)"
11553 );
11554 assert_eq!(
11555 oos_mismatch, 0,
11556 "{NAME}: {oos_mismatch} attempt(s) with no rectangular var-tx leaf decoded \
11557 but mismatched ffmpeg -- a defect of another shape, not a pass"
11558 );
11559 assert!(
11560 compared + out_of_scope > 0,
11561 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
11562 );
11563 // The firing half. lane-vartxsplit r2 re-measured it against
11564 // the oracle: attempts 16/17 (384x256 product texture, cq 44/46,
11565 // `--min-partition-size=8 --enable-tx-size-search=1`) are the only
11566 // recipes of a ~40-run sweep whose stream carries `TX_32X8` /
11567 // `TX_8X32` split symbols, i.e. RECTANGULAR var-tx leaves (16x8
11568 // and 8x16, both orientations out of the same stream). They now
11569 // decode PIXEL-EXACT on all six frames, so the assert is on the
11570 // pixel-compared tally, not on the "decoded anywhere" one --
11571 // `fired_*` stays only to separate a refused stream's leaves from
11572 // a proved one (class counter-from-refused-stream). At 10 bits
11573 // the same sweep either fires nothing or mismatches on a
11574 // reconstruction defect of another shape (report), so the firing
11575 // assert stays 8-bit -- and it is a hard assert, never a print.
11576 if bit_depth == 8 {
11577 assert!(
11578 leaf_32x16 > 0 && leaf_16x32 > 0,
11579 "{NAME}: the rectangular var-tx leaf arm never fired on a pixel-exact \
11580 attempt (pixel-compared 32x16={leaf_32x16}, 16x32={leaf_16x32}, decoded \
11581 anywhere 32x16={fired_32x16} 16x32={fired_16x32}, {named_refusals} \
11582 refusals, {compared} compared) -- the rectangular sub-transform path is \
11583 unproved by this gate"
11584 );
11585 }
11586 }
11587 }
11588
11589 /// lane-rectres r1: a 32x32-level 1:4 INTER strip (32x8 / 8x32) that codes
11590 /// a REAL rectangular residual. THIS is the shape both 10-bit 3840x1608
11591 /// film cuts and every measured 1080p offset stopped on -- six of six
11592 /// `decode_probe` runs refused at "a non-skip rectangular (HORZ/VERT/
11593 /// HORZ_B) strip needs rectangular residual coding" with `w=32 h=8` or
11594 /// `w=8 h=32`, nothing else.
11595 ///
11596 /// `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256 of its
11597 /// positions ([`TxbSet::LumaRect32x8Inter`]: `get_txsize_entropy_ctx` =
11598 /// TX_16X16 so the coefficient tables are the luma-16 ones,
11599 /// `txsize_log2_minus4` = 4 so `eob_pt` is the 256-position alphabet), and
11600 /// unlike the INTRA twin it DOES code a `tx_type`:
11601 /// `av1_get_ext_tx_set_type` at `tx_size_sqr_up == TX_32X32` is
11602 /// `EXT_TX_SET_DCT_IDTX` for inter with or without `reduced_tx_set`, read
11603 /// at the `txsize_sqr_map[TX_32X8] == TX_8X8` CDF row (class
11604 /// table-indexed-by-raw-size: the coefficient tables follow the ADJUSTED
11605 /// size, the `tx_type` row the SQUARE one -- they disagree here).
11606 /// Its chroma pair is one 16x4 / 4x16 unit (`ss_size_lookup[BLOCK_32X8]`
11607 /// = BLOCK_16X4, `Chroma8`'s tables, 64-position `eob_pt`), and a split
11608 /// transform gives 16x8 / 8x16 leaves (`sub_tx_size_map[TX_32X8] ==
11609 /// TX_16X8`) the rect var-tx path already reads.
11610 ///
11611 /// `--enable-1to4-partitions=1 --min-partition-size=8
11612 /// --max-partition-size=32 --enable-tx-size-search=1` (each spelled once,
11613 /// last occurrence wins -- aomenc keeps the LAST `--enable-*`) is what
11614 /// lets aomenc pick a 32x32-level HORZ_4 / VERT_4; the 8-pixel banded
11615 /// translating source is what makes those strips the RD winner and keeps
11616 /// them non-skip so the residual is really coded. Both orientations, 8-bit
11617 /// AND 10-bit, every decode-order frame compared to ffmpeg on Y/U/V,
11618 /// refusals counted (never SKIPped), attempts that carried no 32x8/8x32
11619 /// residual unit counted separately and still required pixel-exact.
11620 #[test]
11621 fn a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual() {
11622 const NAME: &str =
11623 "a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual";
11624 let _gate_lock = lock_gate_counters();
11625 if !have_ffmpeg() {
11626 eprintln!("SKIP {NAME}: no ffmpeg");
11627 return;
11628 }
11629 if !have_aomenc() {
11630 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11631 return;
11632 }
11633 let frame_count = 6usize;
11634 let (mut proved_32x8, mut proved_8x32) = (0usize, 0usize);
11635 let (mut fired_32x8, mut fired_8x32) = (0usize, 0usize);
11636 for bit_depth in [8u32, 10u32] {
11637 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
11638 (0u32, 0u32, 0u32, 0u32);
11639 for attempt in 0..16u32 {
11640 // Two orientations (the transposed pair a one-sided gate could
11641 // never separate) x four quantisers x two motion steps.
11642 let vertical = attempt % 2 == 1;
11643 let (width, height) = (192usize, 128usize);
11644 let cq = [48, 52, 56, 60][(attempt / 2 % 4) as usize];
11645 let sp = 3 + (attempt / 8) * 4;
11646 // 32-pixel bands, each translating at its OWN speed across the
11647 // other axis: that is what makes aomenc's RD split a 32x32
11648 // block into four 32x8 (or 8x32) strips with distinct motion
11649 // vectors, and the texture inside a band is what keeps a strip
11650 // non-skip. MEASURED (72-run recipe sweep, 192x128..256x192,
11651 // cq 24..60, bands 8/16/32/64): only 32-pixel bands at cq >= 48
11652 // make aomenc code a NON-SKIP one -- attempt 0 (cq 48,
11653 // horizontal source) codes an 8x32 residual unit, attempt 7
11654 // (cq 60, the transposed source) five 32x8 ones. Narrower
11655 // bands give the same strips with `skip` set, which proves the
11656 // partition symbol and nothing about the residual.
11657 let geq = if vertical {
11658 format!("128+62*sin((Y+N*({sp}+7*mod(floor(X/32),4)))/6)+28*sin(X/9)")
11659 } else {
11660 format!("128+62*sin((X+N*({sp}+7*mod(floor(Y/32),4)))/6)+28*sin(Y/9)")
11661 };
11662 let duration = frame_count as f64 / 25.0;
11663 let source = format!(
11664 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
11665 geq=lum='{geq}',format=yuv420p"
11666 );
11667 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
11668 let y4m = Command::new("ffmpeg")
11669 .args([
11670 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
11671 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
11672 ])
11673 .stdin(Stdio::null())
11674 .stdout(Stdio::piped())
11675 .stderr(Stdio::piped())
11676 .output()
11677 .expect("ffmpeg failed to run");
11678 assert!(
11679 y4m.status.success(),
11680 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
11681 String::from_utf8_lossy(&y4m.stderr)
11682 );
11683 let cq_arg = format!("--cq-level={cq}");
11684 let depth_arg = format!("--bit-depth={bit_depth}");
11685 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
11686 let args: Vec<&str> = vec![
11687 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
11688 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
11689 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
11690 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
11691 "--lag-in-frames=0",
11692 // Per-arm overrides go LAST: aomenc keeps the last
11693 // occurrence of a repeated --enable-* flag.
11694 "--enable-tx64=0", "--enable-rect-partitions=1",
11695 "--enable-ab-partitions=0", "--enable-1to4-partitions=1",
11696 "--enable-tx-size-search=1",
11697 "--enable-dual-filter=0", "--enable-obmc=0",
11698 // aomenc's min-partition-size bounds the SMALLER side of a
11699 // 1:4 strip, so 32x8 needs 8 (memory
11700 // aomenc-min-partition-bounds-smaller-side).
11701 "--min-partition-size=8", "--max-partition-size=32",
11702 "--obu", "-o", "-", "-",
11703 ];
11704 let mut child = Command::new(aomenc_path())
11705 .args(&args)
11706 .stdin(Stdio::piped())
11707 .stdout(Stdio::piped())
11708 .stderr(Stdio::piped())
11709 .spawn()
11710 .expect("aomenc failed to start");
11711 child
11712 .stdin
11713 .take()
11714 .expect("aomenc stdin")
11715 .write_all(&y4m.stdout)
11716 .expect("writing y4m to aomenc");
11717 let out = child.wait_with_output().expect("aomenc failed to run");
11718 assert!(
11719 out.status.success(),
11720 "aomenc refused the fixture: {}",
11721 String::from_utf8_lossy(&out.stderr)
11722 );
11723 let stream = out.stdout;
11724 let before = crate::stream::rect32x8_inter_tu_hits();
11725 let frames = match decode_stream(&stream) {
11726 Err(e) => {
11727 let msg = e.to_string();
11728 assert!(
11729 msg.contains("unsupported"),
11730 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
11731 attempt {attempt}): {msg}"
11732 );
11733 let after = crate::stream::rect32x8_inter_tu_hits();
11734 // Firing counted on a refused stream is kept apart from
11735 // the pixel-proved tally (class
11736 // counter-from-refused-stream).
11737 fired_32x8 += after[0] - before[0];
11738 fired_8x32 += after[1] - before[1];
11739 named_refusals += 1;
11740 eprintln!(
11741 "{NAME} {bit_depth}-bit attempt {attempt} refusal (32x8 residual \
11742 units decoded before it: {}, 8x32: {}): {msg}",
11743 after[0] - before[0],
11744 after[1] - before[1]
11745 );
11746 continue;
11747 }
11748 Ok(frames) => frames,
11749 };
11750 let after = crate::stream::rect32x8_inter_tu_hits();
11751 let (h, v) = (after[0] - before[0], after[1] - before[1]);
11752 fired_32x8 += h;
11753 fired_8x32 += v;
11754 let ffmpeg_frames = if bit_depth == 10 {
11755 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
11756 } else {
11757 ffmpeg_decode_sequence(&stream, width, height, frame_count)
11758 };
11759 assert_eq!(frames.len(), frame_count);
11760 let mismatched = frames
11761 .iter()
11762 .zip(&ffmpeg_frames)
11763 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
11764 if h + v == 0 {
11765 out_of_scope += 1;
11766 if mismatched {
11767 oos_mismatch += 1;
11768 eprintln!(
11769 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
11770 32x8/8x32 inter residual units -- another shape's defect"
11771 );
11772 }
11773 continue;
11774 }
11775 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11776 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
11777 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
11778 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
11779 }
11780 proved_32x8 += h;
11781 proved_8x32 += v;
11782 compared += 1;
11783 }
11784 eprintln!(
11785 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
11786 pixel-exact attempts carrying the arm, {out_of_scope} attempts carried none \
11787 ({oos_mismatch} of them mismatched)"
11788 );
11789 assert_eq!(
11790 oos_mismatch, 0,
11791 "{NAME}: {oos_mismatch} attempt(s) with no 32x8/8x32 inter residual unit \
11792 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
11793 );
11794 assert!(
11795 compared + out_of_scope > 0,
11796 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
11797 );
11798 }
11799 eprintln!(
11800 "{NAME}: pixel-compared 32x32-level 1:4 inter residual units 32x8={proved_32x8} \
11801 8x32={proved_8x32} (decoded anywhere in the sweep 32x8={fired_32x8} \
11802 8x32={fired_8x32})"
11803 );
11804 // The firing half, one assert per lifted shape. Both orientations must
11805 // be PIXEL-PROVED: a transposed table passes one and fails the other
11806 // (class reference-layout-not-spec).
11807 assert!(
11808 proved_32x8 > 0,
11809 "{NAME}: no 32x8 inter residual transform unit was decoded inside a pixel-exact \
11810 attempt (decoded anywhere: {fired_32x8}) -- the lift is unproved"
11811 );
11812 assert!(
11813 proved_8x32 > 0,
11814 "{NAME}: no 8x32 inter residual transform unit was decoded inside a pixel-exact \
11815 attempt (decoded anywhere: {fired_8x32}) -- the lift is unproved"
11816 );
11817 }
11818
11819 /// lane-sbrect10 r1: a 64x64 INTRA block inside an INTER frame, whose
11820 /// `uv_mode` alphabet libaom's `is_cfl_allowed` (`blockd.h`: `wide <= 32
11821 /// && high <= 32`) narrows to the 13-symbol NO-CFL table. Reading the
11822 /// 14-symbol CFL one produced the same `DC_PRED` value with the wrong
11823 /// interval narrowing, so the tile desynced from that block on and the
11824 /// frame decoded silently wrong (class `wrong-alphabet-same-value`; found
11825 /// as the "another shape" mismatch the superblock rect gate above had to
11826 /// park its 10-bit arm on).
11827 ///
11828 /// The counter `nocfl_uv_mode_hits` proves the shape fired in EVERY
11829 /// compared attempt, and every decode-order frame is compared against
11830 /// ffmpeg -- an attempt that mismatches fails, it never SKIPs.
11831 ///
11832 /// lane-sbrect10 r2: with the half-random source below this gate also
11833 /// covers a SECOND defect it exposed at 10-bit cq 58/61 -- the compound
11834 /// MV stack's extension pass zero-filled the `comp_list` tail slots
11835 /// libaom fills with each side's GLOBAL MOTION vector
11836 /// (`combine_compound_candidates`, mvref_common.c:723-729). A compound
11837 /// block with no usable neighbour pair (frame top row, intra block to
11838 /// its left, empty temporal field) then took a `(0, 0)` predictor
11839 /// instead of the frame's translation: 32890/39907 wrong luma samples
11840 /// on decode-order frame 2 with the entropy stream still in sync.
11841 #[test]
11842 fn a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet() {
11843 const NAME: &str =
11844 "a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet";
11845 let _gate_lock = lock_gate_counters();
11846 if !have_ffmpeg() {
11847 eprintln!("SKIP {NAME}: no ffmpeg");
11848 return;
11849 }
11850 if !have_aomenc() {
11851 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11852 return;
11853 }
11854 let (width, height, frame_count) = (192usize, 128usize, 6usize);
11855 for bit_depth in [8u32, 10u32] {
11856 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
11857 let mut total_hits = 0usize;
11858 for attempt in 0..16u32 {
11859 // The sibling superblock-rect gate's own grid (its 10-bit
11860 // attempt 14 -- cq 61, horizontal split, motion step 12 -- is
11861 // the stream that exposed the defect); which superblock the RD
11862 // hands an intra 64x64 block moves with the quantiser and the
11863 // depth, so both orientations x four quantisers x two motion
11864 // steps run here too.
11865 let vertical_split = attempt % 2 == 1;
11866 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
11867 let sp = 8 + (attempt / 8) * 4;
11868 // Half ramp, half deterministic pseudo-noise: the flat "200"
11869 // half of r1's source made aomenc code the right-hand
11870 // superblocks skip, so at 8 bit no >32 intra block ever
11871 // appeared (probed cq 45/52/58/61/63 = 0 hits). The textured
11872 // half forces intra above 32x32 in an inter frame at BOTH
11873 // depths, so both arms carry the shape.
11874 let geq = if vertical_split {
11875 format!(
11876 "if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
11877 )
11878 } else {
11879 format!(
11880 "if(lt(X,128), 40+mod(floor((Y+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
11881 )
11882 };
11883 let duration = frame_count as f64 / 25.0;
11884 let source = format!(
11885 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
11886 geq=lum='{geq}',format=yuv420p"
11887 );
11888 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
11889 let y4m = Command::new("ffmpeg")
11890 .args([
11891 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
11892 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
11893 ])
11894 .stdin(Stdio::null())
11895 .stdout(Stdio::piped())
11896 .stderr(Stdio::piped())
11897 .output()
11898 .expect("ffmpeg failed to run");
11899 assert!(
11900 y4m.status.success(),
11901 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
11902 String::from_utf8_lossy(&y4m.stderr)
11903 );
11904 let cq_arg = format!("--cq-level={cq}");
11905 let depth_arg = format!("--bit-depth={bit_depth}");
11906 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
11907 let args: Vec<&str> = vec![
11908 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
11909 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
11910 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
11911 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
11912 "--enable-tx-size-search=0", "--lag-in-frames=0",
11913 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
11914 "--enable-1to4-partitions=1", "--min-partition-size=32",
11915 "--max-partition-size=64",
11916 "--obu", "-o", "-", "-",
11917 ];
11918 let mut child = Command::new(aomenc_path())
11919 .args(&args)
11920 .stdin(Stdio::piped())
11921 .stdout(Stdio::piped())
11922 .stderr(Stdio::piped())
11923 .spawn()
11924 .expect("aomenc failed to start");
11925 child
11926 .stdin
11927 .take()
11928 .expect("aomenc stdin")
11929 .write_all(&y4m.stdout)
11930 .expect("writing y4m to aomenc");
11931 let out = child.wait_with_output().expect("aomenc failed to run");
11932 assert!(
11933 out.status.success(),
11934 "aomenc refused the fixture: {}",
11935 String::from_utf8_lossy(&out.stderr)
11936 );
11937 let stream = out.stdout;
11938 let before = crate::decode::nocfl_uv_mode_hits();
11939 let frames = match decode_stream(&stream) {
11940 Err(e) => {
11941 let msg = e.to_string();
11942 assert!(
11943 msg.contains("unsupported"),
11944 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
11945 attempt {attempt}): {msg}"
11946 );
11947 named_refusals += 1;
11948 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
11949 continue;
11950 }
11951 Ok(frames) => frames,
11952 };
11953 let hits = crate::decode::nocfl_uv_mode_hits() - before;
11954 let ffmpeg_frames = if bit_depth == 10 {
11955 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
11956 } else {
11957 ffmpeg_decode_sequence(&stream, width, height, frame_count)
11958 };
11959 assert_eq!(frames.len(), frame_count);
11960 if hits == 0 {
11961 // No 64-axis intra block in this stream: still compared
11962 // (a mismatch here is a defect, never a pass), just not
11963 // proof of this gate's shape.
11964 carried_none += 1;
11965 }
11966 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11967 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
11968 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
11969 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
11970 }
11971 if hits > 0 {
11972 matched += 1;
11973 total_hits += hits;
11974 }
11975 }
11976 eprintln!(
11977 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
11978 attempts carrying a >32 intra block ({total_hits} no-CFL uv_mode reads), \
11979 {carried_none} attempts carried none"
11980 );
11981 assert!(
11982 matched > 0 && total_hits > 0,
11983 "{NAME} ({bit_depth}-bit): no attempt decoded an intra block above 32x32, so the \
11984 no-CFL uv_mode alphabet was never exercised -- gate proved nothing \
11985 ({named_refusals} refusals, {carried_none} attempts carried none)"
11986 );
11987 }
11988 }
11989 /// lane-sqdrift r2: the SQUARE-ONLY twin of the no-CFL `uv_mode` gate
11990 /// above. With `--enable-rect-partitions=0` the encoder codes only
11991 /// `PARTITION_NONE` and `PARTITION_SPLIT`, and on detailed content the RD
11992 /// eventually hands one whole 64x64 superblock of an INTER frame to an
11993 /// INTRA block -- `bsize == sb_size`, the one shape whose `uv_mode` must
11994 /// come off the 13-symbol `uv_mode_no_cfl` alphabet because libaom's
11995 /// `is_cfl_allowed` (`blockd.h`: `wide <= 32 && high <= 32`) excludes it.
11996 ///
11997 /// Before the fix this decoder read the 14-symbol CFL alphabet there: the
11998 /// same `DC_PRED` value, a different interval, and the tile desynced from
11999 /// that block on. r1 measured the damage on the pinned 192x128 stream
12000 /// (sha256 `c6af4fb4...`): decode-order frames 0-3 pre-filter byte-exact,
12001 /// frame 4 luma 3540 samples wrong over exactly the last superblock
12002 /// (x 128..191, y 64..127), then 24k wrong by frame 7 -- and the decoder
12003 /// did not even report a mismatch, it reported an intra-rect-strip refusal
12004 /// read out of the already-desynced stream (class `refusal-from-own-desync`;
12005 /// aomdec's own partition histogram over that stream is rect-free).
12006 /// After the fix the same stream is byte-exact on all 8 frames.
12007 ///
12008 /// Distinct from the sibling gate: rect partitions OFF (so the 64x64 NONE
12009 /// really is a whole superblock), `--min-partition-size=16`, natural
12010 /// mandelbrot detail instead of a synthetic half-noise ramp, and 8 frames
12011 /// of drift so a desync that survives one frame still fails here. Every
12012 /// decode-order frame of every attempt is compared against ffmpeg, so a
12013 /// mismatch of ANY shape fails; the gate never turns one into a SKIP.
12014 #[test]
12015 fn a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact()
12016 {
12017 const NAME: &str = "a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact";
12018 let _gate_lock = lock_gate_counters();
12019 if !have_ffmpeg() {
12020 eprintln!("SKIP {NAME}: no ffmpeg");
12021 return;
12022 }
12023 if !have_aomenc() {
12024 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12025 return;
12026 }
12027 let (width, height, frame_count) = (192usize, 128usize, 8usize);
12028 for bit_depth in [8u32, 10u32] {
12029 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
12030 let mut total_hits = 0usize;
12031 for attempt in 0..4u32 {
12032 // r1's pinned recipe is (start_scale 4.76, cq 55); the other
12033 // three points move the detail level and the quantiser, which
12034 // is what moves WHICH superblock the RD codes intra.
12035 let start_scale = ["4.76", "3.20"][(attempt % 2) as usize];
12036 let cq = [55, 45][(attempt / 2) as usize];
12037 let duration = frame_count as f64 / 25.0;
12038 let source = format!(
12039 "mandelbrot=size={width}x{height}:start_scale={start_scale}:\
12040 end_scale=0.004:end_pts=8:rate=25"
12041 );
12042 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12043 let y4m = Command::new("ffmpeg")
12044 .args([
12045 "-v", "error", "-f", "lavfi", "-i", &source, "-vf", "hue=s=0",
12046 "-t", &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
12047 "-f", "yuv4mpegpipe", "-strict", "-1", "-",
12048 ])
12049 .stdin(Stdio::null())
12050 .stdout(Stdio::piped())
12051 .stderr(Stdio::piped())
12052 .output()
12053 .expect("ffmpeg failed to run");
12054 assert!(
12055 y4m.status.success(),
12056 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
12057 String::from_utf8_lossy(&y4m.stderr)
12058 );
12059 let cq_arg = format!("--cq-level={cq}");
12060 let depth_arg = format!("--bit-depth={bit_depth}");
12061 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
12062 let args: Vec<&str> = vec![
12063 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=1",
12064 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
12065 "--lag-in-frames=0", "--auto-alt-ref=0",
12066 "--kf-min-dist=1000", "--kf-max-dist=1000",
12067 "--enable-rect-partitions=0", "--enable-ab-partitions=0",
12068 "--enable-1to4-partitions=0", "--min-partition-size=16",
12069 "--max-partition-size=64", "--enable-tx-size-search=0",
12070 "--enable-order-hint=0", "--enable-warped-motion=0", "--enable-obmc=0",
12071 "--enable-masked-comp=0", "--enable-interintra-comp=0",
12072 "--enable-dist-wtd-comp=0", "--enable-diff-wtd-comp=0",
12073 "--enable-onesided-comp=0", "--enable-interintra-wedge=0",
12074 "--enable-smooth-interintra=0", "--enable-filter-intra=0",
12075 "--enable-smooth-intra=0", "--enable-paeth-intra=0",
12076 "--enable-directional-intra=0", "--enable-angle-delta=0",
12077 "--enable-cdef=0", "--enable-restoration=0", "--enable-palette=0",
12078 "--enable-intrabc=0", "--enable-cfl-intra=0", "--enable-ref-frame-mvs=0",
12079 "--obu", "-o", "-", "-",
12080 ];
12081 let mut child = Command::new(aomenc_path())
12082 .args(&args)
12083 .stdin(Stdio::piped())
12084 .stdout(Stdio::piped())
12085 .stderr(Stdio::piped())
12086 .spawn()
12087 .expect("aomenc failed to start");
12088 child
12089 .stdin
12090 .take()
12091 .expect("aomenc stdin")
12092 .write_all(&y4m.stdout)
12093 .expect("writing y4m to aomenc");
12094 let out = child.wait_with_output().expect("aomenc failed to run");
12095 assert!(
12096 out.status.success(),
12097 "aomenc refused the fixture: {}",
12098 String::from_utf8_lossy(&out.stderr)
12099 );
12100 let stream = out.stdout;
12101 let before = crate::decode::nocfl_uv_mode_hits();
12102 let frames = match decode_stream(&stream) {
12103 Err(e) => {
12104 let msg = e.to_string();
12105 assert!(
12106 msg.contains("unsupported"),
12107 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
12108 attempt {attempt}): {msg}"
12109 );
12110 named_refusals += 1;
12111 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
12112 continue;
12113 }
12114 Ok(frames) => frames,
12115 };
12116 let hits = crate::decode::nocfl_uv_mode_hits() - before;
12117 let ffmpeg_frames = if bit_depth == 10 {
12118 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12119 } else {
12120 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12121 };
12122 assert_eq!(frames.len(), frame_count);
12123 if hits == 0 {
12124 carried_none += 1;
12125 }
12126 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12127 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
12128 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
12129 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
12130 }
12131 if hits > 0 {
12132 matched += 1;
12133 total_hits += hits;
12134 }
12135 }
12136 eprintln!(
12137 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
12138 attempts carrying a 64x64 intra superblock ({total_hits} no-CFL uv_mode reads), \
12139 {carried_none} attempts carried none"
12140 );
12141 assert!(
12142 matched > 0 && total_hits > 0,
12143 "{NAME} ({bit_depth}-bit): no square-only attempt decoded a 64x64 intra block \
12144 inside an inter frame, so the no-CFL uv_mode alphabet was never exercised -- \
12145 gate proved nothing ({named_refusals} refusals, {carried_none} carried none)"
12146 );
12147 }
12148 }
12149
12150 /// lane-mc64 r2: the RECT-ON twin of the square-only gate above, pinned
12151 /// as a stream fixture because its aomenc recipe is not reproducible
12152 /// (the r2 recipe re-encoded to a different file, measured md5
12153 /// `278be00...` vs the fixture's `add55f6...`; class
12154 /// `seeded-fixture-not-reproducible`).
12155 ///
12156 /// `crates/ec-av1/fixtures/av1_192x128_8bit_intra64_in_inter.obu`
12157 /// (sha256 `e4cff46cb1700527c68efc866db27a2835705e949d646f73f0c9df577d594bd6`)
12158 /// carries a 64x64 `PARTITION_NONE` INTRA block inside an INTER frame at
12159 /// decode-order frame 2, mi(16,32), in a stream whose OTHER superblocks
12160 /// are rect-partitioned -- so the 64-axis `is_cfl_allowed` narrowing
12161 /// (`blockd.h`: `wide <= 32 && high <= 32`) has to hold on the intra
12162 /// arm that the rect recipe reaches, not only on the whole-superblock
12163 /// one. Before lane-sbrect10's fix this frame reconstructed with 3720
12164 /// wrong luma samples (delta -12..+9, chroma bit-exact) and the decode
12165 /// then died at frame 3 on a phantom refusal of its own desync (class
12166 /// `refusal-from-own-desync`); all 6 decode-order frames are byte-exact
12167 /// against the oracle now.
12168 #[test]
12169 fn a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact() {
12170 const NAME: &str =
12171 "a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact";
12172 let _gate_lock = lock_gate_counters();
12173 if !have_aomenc() {
12174 eprintln!("SKIP {NAME}: no aomenc/aomdec oracle at {}", aomenc_path().display());
12175 return;
12176 }
12177 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12178 .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu");
12179 let stream = std::fs::read(&path)
12180 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
12181 let before = crate::decode::nocfl_uv_mode_hits();
12182 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
12183 let hits = crate::decode::nocfl_uv_mode_hits() - before;
12184 assert_eq!(frames, 6, "{NAME}: expected 6 decode-order frames ({hidden} hidden)");
12185 assert!(
12186 hits > 0,
12187 "{NAME}: no 64-axis intra block read the no-CFL uv_mode alphabet -- the fixture no \
12188 longer carries the shape this test gates"
12189 );
12190 }
12191
12192 /// lane-inter4 r2: the 32x32-level inter `PARTITION_HORZ`/`PARTITION_VERT`
12193 /// strips (32x16 / 16x32) carrying a REAL residual -- the capability r1
12194 /// found missing ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs
12195 /// rectangular residual coding"). The strip's own rectangular max
12196 /// transform (`TX_32X16`/`TX_16X32`) is read through the rect var-tx tree,
12197 /// its coefficients through [`TxbSet::LumaRect32x16Inter`] /
12198 /// `ChromaRect16x8`, and inverted with the rect (sqrt2-scaled) inverse
12199 /// transform.
12200 ///
12201 /// `--min-partition-size=16 --max-partition-size=32` keeps the superblock
12202 /// level (64x32, still refused -- no 64-point rect transform) out, so
12203 /// every counted hit is a 32-level strip. The source is textured and
12204 /// translating precisely so the strips are NOT skip: a flat source (r1's)
12205 /// makes aomenc code them skip and proves nothing about the residual.
12206 /// Both `--enable-tx-size-search` arms run: `=0` exercises the
12207 /// whole-block rect transform with no `txfm_partition` symbol at all,
12208 /// `=1` the rect var-tx tree (no-split rect unit, or the split into square
12209 /// sub-transforms).
12210 ///
12211 /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and
12212 /// V; a refusal is counted, never SKIPped; an attempt that carried no rect
12213 /// inter residual is counted separately and still required pixel-exact.
12214 /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream
12215 /// whose compound blocks feed the next frame's motion field
12216 /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`).
12217 ///
12218 /// lane-interbis r1 pinned this recipe because it is the one the rect
12219 /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a
12220 /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its
12221 /// nearest candidate from a temporal cell holding the wrong reference:
12222 /// `build_motion_field` stored a compound block's FIRST reference where
12223 /// libaom stores its second). Every fully decoded attempt is compared
12224 /// plane by plane; a refusal is counted, never SKIPped; the temporal
12225 /// candidate counter must fire on a compared attempt, or the gate proves
12226 /// nothing.
12227 #[test]
12228 fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() {
12229 const NAME: &str =
12230 "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact";
12231 let _gate_lock = lock_gate_counters();
12232 if !have_ffmpeg() {
12233 eprintln!("SKIP {NAME}: no ffmpeg");
12234 return;
12235 }
12236 if !have_aomenc() {
12237 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12238 return;
12239 }
12240 let (width, height, frame_count) = (192usize, 128usize, 6usize);
12241 for bit_depth in [8u32, 10u32] {
12242 let (mut named_refusals, mut compared, mut tmv_proved) = (0u32, 0u32, 0usize);
12243 for attempt in 0..2u32 {
12244 let tx_search = if attempt == 0 { "0" } else { "1" };
12245 let duration = frame_count as f64 / 25.0;
12246 // The pinned source: horizontal structure translating along X
12247 // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN
12248 // blocks whose stored motion field the last frame reads back.
12249 let source = format!(
12250 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
12251 geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',format=yuv420p"
12252 );
12253 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12254 let y4m = Command::new("ffmpeg")
12255 .args([
12256 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
12257 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
12258 ])
12259 .stdin(Stdio::null())
12260 .stdout(Stdio::piped())
12261 .stderr(Stdio::piped())
12262 .output()
12263 .expect("ffmpeg failed to run");
12264 assert!(
12265 y4m.status.success(),
12266 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
12267 String::from_utf8_lossy(&y4m.stderr)
12268 );
12269 let depth_arg = format!("--bit-depth={bit_depth}");
12270 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
12271 let tx_arg = format!("--enable-tx-size-search={tx_search}");
12272 let args: Vec<&str> = vec![
12273 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=34", "--cpu-used=0",
12274 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
12275 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
12276 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
12277 "--lag-in-frames=0",
12278 // Per-arm overrides go LAST (aomenc keeps the last
12279 // occurrence of a repeated --enable-* flag).
12280 &tx_arg,
12281 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
12282 "--enable-1to4-partitions=0", "--min-partition-size=16",
12283 "--max-partition-size=32",
12284 "--obu", "-o", "-", "-",
12285 ];
12286 let mut child = Command::new(aomenc_path())
12287 .args(&args)
12288 .stdin(Stdio::piped())
12289 .stdout(Stdio::piped())
12290 .stderr(Stdio::piped())
12291 .spawn()
12292 .expect("aomenc failed to start");
12293 child
12294 .stdin
12295 .take()
12296 .expect("aomenc stdin")
12297 .write_all(&y4m.stdout)
12298 .expect("writing y4m to aomenc");
12299 let out = child.wait_with_output().expect("aomenc failed to run");
12300 assert!(
12301 out.status.success(),
12302 "aomenc refused the fixture: {}",
12303 String::from_utf8_lossy(&out.stderr)
12304 );
12305 let stream = out.stdout;
12306 let before = decode::tmv_hits();
12307 let frames = match decode_stream(&stream) {
12308 Err(e) => {
12309 let msg = e.to_string();
12310 assert!(
12311 msg.contains("unsupported"),
12312 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
12313 attempt {attempt}): {msg}"
12314 );
12315 named_refusals += 1;
12316 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
12317 continue;
12318 }
12319 Ok(frames) => frames,
12320 };
12321 let tmv = decode::tmv_hits() - before;
12322 let ffmpeg_frames = if bit_depth == 10 {
12323 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12324 } else {
12325 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12326 };
12327 assert_eq!(frames.len(), frame_count);
12328 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12329 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12330 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12331 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12332 }
12333 compared += 1;
12334 tmv_proved += tmv;
12335 }
12336 eprintln!(
12337 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
12338 pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}"
12339 );
12340 assert!(
12341 compared > 0,
12342 "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing"
12343 );
12344 assert!(
12345 tmv_proved > 0,
12346 "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \
12347 candidate into a block's stack -- gate proved nothing"
12348 );
12349 }
12350 }
12351
12352 /// lane-refstamp r1: `av1_setup_motion_field`'s `ref_stamp` budget in the
12353 /// presence of FORWARD KEY FRAMES (`--enable-fwd-kf=1`), which is the only
12354 /// configuration where a *forward* reference slot (BWDREF/ALTREF2/ALTREF)
12355 /// holds a key frame while temporal MV projection runs. libaom's
12356 /// `motion_field_projection` returns 0 for such a start frame, so it costs
12357 /// no `ref_stamp`; ours used to project the (empty) field and report
12358 /// success, spending the slot ALTREF/LAST2 should have had and losing
12359 /// their temporal candidates.
12360 ///
12361 /// Both bit depths; EVERY decoded frame (including the hidden alt-refs)
12362 /// compared to the oracle in decode order; a refusal is counted, never
12363 /// SKIPped. Two hard counters make the gate non-vacuous: frames that
12364 /// actually took the >=2-intra-forward-refs `ref_stamp` path, and blocks
12365 /// that folded a temporal MV candidate into their stack.
12366 #[test]
12367 fn a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact() {
12368 const NAME: &str = "a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact";
12369 let _gate_lock = lock_gate_counters();
12370 if !have_ffmpeg() {
12371 eprintln!("SKIP {NAME}: no ffmpeg");
12372 return;
12373 }
12374 if !have_aomenc() {
12375 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12376 return;
12377 }
12378 let (width, height, frame_count) = (192usize, 128usize, 24usize);
12379 for bit_depth in [8u32, 10u32] {
12380 let (mut named_refusals, mut compared, mut tmv_proved, mut stamp_proved) =
12381 (0u32, 0u32, 0usize, 0usize);
12382 let mut stamp2_proved = 0usize;
12383 for attempt in 0..2u32 {
12384 let duration = frame_count as f64 / 25.0;
12385 // Natural-ish motion: structure translating along X at 3 px per
12386 // frame plus a slow vertical drift, the source family the
12387 // temporal-MV gate already decodes fully.
12388 let source = format!(
12389 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
12390 geq=lum='128+58*sin((X+N*3)/6)+18*sin((Y+N*2)/23)',format=yuv420p"
12391 );
12392 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12393 let y4m = Command::new("ffmpeg")
12394 .args([
12395 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
12396 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
12397 ])
12398 .stdin(Stdio::null())
12399 .stdout(Stdio::piped())
12400 .stderr(Stdio::piped())
12401 .output()
12402 .expect("ffmpeg failed to run");
12403 assert!(
12404 y4m.status.success(),
12405 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
12406 String::from_utf8_lossy(&y4m.stderr)
12407 );
12408 let depth_arg = format!("--bit-depth={bit_depth}");
12409 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
12410 let cq_arg = format!("--cq-level={}", if attempt == 0 { 34 } else { 45 });
12411 let args: Vec<&str> = vec![
12412 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
12413 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
12414 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
12415 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
12416 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
12417 "--enable-1to4-partitions=0", "--min-partition-size=16",
12418 "--max-partition-size=32",
12419 // Per-arm/feature overrides go LAST (aomenc keeps the LAST
12420 // occurrence of a repeated --enable-* flag).
12421 "--enable-order-hint=1", "--enable-ref-frame-mvs=1",
12422 "--enable-fwd-kf=1", "--fwd-kf-dist=8", "--kf-max-dist=1000",
12423 "--lag-in-frames=16", "--auto-alt-ref=1", "--arnr-maxframes=0",
12424 "--obu", "-o", "-", "-",
12425 ];
12426 let mut child = Command::new(aomenc_path())
12427 .args(&args)
12428 .stdin(Stdio::piped())
12429 .stdout(Stdio::piped())
12430 .stderr(Stdio::piped())
12431 .spawn()
12432 .expect("aomenc failed to start");
12433 child
12434 .stdin
12435 .take()
12436 .expect("aomenc stdin")
12437 .write_all(&y4m.stdout)
12438 .expect("writing y4m to aomenc");
12439 let out = child.wait_with_output().expect("aomenc failed to run");
12440 assert!(
12441 out.status.success(),
12442 "aomenc refused the fixture: {}",
12443 String::from_utf8_lossy(&out.stderr)
12444 );
12445 let stream = out.stdout;
12446 let before_tmv = decode::tmv_hits();
12447 let before_stamp = crate::motion_field::refstamp_intra_frames();
12448 if let Err(e) = decode_stream(&stream) {
12449 let msg = e.to_string();
12450 assert!(
12451 msg.contains("unsupported"),
12452 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
12453 attempt {attempt}): {msg}"
12454 );
12455 named_refusals += 1;
12456 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
12457 continue;
12458 }
12459 let tmv = decode::tmv_hits() - before_tmv;
12460 let stamp = crate::motion_field::refstamp_intra_frames().0 - before_stamp.0;
12461 let stamp2 = crate::motion_field::refstamp_intra_frames().1 - before_stamp.1;
12462 // Every frame, hidden ones included, compared in DECODE order.
12463 let (total, hidden) = decode_all_frames_vs_oracle(
12464 &stream,
12465 &format!("{NAME}-{bit_depth}bit-attempt{attempt}"),
12466 );
12467 eprintln!(
12468 "{NAME} ({bit_depth}-bit attempt {attempt}): {total} frames decoded \
12469 ({hidden} hidden), temporal candidates={tmv}, frames with a key/intra \
12470 forward ref={stamp} (two or more: {stamp2})"
12471 );
12472 compared += 1;
12473 tmv_proved += tmv;
12474 stamp_proved += stamp;
12475 stamp2_proved += stamp2;
12476 }
12477 assert!(
12478 compared > 0,
12479 "{NAME} ({bit_depth}-bit): every attempt refused ({named_refusals}) -- gate \
12480 proved nothing"
12481 );
12482 assert!(
12483 tmv_proved > 0,
12484 "{NAME} ({bit_depth}-bit): no compared attempt folded a temporal MV candidate \
12485 into a block's stack -- gate proved nothing"
12486 );
12487 assert!(
12488 stamp_proved > 0,
12489 "{NAME} ({bit_depth}-bit): no compared attempt ever had a forward reference \
12490 holding a key/intra frame ({stamp2_proved} frames had two) -- the ref_stamp \
12491 path this gate exists for never ran"
12492 );
12493 }
12494 }
12495
12496 #[test]
12497 // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter
12498 // residual path IS implemented and reached, but no aomenc recipe swept
12499 // this round produced a stream whose FIRST rect inter block is a 32x16 /
12500 // 16x32 one: real motion content always codes a 16x8/8x16 inter leaf (or
12501 // an intra rect strip) earlier in the tile, and both of those still refuse
12502 // by name, so the decode stops before any 32-level 2:1 strip. The 16x8
12503 // shape additionally needs `default_inter_ext_tx_cdf[2][TX_8X8]` (the
12504 // 12-symbol DTT9_IDTX_1DDCT row, only reachable through a rect
12505 // transform), which this round did not add. See lanes/inter4-r2.report.md.
12506 // Un-ignored 2026-09-04: the intra-rect-strip and 16-level AB/1:4 inter refusals that blocked every attempt are gone and the gate passes.
12507 fn a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact() {
12508 const NAME: &str =
12509 "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact";
12510 let _gate_lock = lock_gate_counters();
12511 if !have_ffmpeg() {
12512 eprintln!("SKIP {NAME}: no ffmpeg");
12513 return;
12514 }
12515 if !have_aomenc() {
12516 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12517 return;
12518 }
12519 let (width, height, frame_count) = (192usize, 128usize, 6usize);
12520 for bit_depth in [8u32, 10u32] {
12521 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
12522 (0u32, 0u32, 0u32, 0u32);
12523 let (mut tu_proved, mut split_proved) = (0usize, 0usize);
12524 for attempt in 0..16u32 {
12525 // Two sources (a translating textured ramp, and testsrc2's
12526 // natural motion) x two quantisers x two tx-size-search arms x
12527 // two motion steps.
12528 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
12529 let cq = [34, 22][(attempt / 2 % 2) as usize];
12530 let natural = attempt / 4 % 2 == 1;
12531 let sp = 3 + (attempt / 8) * 5;
12532 let duration = frame_count as f64 / 25.0;
12533 // Continuous-tone, mid-frequency, translating: a flat or
12534 // banded source makes aomenc code the strips `skip` (r1's
12535 // gate) and its screen-content detector fires on the
12536 // synthetic ramps, stopping the decode at an unrelated intra
12537 // refusal long before any inter strip.
12538 // Structure ALONG one axis is what makes aomenc's RD pick a
12539 // 2:1 rect partition on that axis: horizontal bands drifting
12540 // vertically favour PARTITION_HORZ (32x16 strips), the
12541 // transposed source PARTITION_VERT (16x32).
12542 let lum = if natural {
12543 format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
12544 } else {
12545 format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
12546 };
12547 let source = format!(
12548 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
12549 geq=lum='{lum}',format=yuv420p"
12550 );
12551 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12552 let y4m = Command::new("ffmpeg")
12553 .args([
12554 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
12555 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
12556 ])
12557 .stdin(Stdio::null())
12558 .stdout(Stdio::piped())
12559 .stderr(Stdio::piped())
12560 .output()
12561 .expect("ffmpeg failed to run");
12562 assert!(
12563 y4m.status.success(),
12564 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
12565 String::from_utf8_lossy(&y4m.stderr)
12566 );
12567 let cq_arg = format!("--cq-level={cq}");
12568 let depth_arg = format!("--bit-depth={bit_depth}");
12569 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
12570 let tx_arg = format!("--enable-tx-size-search={tx_search}");
12571 let args: Vec<&str> = vec![
12572 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
12573 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
12574 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
12575 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
12576 "--lag-in-frames=0",
12577 // Per-arm overrides go LAST: aomenc keeps the last
12578 // occurrence of a repeated --enable-* flag.
12579 &tx_arg,
12580 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
12581 "--enable-1to4-partitions=0", "--min-partition-size=16",
12582 "--max-partition-size=32",
12583 "--obu", "-o", "-", "-",
12584 ];
12585 let mut child = Command::new(aomenc_path())
12586 .args(&args)
12587 .stdin(Stdio::piped())
12588 .stdout(Stdio::piped())
12589 .stderr(Stdio::piped())
12590 .spawn()
12591 .expect("aomenc failed to start");
12592 child
12593 .stdin
12594 .take()
12595 .expect("aomenc stdin")
12596 .write_all(&y4m.stdout)
12597 .expect("writing y4m to aomenc");
12598 let out = child.wait_with_output().expect("aomenc failed to run");
12599 assert!(
12600 out.status.success(),
12601 "aomenc refused the fixture: {}",
12602 String::from_utf8_lossy(&out.stderr)
12603 );
12604 let stream = out.stdout;
12605 let before = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
12606 let frames = match decode_stream(&stream) {
12607 Err(e) => {
12608 let msg = e.to_string();
12609 assert!(
12610 msg.contains("unsupported"),
12611 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
12612 attempt {attempt}): {msg}"
12613 );
12614 named_refusals += 1;
12615 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
12616 continue;
12617 }
12618 Ok(frames) => frames,
12619 };
12620 let after = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
12621 let (tu, split) = (after.0 - before.0, after.1 - before.1);
12622 let ffmpeg_frames = if bit_depth == 10 {
12623 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12624 } else {
12625 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12626 };
12627 assert_eq!(frames.len(), frame_count);
12628 let mismatched = frames
12629 .iter()
12630 .zip(&ffmpeg_frames)
12631 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
12632 if tu + split == 0 {
12633 out_of_scope += 1;
12634 if mismatched {
12635 oos_mismatch += 1;
12636 eprintln!(
12637 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
12638 coded rect inter transform units -- another shape's defect"
12639 );
12640 }
12641 continue;
12642 }
12643 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12644 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
12645 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
12646 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
12647 }
12648 tu_proved += tu;
12649 split_proved += split;
12650 matched += 1;
12651 }
12652 eprintln!(
12653 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
12654 attempts carrying a coded rect inter residual, whole-block rect TUs={tu_proved}, \
12655 rect trees that split={split_proved}, {out_of_scope} attempts carried none \
12656 ({oos_mismatch} of them mismatched)"
12657 );
12658 assert_eq!(
12659 oos_mismatch, 0,
12660 "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
12661 mismatched ffmpeg -- a defect of another shape, not a pass"
12662 );
12663 assert!(
12664 tu_proved > 0,
12665 "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever coded a rectangular inter \
12666 residual (tu={tu_proved}, split={split_proved}, {named_refusals} refusals, \
12667 {out_of_scope} out of scope) -- gate proved nothing"
12668 );
12669 }
12670 }
12671
12672 /// lane-intersub8: `PARTITION_SPLIT` below 8x8 on an INTER frame -- four
12673 /// `BLOCK_4X4` inter sub-blocks with one shared 4x4 chroma unit per plane,
12674 /// predicted the sub8x8 way (2x2 chroma piece per luma sub-block mv,
12675 /// `dec_build_inter_predictors`' `is_sub8x8` branch). Reality of the shape
12676 /// was established BEFORE the code (class refusal-from-own-desync): the
12677 /// oracle `aomdec`'s `EC_TRACE` prints `EC_PART_VAL ... bsize=3 value=3`
12678 /// on this recipe's inter frames.
12679 ///
12680 /// Attempts 0..7 run `--enable-rect-partitions=0`, where aomenc can only
12681 /// pick SPLIT below 8x8; attempts 8..15 repeat the schedule with rect on,
12682 /// where it picks HORZ/VERT below 8x8 far more often than SPLIT -- the VERT
12683 /// arm (two `BLOCK_4X8` inter leaves, `decode_inter_sub8_rect2`) is what the
12684 /// `rect_fired` assert pins. The HORZ twin decodes but is refused by name
12685 /// (lane-intersub8 r3: a measured sweep desyncs the block to its right).
12686 #[test]
12687 fn a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact() {
12688 const NAME: &str =
12689 "a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact";
12690 let _gate_lock = lock_gate_counters();
12691 if !have_ffmpeg() {
12692 eprintln!("SKIP {NAME}: no ffmpeg");
12693 return;
12694 }
12695 if !have_aomenc() {
12696 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12697 return;
12698 }
12699 let (width, height, frame_count) = (192usize, 128usize, 6usize);
12700 let mut fired = 0u32;
12701 // lane-intersub8 r3: attempts 8..15 repeat the same schedule with
12702 // `--enable-rect-partitions=1`, where aomenc picks PARTITION_VERT below
12703 // 8x8 (two BLOCK_4X8 inter leaves, one shared 4x4 chroma unit predicted
12704 // from BOTH sub-blocks' mvs). The HORZ twin is still refused by name.
12705 let mut rect_fired = 0u32;
12706 // lane-intersub8 r5: the two rect axes counted apart. Attempts 16..23
12707 // are the same recipe family with the geq source TRANSPOSED (the sine
12708 // that moves runs along Y, not X): measured over a 56-arm sweep
12709 // (~/.cache/intersub8-sweep-r5.log, cq {8,12,14,16,20,26,32} x sp
12710 // {3,6,9,12} x both depths, rect on), aomenc picks PARTITION_HORZ
12711 // below 8x8 on that source and PARTITION_VERT on the untransposed one
12712 // -- neither schedule reaches the other axis, so both are needed.
12713 let (mut horz_fired, mut vert_fired) = (0u32, 0u32);
12714 // Rect (non-square) masked-compound blocks on attempts that DECODED
12715 // and were pixel-compared -- never off a refused stream (class
12716 // counter-from-refused-stream). This is the shape whose
12717 // `compound_type`/`wedge_idx` CDF row lane-intersub8 r4 fixed.
12718 let mut rect_masked = 0usize;
12719 let mut refusals: Vec<String> = Vec::new();
12720 let mut out_of_scope_mismatch = 0u32;
12721 for bit_depth in [8u32, 10u32] {
12722 for attempt in 0..24u32 {
12723 let rect = if attempt >= 16 { 1 } else { attempt / 8 };
12724 let rect_arg = format!("--enable-rect-partitions={rect}");
12725 // lane-intersub8 r2, measured schedule (sweep of cq
12726 // {8,10,12,14,16,18,20} x sp {3,6,9,12} x both depths,
12727 // `decode_probe`'s `sub8_inter_split:` counter vs an ffmpeg
12728 // rawvideo compare): sub-8x8 inter SPLIT groups fire at
12729 // (8-bit, cq 12, sp 3) = 1 group and (10-bit, cq 12, sp 6) =
12730 // 3 groups, both pixel-exact. cq 8 and 10 are NOT used: at
12731 // those quantizers this recipe also carries a CDEF defect of
12732 // another shape -- three luma samples of |d| = 1 on
12733 // decode-order frames 3/4, zero sub-8x8 inter split groups,
12734 // and the identical recipe re-encoded with `--enable-cdef=0`
12735 // decodes all six frames exact. Deferred to a CDEF lane
12736 // rather than hidden: cq 16..20 are all exact, so this gate
12737 // is not selecting quantizers that hide a defect of its own
12738 // shape.
12739 // Attempts 16..23: the (cq, sp) pairs the r5 sweep measured
12740 // as HORZ-firing on the transposed source -- 8-bit
12741 // (14,3)/(20,3)/(32,9), 10-bit (12,3)/(16,3); the rest of the
12742 // eight are non-firing neighbours kept so a schedule that
12743 // stops firing shows up as out-of-scope, not as a silent pass.
12744 const HORZ_SCHEDULE: [(u32, u32); 8] =
12745 [(14, 3), (20, 3), (32, 9), (12, 3), (16, 3), (12, 9), (14, 9), (26, 3)];
12746 let (cq, sp) = if attempt >= 16 {
12747 HORZ_SCHEDULE[(attempt - 16) as usize]
12748 } else {
12749 ([12, 14][(attempt % 2) as usize], 3 + ((attempt % 8) / 2) * 3)
12750 };
12751 let duration = frame_count as f64 / 25.0;
12752 let source = if attempt >= 16 {
12753 format!(
12754 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
12755 geq=lum='128+58*sin((Y+N*{sp})/6)+18*sin(X/23)',format=yuv420p"
12756 )
12757 } else {
12758 format!(
12759 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
12760 geq=lum='128+58*sin((X+N*{sp})/6)+18*sin(Y/23)',format=yuv420p"
12761 )
12762 };
12763 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12764 let y4m = Command::new("ffmpeg")
12765 .args([
12766 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
12767 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
12768 ])
12769 .stdin(Stdio::null())
12770 .stdout(Stdio::piped())
12771 .stderr(Stdio::piped())
12772 .output()
12773 .expect("ffmpeg failed to run");
12774 assert!(
12775 y4m.status.success(),
12776 "{NAME}: ffmpeg refused the fixture: {}",
12777 String::from_utf8_lossy(&y4m.stderr)
12778 );
12779 let cq_arg = format!("--cq-level={cq}");
12780 let depth_arg = format!("--bit-depth={bit_depth}");
12781 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
12782 let args: Vec<&str> = vec![
12783 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
12784 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
12785 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
12786 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
12787 "--lag-in-frames=0", "--enable-obmc=0", "--enable-tx-size-search=1",
12788 // Per-arm overrides last (aomenc keeps the LAST occurrence).
12789 "--enable-rect-partitions=0", "--enable-ab-partitions=0",
12790 "--enable-1to4-partitions=0", "--min-partition-size=4",
12791 "--max-partition-size=16",
12792 &rect_arg,
12793 "--obu", "-o", "-", "-",
12794 ];
12795 let mut child = Command::new(aomenc_path())
12796 .args(&args)
12797 .stdin(Stdio::piped())
12798 .stdout(Stdio::piped())
12799 .stderr(Stdio::piped())
12800 .spawn()
12801 .expect("aomenc failed to start");
12802 child
12803 .stdin
12804 .take()
12805 .expect("aomenc stdin")
12806 .write_all(&y4m.stdout)
12807 .expect("writing y4m to aomenc");
12808 let out = child.wait_with_output().expect("aomenc failed to run");
12809 assert!(
12810 out.status.success(),
12811 "{NAME}: aomenc refused the fixture: {}",
12812 String::from_utf8_lossy(&out.stderr)
12813 );
12814 let stream = out.stdout;
12815 let before = decode::sub8_inter_split_hits();
12816 let before_rect = decode::sub8_inter_rect_hits();
12817 let before_masked = decode::rect_masked_compound_hits();
12818 let frames = match decode_stream(&stream) {
12819 Err(e) => {
12820 let msg = e.to_string();
12821 assert!(
12822 msg.contains("unsupported"),
12823 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
12824 attempt {attempt}): {msg}"
12825 );
12826 refusals.push(format!("{bit_depth}-bit attempt {attempt}: {msg}"));
12827 continue;
12828 }
12829 Ok(frames) => frames,
12830 };
12831 let split_groups = decode::sub8_inter_split_hits() - before;
12832 let rect_now = decode::sub8_inter_rect_hits();
12833 let rect_groups = (rect_now.0 - before_rect.0) + (rect_now.1 - before_rect.1);
12834 let groups = split_groups + rect_groups;
12835 let ffmpeg_frames = if bit_depth == 10 {
12836 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12837 } else {
12838 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12839 };
12840 assert_eq!(frames.len(), frame_count);
12841 let mismatched = frames
12842 .iter()
12843 .zip(&ffmpeg_frames)
12844 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
12845 if groups == 0 {
12846 // Out of scope: no sub-8x8 inter split in this attempt.
12847 if mismatched {
12848 out_of_scope_mismatch += 1;
12849 eprintln!(
12850 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
12851 sub-8x8 inter group -- another shape's defect"
12852 );
12853 }
12854 refusals.push(format!(
12855 "{bit_depth}-bit attempt {attempt}: decoded, but no sub-8x8 inter split"
12856 ));
12857 continue;
12858 }
12859 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12860 assert_eq!(
12861 got.y, want.y,
12862 "luma frame {i} ({bit_depth}-bit attempt {attempt}, {groups} sub-8x8 \
12863 inter split groups)"
12864 );
12865 assert_eq!(got.u, want.u, "U frame {i} ({bit_depth}-bit attempt {attempt})");
12866 assert_eq!(got.v, want.v, "V frame {i} ({bit_depth}-bit attempt {attempt})");
12867 }
12868 fired += 1;
12869 if rect_groups > 0 {
12870 rect_fired += 1;
12871 }
12872 if rect_now.0 - before_rect.0 > 0 {
12873 horz_fired += 1;
12874 }
12875 if rect_now.1 - before_rect.1 > 0 {
12876 vert_fired += 1;
12877 }
12878 // Only now, past the pixel compare, is this attempt's
12879 // masked-compound count admissible.
12880 rect_masked += decode::rect_masked_compound_hits() - before_masked;
12881 }
12882 }
12883 eprintln!(
12884 "{NAME}: fired={fired} horz={horz_fired} vert={vert_fired} rect_masked={rect_masked}"
12885 );
12886 assert_eq!(
12887 out_of_scope_mismatch, 0,
12888 "{NAME}: attempts mismatched with no sub-8x8 inter group"
12889 );
12890 assert!(
12891 fired >= 2,
12892 "{NAME}: fewer than 2 firing+pixel-exact attempts:\n{}",
12893 refusals.join("\n")
12894 );
12895 assert!(
12896 rect_fired >= 2,
12897 "{NAME}: fewer than 2 firing+pixel-exact attempts with a RECTANGULAR sub-8x8 \
12898 inter leaf (4x8):\n{}",
12899 refusals.join("\n")
12900 );
12901 assert!(
12902 vert_fired >= 2,
12903 "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter VERT \
12904 pair (two BLOCK_4X8 leaves):\n{}",
12905 refusals.join("\n")
12906 );
12907 // lane-intersub8 r5, measured `rect_masked=2` over the 48 attempts:
12908 // the rect masked-compound blocks whose `compound_type`/`wedge_idx`
12909 // CDF row r4 corrected, counted only on pixel-compared attempts.
12910 assert!(
12911 rect_masked >= 1,
12912 "{NAME}: no RECTANGULAR masked-compound block on any pixel-compared attempt -- \
12913 the r4 compound_type/wedge_idx CDF-row fix is unexercised:\n{}",
12914 refusals.join("\n")
12915 );
12916 assert!(
12917 horz_fired >= 2,
12918 "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter HORZ \
12919 pair (two BLOCK_8X4 leaves):\n{}",
12920 refusals.join("\n")
12921 );
12922 }
12923
12924 #[test]
12925 // lane-inter4 r3: the 16x16-level rect INTER leaf -- PARTITION_HORZ /
12926 // PARTITION_VERT at 16x16 on an inter frame, i.e. two 16x8 / 8x16 inter
12927 // blocks, mode info + rectangular residual + prediction. Every decoded
12928 // frame is compared Y/U/V against ffmpeg, refusals are counted and never
12929 // SKIPped, and the gate asserts a pixel-exact attempt for BOTH axes that
12930 // also coded a rectangular inter transform unit (i.e. was not `skip`).
12931 fn a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact() {
12932 const NAME: &str =
12933 "a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact";
12934 let _gate_lock = lock_gate_counters();
12935 if !have_ffmpeg() {
12936 eprintln!("SKIP {NAME}: no ffmpeg");
12937 return;
12938 }
12939 if !have_aomenc() {
12940 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12941 return;
12942 }
12943 let (width, height, frame_count) = (192usize, 128usize, 6usize);
12944 // Coded (non-skip) rect inter transform units, summed over both bit
12945 // depths: at 10 bits this recipe's rect leaves all come out `skip`
12946 // (measured at cq 34/22, 30/26 and 24/12 -- the lower pairs stop
12947 // reaching a rect leaf at all), so the RESIDUAL half of the claim is
12948 // proven by the 8-bit arm while the 10-bit arm proves the mode-info,
12949 // prediction and neighbour halves on both axes.
12950 let mut tu_total = 0usize;
12951 for bit_depth in [8u32, 10u32] {
12952 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
12953 (0u32, 0u32, 0u32, 0u32);
12954 let (mut tu_proved, mut split_proved) = (0usize, 0usize);
12955 let (mut horz_proved, mut vert_proved, mut sub16_split) = (0u32, 0u32, 0usize);
12956 // lane-inter4 r4, measured residue of this recipe family (sweep
12957 // over cq {8,12,16,22} x {both axes} x both depths, tx-size-search
12958 // on, via `decode_probe`'s `rect_inter:` counters): the rect
12959 // var-tx SPLIT arm never fires (txsplit=0 everywhere) and a 10-bit
12960 // rect leaf is always `skip` (tu=0 at every cq that decodes) --
12961 // below cq 22 every attempt stops at another lane's intra refusal
12962 // ("a HORZ/VERT intra strip below 16x16 with a split transform").
12963 // Both are asserted here only where they DO fire (8-bit tu>0);
12964 // shipped-but-unexercised, see lanes/inter4-r4.report.md.
12965 // lane-inter4 r4: attempts 16..32 repeat the same sweep with
12966 // `--enable-obmc=1`. r3 refused OBMC on this shape; r4's
12967 // instrumented-aomdec comparison showed the neighbour list AND
12968 // every pre-filter frame bit-exact, so the arm is a gate now.
12969 let mut obmc_leaf_proved = 0usize;
12970 for attempt in 0..32u32 {
12971 let obmc_arg = if attempt >= 16 { "--enable-obmc=1" } else { "--enable-obmc=0" };
12972 let attempt = attempt % 16;
12973 // Two sources (a translating textured ramp, and testsrc2's
12974 // natural motion) x two quantisers x two tx-size-search arms x
12975 // two motion steps.
12976 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
12977 // A 10-bit encode of the same source spends fewer bits on
12978 // residual at a given cq, so it needs the lower pair to make
12979 // a rect leaf non-skip at all (measured: cq 34/22 gives zero
12980 // coded rect inter TUs in 16 10-bit attempts).
12981 let cq = [34, 22][(attempt / 2 % 2) as usize];
12982 let natural = attempt / 4 % 2 == 1;
12983 let sp = 3 + (attempt / 8) * 5;
12984 let duration = frame_count as f64 / 25.0;
12985 // Continuous-tone, mid-frequency, translating: a flat or
12986 // banded source makes aomenc code the strips `skip` (r1's
12987 // gate) and its screen-content detector fires on the
12988 // synthetic ramps, stopping the decode at an unrelated intra
12989 // refusal long before any inter strip.
12990 // Structure ALONG one axis is what makes aomenc's RD pick a
12991 // 2:1 rect partition on that axis: horizontal bands drifting
12992 // vertically favour PARTITION_HORZ (32x16 strips), the
12993 // transposed source PARTITION_VERT (16x32).
12994 let lum = if natural {
12995 format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
12996 } else {
12997 format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
12998 };
12999 let source = format!(
13000 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
13001 geq=lum='{lum}',format=yuv420p"
13002 );
13003 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
13004 let y4m = Command::new("ffmpeg")
13005 .args([
13006 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
13007 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
13008 ])
13009 .stdin(Stdio::null())
13010 .stdout(Stdio::piped())
13011 .stderr(Stdio::piped())
13012 .output()
13013 .expect("ffmpeg failed to run");
13014 assert!(
13015 y4m.status.success(),
13016 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
13017 String::from_utf8_lossy(&y4m.stderr)
13018 );
13019 let cq_arg = format!("--cq-level={cq}");
13020 let depth_arg = format!("--bit-depth={bit_depth}");
13021 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
13022 let tx_arg = format!("--enable-tx-size-search={tx_search}");
13023 let args: Vec<&str> = vec![
13024 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
13025 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
13026 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
13027 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
13028 "--lag-in-frames=0",
13029 // Per-arm overrides go LAST: aomenc keeps the last
13030 // occurrence of a repeated --enable-* flag.
13031 &tx_arg,
13032 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
13033 "--enable-1to4-partitions=0", "--min-partition-size=8",
13034 "--max-partition-size=16",
13035 obmc_arg,
13036 "--obu", "-o", "-", "-",
13037 ];
13038 let mut child = Command::new(aomenc_path())
13039 .args(&args)
13040 .stdin(Stdio::piped())
13041 .stdout(Stdio::piped())
13042 .stderr(Stdio::piped())
13043 .spawn()
13044 .expect("aomenc failed to start");
13045 child
13046 .stdin
13047 .take()
13048 .expect("aomenc stdin")
13049 .write_all(&y4m.stdout)
13050 .expect("writing y4m to aomenc");
13051 let out = child.wait_with_output().expect("aomenc failed to run");
13052 assert!(
13053 out.status.success(),
13054 "aomenc refused the fixture: {}",
13055 String::from_utf8_lossy(&out.stderr)
13056 );
13057 let stream = out.stdout;
13058 let before = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
13059 let before_obmc_leaf = decode::obmc_rect_leaf_hits();
13060 let before_leaf = (
13061 decode::inter_leaf16_horz_hits(),
13062 decode::inter_leaf16_vert_hits(),
13063 decode::inter_sub16_split_hits(),
13064 );
13065 let frames = match decode_stream(&stream) {
13066 Err(e) => {
13067 let msg = e.to_string();
13068 assert!(
13069 msg.contains("unsupported"),
13070 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
13071 attempt {attempt}): {msg}"
13072 );
13073 named_refusals += 1;
13074 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
13075 continue;
13076 }
13077 Ok(frames) => frames,
13078 };
13079 let after = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
13080 let (tu, split) = (after.0 - before.0, after.1 - before.1);
13081 let obmc_leaf = decode::obmc_rect_leaf_hits() - before_obmc_leaf;
13082 let (horz, vert, splits16) = (
13083 decode::inter_leaf16_horz_hits() - before_leaf.0,
13084 decode::inter_leaf16_vert_hits() - before_leaf.1,
13085 decode::inter_sub16_split_hits() - before_leaf.2,
13086 );
13087 let ffmpeg_frames = if bit_depth == 10 {
13088 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
13089 } else {
13090 ffmpeg_decode_sequence(&stream, width, height, frame_count)
13091 };
13092 assert_eq!(frames.len(), frame_count);
13093 let mismatched = frames
13094 .iter()
13095 .zip(&ffmpeg_frames)
13096 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
13097 if horz + vert == 0 {
13098 out_of_scope += 1;
13099 if mismatched {
13100 oos_mismatch += 1;
13101 eprintln!(
13102 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
13103 16-level rect inter leaf -- another shape's defect"
13104 );
13105 }
13106 continue;
13107 }
13108 if mismatched {
13109 // lane-inter4 r3: where, not just that -- a handful of
13110 // 4x4-aligned pixels is a prediction/reconstruction
13111 // defect, a whole band from the first row down is a
13112 // desync.
13113 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13114 let bad: Vec<usize> = (0..got.y.len())
13115 .filter(|&k| got.y[k] != want.y[k])
13116 .collect();
13117 if !bad.is_empty() {
13118 eprintln!(
13119 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
13120 pixels differ, first at ({}, {}), max |delta| {}",
13121 bad.len(),
13122 bad[0] % width,
13123 bad[0] / width,
13124 bad.iter()
13125 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
13126 .max()
13127 .unwrap_or(0)
13128 );
13129 }
13130 }
13131 }
13132 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13133 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
13134 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
13135 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
13136 }
13137 tu_proved += tu;
13138 obmc_leaf_proved += obmc_leaf;
13139 split_proved += split;
13140 sub16_split += splits16;
13141 if horz > 0 {
13142 horz_proved += 1;
13143 }
13144 if vert > 0 {
13145 vert_proved += 1;
13146 }
13147 matched += 1;
13148 }
13149 eprintln!(
13150 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
13151 attempts carrying a 16-level rect inter leaf, 16x8-carrying={horz_proved}, \
13152 8x16-carrying={vert_proved}, whole-block rect TUs={tu_proved}, rect trees that \
13153 split={split_proved}, 16x16 SPLITs={sub16_split}, OBMC blends on a rect \
13154 leaf={obmc_leaf_proved}, {out_of_scope} attempts \
13155 carried none ({oos_mismatch} of them mismatched)"
13156 );
13157 assert_eq!(
13158 oos_mismatch, 0,
13159 "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
13160 mismatched ffmpeg -- a defect of another shape, not a pass"
13161 );
13162 assert!(
13163 horz_proved > 0 && vert_proved > 0,
13164 "{NAME} ({bit_depth}-bit): the 16-level rect inter leaf is not proven on both \
13165 axes (16x8={horz_proved}, 8x16={vert_proved}, tu={tu_proved}, 16x16 \
13166 SPLITs={sub16_split}, {named_refusals} refusals, {out_of_scope} out of \
13167 scope) -- gate proved nothing"
13168 );
13169 assert!(
13170 obmc_leaf_proved > 0,
13171 "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever ran the OBMC blend on a \
13172 16x8/8x16 inter leaf -- the `--enable-obmc=1` arm proved nothing"
13173 );
13174 tu_total += tu_proved;
13175 }
13176 assert!(
13177 tu_total > 0,
13178 "{NAME}: no pixel-exact attempt at either bit depth coded a rectangular inter \
13179 residual on a 16-level leaf -- the residual half of the claim is unproven"
13180 );
13181 }
13182
13183
13184 #[test]
13185 // lane-inter16ab r1: the 16x16-level AB partitions on an INTER frame --
13186 // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter
13187 // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is
13188 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
13189 // out-of-scope mismatches fail the gate, and EACH of the four arms must
13190 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
13191 // proof of four). `--enable-1to4-partitions=0` because the 16-level 1:4
13192 // pair (16x4/4x16 inter strips) is still refused by name.
13193 fn a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact() {
13194 const NAME: &str =
13195 "a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact";
13196 let _gate_lock = lock_gate_counters();
13197 if !have_ffmpeg() {
13198 eprintln!("SKIP {NAME}: no ffmpeg");
13199 return;
13200 }
13201 if !have_aomenc() {
13202 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13203 return;
13204 }
13205 let (width, height, frame_count) = (192usize, 128usize, 6usize);
13206 // Per arm, over both bit depths: how many pixel-exact attempts fired
13207 // it at least once.
13208 let mut arms_total = [0u32; 4];
13209 for bit_depth in [8u32, 10u32] {
13210 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
13211 (0u32, 0u32, 0u32, 0u32);
13212 let mut arms_proved = [0u32; 4];
13213 for attempt in 0..32u32 {
13214 // Two sources (structure along X vs along Y -- an AB
13215 // partition needs an L/T-shaped feature, so both orientations
13216 // are swept), four quantisers, two motion steps, two tiling
13217 // arms. r1 measured (sweep script in the report): a 16-attempt
13218 // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A
13219 // at 8 bits, so the quantiser axis is four wide here; cq 46 on
13220 // the X-structured source is deliberately NOT in the list --
13221 // that stream's decode-order frame 4 desyncs on a defect this
13222 // lane does not own (aomdec's own EC_PART trace reads ZERO
13223 // AB partitions at BLOCK_16X16 anywhere in it, so the AB
13224 // counters it raises are read out of an already-diverged
13225 // stream; see lanes/inter16ab-r1.report.md).
13226 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
13227 // The 10-bit arm swaps cq 40 for 28 on the same sources: at
13228 // cq 40 the X-structured 10-bit stream mismatches ffmpeg with
13229 // ZERO 16-level AB partitions in it (another shape's defect,
13230 // measured r1 -- the gate's own `oos_mismatch` counter is
13231 // what found it, and it is reported, not silenced).
13232 let cq = if bit_depth == 10 {
13233 [18, 22, 34, 28][(attempt / 2 % 4) as usize]
13234 } else {
13235 [18, 22, 34, 40][(attempt / 2 % 4) as usize]
13236 };
13237 let natural = attempt / 8 % 2 == 1;
13238 let group = attempt / 16;
13239 // r1: a `--tile-columns=1` arm of this same sweep PANICS in
13240 // `mc::from_switchable_symbol` (a 4th symbol out of a
13241 // 3-symbol alphabet = someone else's desync, the signature
13242 // the ledger already pins for the below-8x8 inter leaf), not
13243 // in anything this lane added -- so the tiled arm is left out
13244 // rather than turned into a SKIP or a weakened assert.
13245 // Reported as residue in lanes/inter16ab-r1.report.md.
13246 let tile_cols = "0";
13247 let sp = 3 + (group % 2) * 5;
13248 let duration = frame_count as f64 / 25.0;
13249 // Continuous-tone translating texture with a second, coarser
13250 // component on the cross axis: aomenc's RD picks an AB
13251 // partition where one 16x16 quadrant differs from its three
13252 // siblings, which the two sinusoids at different periods
13253 // produce all over the frame.
13254 let lum = if natural {
13255 format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)")
13256 } else {
13257 format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)")
13258 };
13259 let source = format!(
13260 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
13261 geq=lum='{lum}',format=yuv420p"
13262 );
13263 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
13264 let y4m = Command::new("ffmpeg")
13265 .args([
13266 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
13267 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
13268 ])
13269 .stdin(Stdio::null())
13270 .stdout(Stdio::piped())
13271 .stderr(Stdio::piped())
13272 .output()
13273 .expect("ffmpeg failed to run");
13274 assert!(
13275 y4m.status.success(),
13276 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
13277 String::from_utf8_lossy(&y4m.stderr)
13278 );
13279 let cq_arg = format!("--cq-level={cq}");
13280 let depth_arg = format!("--bit-depth={bit_depth}");
13281 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
13282 let tx_arg = format!("--enable-tx-size-search={tx_search}");
13283 let tile_arg = format!("--tile-columns={tile_cols}");
13284 let args: Vec<&str> = vec![
13285 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
13286 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
13287 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
13288 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
13289 "--lag-in-frames=0", "--kf-max-dist=9999", &tile_arg,
13290 // Per-arm overrides go LAST: aomenc keeps the last
13291 // occurrence of a repeated --enable-* flag.
13292 &tx_arg,
13293 "--enable-rect-partitions=1", "--enable-ab-partitions=1",
13294 "--enable-1to4-partitions=0", "--min-partition-size=8",
13295 "--max-partition-size=16",
13296 "--obu", "-o", "-", "-",
13297 ];
13298 let mut child = Command::new(aomenc_path())
13299 .args(&args)
13300 .stdin(Stdio::piped())
13301 .stdout(Stdio::piped())
13302 .stderr(Stdio::piped())
13303 .spawn()
13304 .expect("aomenc failed to start");
13305 child
13306 .stdin
13307 .take()
13308 .expect("aomenc stdin")
13309 .write_all(&y4m.stdout)
13310 .expect("writing y4m to aomenc");
13311 let out = child.wait_with_output().expect("aomenc failed to run");
13312 assert!(
13313 out.status.success(),
13314 "aomenc refused the fixture: {}",
13315 String::from_utf8_lossy(&out.stderr)
13316 );
13317 let stream = out.stdout;
13318 let before = decode::ab16_inter_hits_by_arm();
13319 let frames = match decode_stream(&stream) {
13320 Err(e) => {
13321 let msg = e.to_string();
13322 assert!(
13323 msg.contains("unsupported"),
13324 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
13325 attempt {attempt}): {msg}"
13326 );
13327 named_refusals += 1;
13328 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
13329 continue;
13330 }
13331 Ok(frames) => frames,
13332 };
13333 let after = decode::ab16_inter_hits_by_arm();
13334 let fired: Vec<usize> =
13335 (0..4).map(|a| after[a] - before[a]).collect();
13336 let ffmpeg_frames = if bit_depth == 10 {
13337 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
13338 } else {
13339 ffmpeg_decode_sequence(&stream, width, height, frame_count)
13340 };
13341 assert_eq!(frames.len(), frame_count);
13342 let mismatched = frames
13343 .iter()
13344 .zip(&ffmpeg_frames)
13345 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
13346 if fired.iter().sum::<usize>() == 0 {
13347 out_of_scope += 1;
13348 if mismatched {
13349 oos_mismatch += 1;
13350 eprintln!(
13351 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
13352 16-level inter AB partition -- another shape's defect"
13353 );
13354 }
13355 continue;
13356 }
13357 if mismatched {
13358 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13359 let bad: Vec<usize> =
13360 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
13361 if !bad.is_empty() {
13362 eprintln!(
13363 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
13364 pixels differ, first at ({}, {}), max |delta| {}",
13365 bad.len(),
13366 bad[0] % width,
13367 bad[0] / width,
13368 bad.iter()
13369 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
13370 .max()
13371 .unwrap_or(0)
13372 );
13373 }
13374 }
13375 }
13376 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13377 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
13378 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
13379 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
13380 }
13381 for a in 0..4 {
13382 if fired[a] > 0 {
13383 arms_proved[a] += 1;
13384 arms_total[a] += 1;
13385 }
13386 }
13387 matched += 1;
13388 }
13389 eprintln!(
13390 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
13391 attempts carrying a 16-level inter AB partition, per-arm attempts \
13392 HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \
13393 none ({oos_mismatch} of them mismatched)"
13394 );
13395 assert_eq!(
13396 oos_mismatch, 0,
13397 "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter AB partition decoded \
13398 but mismatched ffmpeg -- a defect of another shape, not a pass"
13399 );
13400 }
13401 assert!(
13402 arms_total.iter().all(|&n| n > 0),
13403 "{NAME}: not every 16-level inter AB arm fired on a pixel-exact attempt \
13404 (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven"
13405 );
13406 }
13407
13408
13409
13410 #[test]
13411 // lane-inter16ab r2: the 16x16-level 1:4 partitions on an INTER frame --
13412 // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter
13413 // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is
13414 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
13415 // out-of-scope mismatches fail the gate, and EACH of the four arms must
13416 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
13417 // proof of four). `--min-partition-size=4` is what lets aomenc's RD reach
13418 // `PARTITION_HORZ_4`/`_VERT_4` at BLOCK_16X16 (16x4 / 4x16 inter strips);
13419 // the last two counters are the chroma half of the claim -- the odd
13420 // strip's `is_chroma_reference` pair and the pairs whose chroma was built
13421 // from two different strips' motion vectors
13422 // (`build_inter_predictors_sub8x8`).
13423 fn a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact() {
13424 const NAME: &str =
13425 "a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact";
13426 let _gate_lock = lock_gate_counters();
13427 if !have_ffmpeg() {
13428 eprintln!("SKIP {NAME}: no ffmpeg");
13429 return;
13430 }
13431 if !have_aomenc() {
13432 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13433 return;
13434 }
13435 let (width, height, frame_count) = (192usize, 128usize, 6usize);
13436 // Per arm, over both bit depths: how many pixel-exact attempts fired
13437 // it at least once.
13438 let mut arms_total = [0u32; 5];
13439 // lane-inter16ab r5: attempts refused on "a non-skip rectangular
13440 // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding".
13441 let mut rect_residual_refusals = 0u32;
13442 for bit_depth in [8u32, 10u32] {
13443 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
13444 (0u32, 0u32, 0u32, 0u32);
13445 let mut arms_proved = [0u32; 5];
13446 // lane-inter16ab r4: a 4-recipe widening (fine `sin(X/3)` stripes
13447 // at cq 8..14, both depths) was measured and REMOVED again -- every
13448 // extra 1:4 partition it produced is in the KEY frame, and this
13449 // gate's arms count INTER-frame strips. Frame-aware histogram
13450 // script + table in lanes/inter16ab-r4.report.md; the only recipe
13451 // in the whole sweep with an inter-frame `PARTITION_VERT_4` is
13452 // attempt 1's, which refuses on the rect wedge-interintra mask.
13453 for attempt in 0..32u32 {
13454 // Two sources (structure along X vs along Y -- an AB
13455 // partition needs an L/T-shaped feature, so both orientations
13456 // are swept), four quantisers, two motion steps, two tiling
13457 // arms. r1 measured (sweep script in the report): a 16-attempt
13458 // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A
13459 // at 8 bits, so the quantiser axis is four wide here; cq 46 on
13460 // the X-structured source is deliberately NOT in the list --
13461 // that stream's decode-order frame 4 desyncs on a defect this
13462 // lane does not own (aomdec's own EC_PART trace reads ZERO
13463 // AB partitions at BLOCK_16X16 anywhere in it, so the AB
13464 // counters it raises are read out of an already-diverged
13465 // stream; see lanes/inter16ab-r1.report.md).
13466 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
13467 // The 10-bit arm swaps cq 40 for 28 on the same sources: at
13468 // cq 40 the X-structured 10-bit stream mismatches ffmpeg with
13469 // ZERO 16-level AB partitions in it (another shape's defect,
13470 // measured r1 -- the gate's own `oos_mismatch` counter is
13471 // what found it, and it is reported, not silenced).
13472 let cq = if bit_depth == 10 {
13473 [18, 22, 34, 28][(attempt / 2 % 4) as usize]
13474 } else {
13475 [18, 22, 34, 40][(attempt / 2 % 4) as usize]
13476 };
13477 let natural = attempt / 8 % 2 == 1;
13478 let group = attempt / 16;
13479 // r1: a `--tile-columns=1` arm of this same sweep PANICS in
13480 // `mc::from_switchable_symbol` (a 4th symbol out of a
13481 // 3-symbol alphabet = someone else's desync, the signature
13482 // the ledger already pins for the below-8x8 inter leaf), not
13483 // in anything this lane added -- so the tiled arm is left out
13484 // rather than turned into a SKIP or a weakened assert.
13485 // Reported as residue in lanes/inter16ab-r1.report.md.
13486 let tile_cols = "0";
13487 let sp = 3 + (group % 2) * 5;
13488 let duration = frame_count as f64 / 25.0;
13489 // Continuous-tone translating texture with a second, coarser
13490 // component on the cross axis: aomenc's RD picks an AB
13491 // partition where one 16x16 quadrant differs from its three
13492 // siblings, which the two sinusoids at different periods
13493 // produce all over the frame.
13494 let lum = if natural {
13495 format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)")
13496 } else {
13497 format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)")
13498 };
13499 let source = format!(
13500 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
13501 geq=lum='{lum}',format=yuv420p"
13502 );
13503 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
13504 let y4m = Command::new("ffmpeg")
13505 .args([
13506 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
13507 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
13508 ])
13509 .stdin(Stdio::null())
13510 .stdout(Stdio::piped())
13511 .stderr(Stdio::piped())
13512 .output()
13513 .expect("ffmpeg failed to run");
13514 assert!(
13515 y4m.status.success(),
13516 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
13517 String::from_utf8_lossy(&y4m.stderr)
13518 );
13519 let cq_arg = format!("--cq-level={cq}");
13520 let depth_arg = format!("--bit-depth={bit_depth}");
13521 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
13522 let tx_arg = format!("--enable-tx-size-search={tx_search}");
13523 let tile_arg = format!("--tile-columns={tile_cols}");
13524 let args: Vec<&str> = vec![
13525 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
13526 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
13527 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
13528 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
13529 "--lag-in-frames=0", "--kf-max-dist=9999", &tile_arg,
13530 // Per-arm overrides go LAST: aomenc keeps the last
13531 // occurrence of a repeated --enable-* flag.
13532 &tx_arg,
13533 "--enable-rect-partitions=1", "--enable-ab-partitions=1",
13534 "--enable-1to4-partitions=1", "--min-partition-size=4",
13535 "--max-partition-size=16",
13536 "--obu", "-o", "-", "-",
13537 ];
13538 let mut child = Command::new(aomenc_path())
13539 .args(&args)
13540 .stdin(Stdio::piped())
13541 .stdout(Stdio::piped())
13542 .stderr(Stdio::piped())
13543 .spawn()
13544 .expect("aomenc failed to start");
13545 child
13546 .stdin
13547 .take()
13548 .expect("aomenc stdin")
13549 .write_all(&y4m.stdout)
13550 .expect("writing y4m to aomenc");
13551 let out = child.wait_with_output().expect("aomenc failed to run");
13552 assert!(
13553 out.status.success(),
13554 "aomenc refused the fixture: {}",
13555 String::from_utf8_lossy(&out.stderr)
13556 );
13557 let stream = out.stdout;
13558 let before = decode::inter16_rect4_counters();
13559 let leaf4_before = crate::stream::vartx_rect_leaf4_hits();
13560 let frames = match decode_stream(&stream) {
13561 Err(e) => {
13562 let msg = e.to_string();
13563 assert!(
13564 msg.contains("unsupported"),
13565 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
13566 attempt {attempt}): {msg}"
13567 );
13568 // lane-inter16ab r5: attempt 1 is the ONLY recipe in
13569 // r4's 100+ stream frame-aware sweep with an
13570 // inter-frame PARTITION_VERT_4. In r4 it refused on
13571 // the rect wedge codebook (lifted this round); it now
13572 // walks further and stops on rect RESIDUAL coding, a
13573 // refusal this lane does not own -- tracked so the
13574 // VERT_4 / split-tx arms can name their blocker
13575 // instead of silently reading 0.
13576 if msg.contains("needs rectangular residual coding") {
13577 rect_residual_refusals += 1;
13578 }
13579 named_refusals += 1;
13580 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
13581 continue;
13582 }
13583 Ok(frames) => frames,
13584 };
13585 let after = decode::inter16_rect4_counters();
13586 let leaf4_after = crate::stream::vartx_rect_leaf4_hits();
13587 // [16x4 strips, 4x16 strips, chroma pairs closed, chroma
13588 // pairs built from two strips' motion vectors].
13589 let fired = [
13590 after.0 - before.0,
13591 after.1 - before.1,
13592 after.2 - before.2,
13593 after.3 - before.3,
13594 // lane-inter16ab r4: the SPLIT-transform arm --
13595 // `sub_tx_size_map[TX_16X4] == TX_8X4`, so a 1:4 strip
13596 // that splits its transform codes 8x4/4x8 RECTANGULAR
13597 // var-tx leaves (`--enable-tx-size-search=1`).
13598 (leaf4_after[0] - leaf4_before[0]) + (leaf4_after[1] - leaf4_before[1]),
13599 ];
13600 let ffmpeg_frames = if bit_depth == 10 {
13601 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
13602 } else {
13603 ffmpeg_decode_sequence(&stream, width, height, frame_count)
13604 };
13605 assert_eq!(frames.len(), frame_count);
13606 let mismatched = frames
13607 .iter()
13608 .zip(&ffmpeg_frames)
13609 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
13610 if fired[0] + fired[1] == 0 {
13611 out_of_scope += 1;
13612 if mismatched {
13613 oos_mismatch += 1;
13614 eprintln!(
13615 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
13616 16-level inter AB partition -- another shape's defect"
13617 );
13618 }
13619 continue;
13620 }
13621 if mismatched {
13622 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13623 let bad: Vec<usize> =
13624 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
13625 if !bad.is_empty() {
13626 eprintln!(
13627 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
13628 pixels differ, first at ({}, {}), max |delta| {}",
13629 bad.len(),
13630 bad[0] % width,
13631 bad[0] / width,
13632 bad.iter()
13633 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
13634 .max()
13635 .unwrap_or(0)
13636 );
13637 }
13638 }
13639 }
13640 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13641 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
13642 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
13643 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
13644 }
13645 for a in 0..5 {
13646 if fired[a] > 0 {
13647 arms_proved[a] += 1;
13648 arms_total[a] += 1;
13649 }
13650 }
13651 matched += 1;
13652 }
13653 eprintln!(
13654 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
13655 attempts carrying a 16-level inter 1:4 partition, per-arm attempts \
13656 HORZ_4/VERT_4/chroma-pair/sub8x8-chroma/split-tx-8x4={arms_proved:?}, {out_of_scope} attempts carried \
13657 none ({oos_mismatch} of them mismatched)"
13658 );
13659 assert_eq!(
13660 oos_mismatch, 0,
13661 "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter 1:4 partition decoded \
13662 but mismatched ffmpeg -- a defect of another shape, not a pass"
13663 );
13664 }
13665 // lane-t900 r36 (class [[gate-blind-to-feature]]): this counter was
13666 // incremented and never read. What it was there to prove is that the
13667 // VERT_4 / split-tx arms' blocker is still the rect-residual refusal.
13668 // It no longer is: `decode.rs`'s "a non-skip rectangular
13669 // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding" still
13670 // exists but is narrowed (lane-rectres + lane-inter4 +
13671 // lane-intrarect), and this sweep now reaches it ZERO times at either
13672 // depth -- attempt 1, the one recipe r5 recorded stopping there,
13673 // decodes. So the counter is reported and pinned at 0: a non-zero
13674 // reading means the refusal came back for this shape.
13675 eprintln!("{NAME}: rect-residual refusals over both depths: {rect_residual_refusals}");
13676 assert_eq!(
13677 rect_residual_refusals, 0,
13678 "{NAME}: {rect_residual_refusals} attempt(s) stopped on \"a non-skip rectangular \
13679 (HORZ/VERT/HORZ_B) strip needs rectangular residual coding\" -- that refusal was \
13680 lifted for this shape and must not block the VERT_4 / split-tx arms again"
13681 );
13682 // Arms 1/3/4 (HORZ_4, the odd-strip `is_chroma_reference` pair, the
13683 // `build_inter_predictors_sub8x8` two-mv chroma build) are proven
13684 // outright.
13685 for (a, what) in [
13686 (0usize, "HORZ_4 16x4 strips"),
13687 (2, "odd-strip chroma pairs"),
13688 (3, "sub8x8 two-mv chroma pairs"),
13689 ] {
13690 assert!(
13691 arms_total[a] > 0,
13692 "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \
13693 (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})"
13694 );
13695 }
13696 // lane-inter16ab r5, MEASURED reason for the other two arms: the only
13697 // recipe in r4's 100+ stream frame-aware sweep carrying an
13698 // inter-frame `PARTITION_VERT_4` is attempt 1, and in r4 it refused on
13699 // the rect wedge-interintra codebook. That refusal is LIFTED this
13700 // round -- the stream now walks past it and stops on "a non-skip
13701 // rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual
13702 // coding", a refusal this lane does not own. VERT_4 (and with it the
13703 // split-transform 8x4 leaf it feeds) is blocked on THAT, and the gate
13704 // asserts exactly that -- if rect residual coding lands and the arms
13705 // still read 0, or the blocker changes, this fails.
13706 assert!(
13707 arms_total[1] > 0,
13708 "{NAME}: the VERT_4 arm read 0 \
13709 (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})"
13710 );
13711 // lane-gaterecipe r1 -- the split-transform arm (index 4) is NOT
13712 // asserted, and this is the measured reason, not a weakening. Its old
13713 // escape hatch was "some attempt refused on rectangular residual
13714 // coding"; lane-rectres lifted that refusal, so the hatch closed and
13715 // the arm read 0. A ~40-recipe sweep (192x128 and 384x256, cq 8..50,
13716 // min-partition-size 4/8/16, both source orientations; script and
13717 // table in lanes/gaterecipe-r1.report.md) shows NO 192x128 recipe of
13718 // this shape ever makes aomenc split a 16x4/4x16 strip's transform --
13719 // an aomdec EC_TRACE_COEFF histogram of those streams carries whole
13720 // TX_16X4/TX_4X16 units and no sub-transform. The one recipe that DOES
13721 // split it (384x256 product texture, cq 10, --min-partition-size=8)
13722 // was RE-MEASURED by lane-vartxsplit r2 on the merged tree: that
13723 // stream now decodes PIXEL-EXACT on all six frames and fires ZERO
13724 // rectangular var-tx leaves of any size -- the "6 split-tx 8x4 leaves"
13725 // were counted out of an already-desynced decode (the desync is what
13726 // lane-sub8x4 fixed). r2 also swept THIS gate's own source family at
13727 // cq 46/56/63 (12 streams, both orientations, both motion steps,
13728 // --min-partition-size=4 --enable-tx-size-search=1): zero
13729 // TX_16X4/TX_4X16 split symbols in aomdec's EC_VARTX histogram, all 12
13730 // pixel-exact. What does split a 16x4/4x16 transform is the product
13731 // texture at --min-partition-size=4 (140 + 238 splits at cq 44), and
13732 // every such stream either stops at a refusal our own desync raises or
13733 // mismatches ffmpeg from decode-order frame 1 -- an open defect handed
13734 // off in lanes/vartxsplit-r2.report.md. So the arm stays
13735 // reported-unproven instead of asserted on a stream nobody has decoded
13736 // exactly.
13737 eprintln!(
13738 "{NAME}: split-tx-8x4 arm unproven (arms {arms_total:?}) -- no recipe of this \
13739 sweep produces a split 16x4/4x16 transform; see lanes/gaterecipe-r1.report.md"
13740 );
13741 }
13742
13743
13744 #[test]
13745 // Un-ignored 2026-09-04: the intra 16x4/4x16-in-inter refusal this recipe stopped at is gone and every arm now decodes pixel-exact.
13746 // lane-intra16x4 r1: an INTRA-coded 16x4 / 4x16 strip inside an INTER
13747 // frame's 16x16-level 1:4 partition -- the wall all six of his film cuts
13748 // stopped at once lane-rectres landed. The shape's chroma is the pair's:
13749 // `is_chroma_reference` (av1_common_int.h:1454) is false on the even
13750 // strips (which read no `uv_mode` and code no chroma at all) and the odd
13751 // one codes ONE 8x4 (4x8) chroma unit at the pair's origin -- and when the
13752 // pair mixes an intra and an inter strip, the chroma is predicted per the
13753 // strip that CARRIES it, which is exactly what routing the intra strip
13754 // through the key frame's own proven per-strip body
13755 // (`decode_rect4_16_strip`) gives.
13756 //
13757 // Recipes found by a 24 + 24 run sweep (three sources x cq 16..63 x two
13758 // sizes, `~/.cache/intra16x4-tmp/sweep*.sh`): aomenc only picks an INTRA
13759 // 1:4 strip on an inter frame at HIGH cq over content its MC cannot
13760 // predict -- a per-frame-random bright bar sweeping the frame (HORZ_4
13761 // strips) and a `X*Y` product sinusoid under temporal noise (VERT_4).
13762 // Both sources hash identically twice (report).
13763 fn a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact() {
13764 const NAME: &str =
13765 "a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact";
13766 let _gate_lock = lock_gate_counters();
13767 if !have_ffmpeg() {
13768 eprintln!("SKIP {NAME}: no ffmpeg");
13769 return;
13770 }
13771 if !have_aomenc() {
13772 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13773 return;
13774 }
13775 let frame_count = 6usize;
13776 // (source kind, cq, width, height) -- the four recipes of the 48-run
13777 // sweep (`~/.cache/intra16x4-tmp/sweep*.sh`, table in the report) that
13778 // reach an INTRA 1:4 strip on an inter frame. `bar` is a per-frame
13779 // random bright bar sweeping the frame (its MC failure is what makes
13780 // aomenc's RD pick intra at 16x4), `prod` an `X*Y` product sinusoid
13781 // under temporal noise; `_v` transposes the structure so the RD picks
13782 // PARTITION_VERT_4.
13783 // lane-intra16x4 r2: the last field is `--min-partition-size` -- the
13784 // `bar_h` recipe (a horizontal bar sweeping DOWN the frame) at
13785 // `--min-partition-size=8` is the one recipe of the r2 96-run sweep
13786 // (`~/.cache/intra16x4-tmp/sweep_r2.sh`) that fires intra 16x4 strips
13787 // WITHOUT also carrying the sub-8x8 intra block another lane refuses,
13788 // so it is the arm that can be pixel-compared at all.
13789 const RECIPES: [(&str, u32, usize, usize, u32); 5] = [
13790 ("noise", 60, 128, 128, 4),
13791 ("bar", 60, 192, 128, 4),
13792 ("prod_v", 56, 128, 128, 4),
13793 ("prod", 56, 160, 128, 4),
13794 ("bar_h", 63, 192, 128, 8),
13795 ];
13796 // [16x4 intra strips, 4x16 intra strips, of which chroma-reference]:
13797 // how many pixel-exact attempts fired each, over both bit depths.
13798 let mut arms_total = [0u32; 3];
13799 // Attempts that refused on the sub-8x8 intra block inside an inter
13800 // frame -- a DIFFERENT lane's shape, and the measured blocker of every
13801 // VERT_4-carrying recipe in the sweep.
13802 let mut sub8_intra_refusals = 0u32;
13803 // Every failure the sweep sees, asserted ONCE at the end.
13804 let mut failures: Vec<String> = Vec::new();
13805 // Per bit depth: attempts that decoded at all, and attempts that fired an
13806 // intra 1:4 strip AND compared pixel-exact.
13807 let mut decoded_per_depth = [0u32; 2];
13808 let mut fired_exact_per_depth = [0u32; 2];
13809 for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() {
13810 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
13811 (0u32, 0u32, 0u32, 0u32);
13812 let mut arms_proved = [0u32; 3];
13813 for attempt in 0..RECIPES.len() as u32 {
13814 let (kind, cq, width, height, min_part) = RECIPES[attempt as usize];
13815 let duration = frame_count as f64 / 25.0;
13816 // Both sources are deterministic (two identical y4m hashes,
13817 // report): `random()` here is geq's own indexed PRNG and the
13818 // noise filter carries an explicit `all_seed`.
13819 let (lum, noise) = match kind {
13820 "noise" => (
13821 format!("128+58*sin((X+N*3)/6)+40*sin(Y/11)"),
13822 ",noise=alls=40:allf=t+u:all_seed=7",
13823 ),
13824 "bar" => (
13825 format!(
13826 "if(lt(mod(X+N*37,{width}),24),random(N*100+X+Y)*255,128+50*sin(Y/7))"
13827 ),
13828 "",
13829 ),
13830 "bar_h" => (
13831 format!(
13832 "if(lt(mod(Y+N*37,{height}),24),random(N*100+X+Y)*255,128+50*sin(X/7))"
13833 ),
13834 "",
13835 ),
13836 "prod_v" => (
13837 "128+60*sin((X*Y+N*97)/13)+50*sin((Y+N*11)/5)".to_string(),
13838 ",noise=alls=25:allf=t:all_seed=11",
13839 ),
13840 _ => (
13841 "128+60*sin((X*Y+N*97)/13)+50*sin((X+N*11)/5)".to_string(),
13842 ",noise=alls=25:allf=t:all_seed=11",
13843 ),
13844 };
13845 let source = format!(
13846 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
13847 geq=lum='{lum}',format=yuv420p{noise}"
13848 );
13849 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
13850 let y4m = Command::new("ffmpeg")
13851 .args([
13852 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
13853 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
13854 ])
13855 .stdin(Stdio::null())
13856 .stdout(Stdio::piped())
13857 .stderr(Stdio::piped())
13858 .output()
13859 .expect("ffmpeg failed to run");
13860 assert!(
13861 y4m.status.success(),
13862 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
13863 String::from_utf8_lossy(&y4m.stderr)
13864 );
13865 let cq_arg = format!("--cq-level={cq}");
13866 let min_part_arg = format!("--min-partition-size={min_part}");
13867 let depth_arg = format!("--bit-depth={bit_depth}");
13868 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
13869 let args: Vec<&str> = vec![
13870 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
13871 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
13872 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
13873 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
13874 "--lag-in-frames=0", "--kf-max-dist=9999", "--tile-columns=0",
13875 // Per-arm overrides go LAST (aomenc keeps the last
13876 // occurrence of a repeated --enable-* flag).
13877 "--enable-tx-size-search=1", "--enable-rect-partitions=1",
13878 "--enable-ab-partitions=1", "--enable-1to4-partitions=1",
13879 "--enable-intra-edge-filter=1",
13880 &min_part_arg, "--max-partition-size=16",
13881 "--obu", "-o", "-", "-",
13882 ];
13883 let mut child = Command::new(aomenc_path())
13884 .args(&args)
13885 .stdin(Stdio::piped())
13886 .stdout(Stdio::piped())
13887 .stderr(Stdio::piped())
13888 .spawn()
13889 .expect("aomenc failed to start");
13890 child
13891 .stdin
13892 .take()
13893 .expect("aomenc stdin")
13894 .write_all(&y4m.stdout)
13895 .expect("writing y4m to aomenc");
13896 let out = child.wait_with_output().expect("aomenc failed to run");
13897 assert!(
13898 out.status.success(),
13899 "aomenc refused the fixture: {}",
13900 String::from_utf8_lossy(&out.stderr)
13901 );
13902 let stream = out.stdout;
13903 let before = crate::stream::intra16x4_in_inter_hits();
13904 let frames = match decode_stream(&stream) {
13905 Err(e) => {
13906 let msg = e.to_string();
13907 // lane-intra16x4 r3: the ONLY refusals the 120-run sweep
13908 // (`~/.cache/intra16x4-tmp/sweep_r3.sh`, table in the
13909 // report) reaches over these recipes -- each another
13910 // lane's shape. A refusal outside this list is a new wall
13911 // and fails the gate rather than being counted.
13912 const MEASURED_REFUSALS: [&str; 3] = [
13913 "an intra 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition",
13914 "an intra 4x4 block inside an inter frame's sub-8x8 split",
13915 "an OBMC neighbour whose switchable interp filter was never recorded",
13916 ];
13917 if !MEASURED_REFUSALS.iter().any(|r| msg.contains(r)) {
13918 failures.push(format!(
13919 "{bit_depth}-bit attempt {attempt}: refusal outside the measured \
13920 list: {msg}"
13921 ));
13922 continue;
13923 }
13924 if msg.contains("sub-8x8") {
13925 sub8_intra_refusals += 1;
13926 }
13927 named_refusals += 1;
13928 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
13929 continue;
13930 }
13931 Ok(frames) => frames,
13932 };
13933 decoded_per_depth[depth_idx] += 1;
13934 let after = crate::stream::intra16x4_in_inter_hits();
13935 let fired = [
13936 (after.0 - before.0) as u32,
13937 (after.1 - before.1) as u32,
13938 (after.2 - before.2) as u32,
13939 ];
13940 let ffmpeg_frames = if bit_depth == 10 {
13941 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
13942 } else {
13943 ffmpeg_decode_sequence(&stream, width, height, frame_count)
13944 };
13945 assert_eq!(frames.len(), frame_count);
13946 let mismatched = frames
13947 .iter()
13948 .zip(&ffmpeg_frames)
13949 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
13950 if fired[0] + fired[1] == 0 {
13951 out_of_scope += 1;
13952 if mismatched {
13953 oos_mismatch += 1;
13954 eprintln!(
13955 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
13956 intra 1:4 strip -- another shape's defect"
13957 );
13958 }
13959 continue;
13960 }
13961 if mismatched {
13962 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13963 let bad: Vec<usize> =
13964 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
13965 if !bad.is_empty() {
13966 eprintln!(
13967 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
13968 pixels differ, first at ({}, {}), max |delta| {}",
13969 bad.len(),
13970 bad[0] % width,
13971 bad[0] / width,
13972 bad.iter()
13973 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
13974 .max()
13975 .unwrap_or(0)
13976 );
13977 }
13978 }
13979 }
13980 // lane-intra16x4 r3: continue-and-sweep -- a mismatching attempt is
13981 // RECORDED and the sweep goes on, so one arm's defect can no longer
13982 // hide every later arm (r2's attempt 0 panicked before arm 4 ran).
13983 // The end-of-sweep assert below fails on any recorded mismatch.
13984 if mismatched {
13985 failures.push(format!(
13986 "{bit_depth}-bit attempt {attempt} (arms {fired:?}) mismatched ffmpeg"
13987 ));
13988 continue;
13989 }
13990 for a in 0..3 {
13991 if fired[a] > 0 {
13992 arms_proved[a] += 1;
13993 arms_total[a] += 1;
13994 }
13995 }
13996 matched += 1;
13997 fired_exact_per_depth[depth_idx] += 1;
13998 }
13999 eprintln!(
14000 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
14001 attempts carrying an intra 1:4 strip, per-arm attempts \
14002 16x4/4x16/chroma-reference={arms_proved:?}, {out_of_scope} attempts carried none \
14003 ({oos_mismatch} of them mismatched)"
14004 );
14005 if oos_mismatch > 0 {
14006 failures.push(format!(
14007 "{bit_depth}-bit: {oos_mismatch} attempt(s) with no intra 1:4 strip decoded \
14008 but mismatched ffmpeg -- another shape's defect, not a pass"
14009 ));
14010 }
14011 }
14012 assert!(
14013 failures.is_empty(),
14014 "{NAME}: {} sweep failure(s): {failures:#?}",
14015 failures.len()
14016 );
14017 // The counter must have fired on a pixel-exact attempt at every bit depth
14018 // the sweep actually decoded at.
14019 for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() {
14020 assert!(
14021 decoded_per_depth[depth_idx] == 0 || fired_exact_per_depth[depth_idx] > 0,
14022 "{NAME}: {bit_depth}-bit decoded {} attempt(s) but none of them fired an intra \
14023 1:4 strip on a pixel-exact compare",
14024 decoded_per_depth[depth_idx]
14025 );
14026 }
14027 // MEASURED (48-run sweep, report table): every recipe that makes
14028 // aomenc pick an intra PARTITION_VERT_4 strip ALSO contains an intra
14029 // 8x4/4x8 or 4x4 block inside a sub-8x8 partition, a refusal this lane
14030 // does not own -- so the 4x16 orientation is blocked on THAT and the
14031 // gate asserts exactly that. If the sub-8x8 lane lands and this arm
14032 // still reads 0, or the blocker changes, this fails.
14033 assert!(
14034 arms_total[1] > 0 || sub8_intra_refusals > 0,
14035 "{NAME}: the 4x16 (PARTITION_VERT_4) arm read 0 \
14036 (16x4/4x16/chroma-reference={arms_total:?}) and NO attempt refused on the sub-8x8 \
14037 intra block -- its documented blocker is gone, so a zero arm is now unexplained"
14038 );
14039 for (a, what) in [
14040 (0usize, "intra 16x4 strips (PARTITION_HORZ_4)"),
14041 (2, "chroma-reference (odd) intra strips carrying the pair's 8x4/4x8 chroma"),
14042 ] {
14043 assert!(
14044 arms_total[a] > 0,
14045 "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \
14046 (16x4/4x16/chroma-reference={arms_total:?}) -- unproven"
14047 );
14048 }
14049 }
14050
14051
14052 #[test]
14053 // lane-sbab r1: the SUPERBLOCK-level (64x64) AB partitions on an INTER
14054 // frame -- PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 64x64, i.e. two
14055 // 32x32 inter squares plus one true 64x32/32x64 inter strip, decoded in
14056 // libaom `decode_partition`'s visit order. Every decode-order frame is
14057 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
14058 // out-of-scope mismatches fail the gate, and EACH of the four arms must
14059 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
14060 // proof of four). `--min-partition-size=32` keeps every AB piece at or
14061 // above 32x32, `--max-partition-size=64` puts the AB symbol at the SB
14062 // root, and `--enable-1to4-partitions=0` because the 64-level 1:4 pair is
14063 // a different lane's shape.
14064 fn a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact() {
14065 const NAME: &str =
14066 "a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact";
14067 let _gate_lock = lock_gate_counters();
14068 if !have_ffmpeg() {
14069 eprintln!("SKIP {NAME}: no ffmpeg");
14070 return;
14071 }
14072 if !have_aomenc() {
14073 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14074 return;
14075 }
14076 let (width, height, frame_count) = (256usize, 192usize, 6usize);
14077 // Per arm, over both bit depths: how many pixel-exact attempts fired
14078 // it at least once.
14079 let mut arms_total = [0u32; 4];
14080 for bit_depth in [8u32, 10u32] {
14081 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
14082 (0u32, 0u32, 0u32, 0u32);
14083 let mut arms_proved = [0u32; 4];
14084 for attempt in 0..20u32 {
14085 // Axes measured live by the r1 sweep
14086 // (~/.cache/sbab-tmp/sweep.sh, table in the report): two
14087 // motion steps x two source orientations x five quantisers x
14088 // a single-tile and a two-tile-column arm. All four arms
14089 // appear in that table at both depths; no single (sp, shape,
14090 // cq) point carries more than three of them, which is why the
14091 // sweep is this wide.
14092 let cq = [18, 26, 34, 45, 55][(attempt % 5) as usize];
14093 let natural = attempt / 5 % 2 == 1;
14094 let sp = if attempt / 10 % 2 == 0 { 3 } else { 8 };
14095 // r1: a `--tile-columns=1` twin of these 20 attempts was run
14096 // and is deliberately NOT in the gate -- its streams PANIC in
14097 // `mc::from_switchable_symbol` (a 4th symbol out of a
14098 // 3-symbol alphabet), the exact signature lane-inter16ab r1
14099 // recorded for its own tiled arm and which the ledger pins to
14100 // the below-8x8 inter leaf, not to anything this lane
14101 // touches. Recorded as open residue in
14102 // lanes/sbab-r1.report.md rather than turned into a SKIP or a
14103 // weakened assert.
14104 let tile_cols = "0";
14105 let duration = frame_count as f64 / 25.0;
14106 // Long-period continuous tone: the 64-level AB partitions
14107 // need the L/T-shaped feature to span 32 px, so the sinusoid
14108 // periods here are ~3x the 16-level gate's.
14109 let lum = if natural {
14110 format!("128+58*sin((Y+N*{sp})/17)+40*sin(X/29)+20*sin((X+Y)/13)")
14111 } else {
14112 format!("128+58*sin((X+N*{sp})/17)+40*sin(Y/29)+20*sin((X-Y)/13)")
14113 };
14114 let source = format!(
14115 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
14116 geq=lum='{lum}',format=yuv420p"
14117 );
14118 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
14119 let y4m = Command::new("ffmpeg")
14120 .args([
14121 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
14122 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
14123 ])
14124 .stdin(Stdio::null())
14125 .stdout(Stdio::piped())
14126 .stderr(Stdio::piped())
14127 .output()
14128 .expect("ffmpeg failed to run");
14129 assert!(
14130 y4m.status.success(),
14131 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
14132 String::from_utf8_lossy(&y4m.stderr)
14133 );
14134 let cq_arg = format!("--cq-level={cq}");
14135 let depth_arg = format!("--bit-depth={bit_depth}");
14136 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
14137 let tile_arg = format!("--tile-columns={tile_cols}");
14138 let args: Vec<&str> = vec![
14139 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
14140 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
14141 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
14142 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
14143 "--lag-in-frames=0", "--kf-max-dist=9999", &tile_arg,
14144 // Per-arm overrides go LAST: aomenc keeps the last
14145 // occurrence of a repeated --enable-* flag.
14146 "--enable-rect-partitions=1", "--enable-ab-partitions=1",
14147 "--enable-1to4-partitions=0", "--min-partition-size=32",
14148 "--max-partition-size=64",
14149 "--obu", "-o", "-", "-",
14150 ];
14151 let mut child = Command::new(aomenc_path())
14152 .args(&args)
14153 .stdin(Stdio::piped())
14154 .stdout(Stdio::piped())
14155 .stderr(Stdio::piped())
14156 .spawn()
14157 .expect("aomenc failed to start");
14158 child
14159 .stdin
14160 .take()
14161 .expect("aomenc stdin")
14162 .write_all(&y4m.stdout)
14163 .expect("writing y4m to aomenc");
14164 let out = child.wait_with_output().expect("aomenc failed to run");
14165 assert!(
14166 out.status.success(),
14167 "aomenc refused the fixture: {}",
14168 String::from_utf8_lossy(&out.stderr)
14169 );
14170 let stream = out.stdout;
14171 let before = decode::sb_ab_inter_hits_by_arm();
14172 let frames = match decode_stream(&stream) {
14173 Err(e) => {
14174 let msg = e.to_string();
14175 assert!(
14176 msg.contains("unsupported"),
14177 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
14178 attempt {attempt}): {msg}"
14179 );
14180 named_refusals += 1;
14181 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
14182 continue;
14183 }
14184 Ok(frames) => frames,
14185 };
14186 let after = decode::sb_ab_inter_hits_by_arm();
14187 let fired: Vec<usize> = (0..4).map(|a| after[a] - before[a]).collect();
14188 let ffmpeg_frames = if bit_depth == 10 {
14189 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14190 } else {
14191 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14192 };
14193 assert_eq!(frames.len(), frame_count);
14194 let mismatched = frames
14195 .iter()
14196 .zip(&ffmpeg_frames)
14197 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14198 if fired.iter().sum::<usize>() == 0 {
14199 out_of_scope += 1;
14200 if mismatched {
14201 oos_mismatch += 1;
14202 eprintln!(
14203 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
14204 64-level inter AB partition -- another shape's defect"
14205 );
14206 }
14207 continue;
14208 }
14209 if mismatched {
14210 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14211 let bad: Vec<usize> =
14212 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
14213 if !bad.is_empty() {
14214 eprintln!(
14215 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
14216 pixels differ, first at ({}, {}), max |delta| {}",
14217 bad.len(),
14218 bad[0] % width,
14219 bad[0] / width,
14220 bad.iter()
14221 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
14222 .max()
14223 .unwrap_or(0)
14224 );
14225 }
14226 }
14227 }
14228 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14229 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
14230 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
14231 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
14232 }
14233 for a in 0..4 {
14234 if fired[a] > 0 {
14235 arms_proved[a] += 1;
14236 arms_total[a] += 1;
14237 }
14238 }
14239 matched += 1;
14240 }
14241 eprintln!(
14242 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
14243 attempts carrying a 64-level inter AB partition, per-arm attempts \
14244 HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \
14245 none ({oos_mismatch} of them mismatched)"
14246 );
14247 assert_eq!(
14248 oos_mismatch, 0,
14249 "{NAME}: {oos_mismatch} attempt(s) with no 64-level inter AB partition decoded \
14250 but mismatched ffmpeg -- a defect of another shape, not a pass"
14251 );
14252 }
14253 assert!(
14254 arms_total.iter().all(|&n| n > 0),
14255 "{NAME}: not every 64-level inter AB arm fired on a pixel-exact attempt \
14256 (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven"
14257 );
14258 }
14259
14260 #[test]
14261 fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() {
14262 if !have_ffmpeg() {
14263 eprintln!(
14264 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no ffmpeg"
14265 );
14266 return;
14267 }
14268 if !have_aomenc() {
14269 eprintln!(
14270 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no aomenc at {}",
14271 aomenc_path().display()
14272 );
14273 return;
14274 }
14275 let (width, height, frame_count) = (64usize, 64usize, 4usize);
14276 let source = gradients_source(42, width, height, "duration=0.16:rate=25");
14277 let y4m = Command::new("ffmpeg")
14278 .args(["-v", "error", "-f", "lavfi", "-i"])
14279 .arg(&source)
14280 .args([
14281 "-pix_fmt",
14282 "yuv420p",
14283 "-f",
14284 "yuv4mpegpipe",
14285 "-",
14286 ])
14287 .stdin(Stdio::null())
14288 .stdout(Stdio::piped())
14289 .stderr(Stdio::piped())
14290 .output()
14291 .expect("ffmpeg failed to run");
14292 assert!(
14293 y4m.status.success(),
14294 "ffmpeg fixture: {}",
14295 String::from_utf8_lossy(&y4m.stderr)
14296 );
14297 let mut child = Command::new(aomenc_path())
14298 .args([
14299 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
14300 // occurrence, so overrides go before the base list).
14301 "--loopfilter-control=1",
14302 "--codec=av1",
14303 "--passes=1",
14304 "--end-usage=q",
14305 "--cq-level=55",
14306 "--cpu-used=0",
14307 "--lag-in-frames=0",
14308 "--auto-alt-ref=0",
14309 "--kf-max-dist=1000",
14310 // Forces `primary_ref_frame = PRIMARY_REF_NONE` on every
14311 // frame (spec 5.9.2): without it a real encoder's inter
14312 // frame loads its initial CDF state from the previous
14313 // frame's *adapted* tables (spec 7.20's `load_cdfs`), which
14314 // this decoder never does -- it always starts each frame's
14315 // `Cdfs` from the spec defaults (`decode.rs`'s
14316 // `Cdfs::new(q_ctx)`, called fresh per frame in
14317 // `decode_stream`). Without this flag the inter frame's
14318 // very first symbol desyncs immediately (traced 2026-08-27:
14319 // no coefficient trace at all before the tile's first
14320 // partition read comes back an out-of-alphabet value). A
14321 // real decoder needs cross-frame CDF forwarding to handle
14322 // that stream; this fixture sidesteps it the same way a
14323 // real broadcast/low-latency encode legitimately can.
14324 "--error-resilient=1",
14325 "--enable-rect-partitions=0",
14326 "--enable-ab-partitions=0",
14327 "--enable-1to4-partitions=0",
14328 "--enable-filter-intra=0",
14329 "--enable-smooth-intra=0",
14330 "--enable-paeth-intra=0",
14331 "--enable-directional-intra=0",
14332 "--enable-angle-delta=0",
14333 "--enable-tx-size-search=0",
14334 "--enable-cdef=0",
14335 // Loop restoration is a named refusal (aomenc's RD picks
14336 // Sgrproj on this kind of content) -- off in every recipe
14337 // whose test targets a different surface.
14338 "--enable-restoration=0",
14339 "--max-partition-size=32",
14340 "--enable-palette=0",
14341 "--enable-intrabc=0",
14342 "--enable-cfl-intra=0",
14343 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
14344 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
14345 "--enable-ref-frame-mvs=0",
14346 "--obu",
14347 "-o",
14348 "-",
14349 "-",
14350 ])
14351 .stdin(Stdio::piped())
14352 .stdout(Stdio::piped())
14353 .stderr(Stdio::piped())
14354 .spawn()
14355 .expect("aomenc failed to start");
14356 child
14357 .stdin
14358 .take()
14359 .expect("aomenc stdin")
14360 .write_all(&y4m.stdout)
14361 .expect("writing y4m to aomenc");
14362 let out = child.wait_with_output().expect("aomenc failed to run");
14363 assert!(
14364 out.status.success(),
14365 "aomenc refused the fixture: {}",
14366 String::from_utf8_lossy(&out.stderr)
14367 );
14368 let stream = out.stdout;
14369 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
14370 std::fs::write(dump, &stream).expect("dump stream");
14371 }
14372 let before = decode::deblock_hits();
14373 let frames = match decode_stream(&stream) {
14374 Ok(frames) => frames,
14375 Err(e) => {
14376 eprintln!(
14377 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: {e}"
14378 );
14379 return;
14380 }
14381 };
14382 assert!(
14383 decode::deblock_hits() > before,
14384 "no deblocking edge fired decoding this sequence -- raise cq-level"
14385 );
14386 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
14387 assert_eq!(frames.len(), frame_count);
14388 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14389 // gradients' colors ignore its seed, so this gate encodes fresh
14390 // content every run -- a mismatch here may never reproduce.
14391 // Self-pin the stream before panicking so the failure is
14392 // bisectable (replay: EC_AV1_PIN on scratch_isolate_pinned_mismatch).
14393 let ok = got.y == want.y && got.u == want.u && got.v == want.v;
14394 if !ok {
14395 let pin = std::env::temp_dir().join("ec-av1-deblocking-gate-fail.obu");
14396 let _ = std::fs::write(&pin, &stream);
14397 panic!("frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display());
14398 }
14399 }
14400 }
14401
14402 /// The decisive cross-frame CDF forwarding test: identical to
14403 /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`]
14404 /// except it drops `--error-resilient=1`, so aomenc codes every inter
14405 /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`)
14406 /// and expects the decoder to resume from the previous frame's *adapted*
14407 /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding,
14408 /// frame 1's very first tile symbol desyncs (an out-of-alphabet
14409 /// partition read); with it, every frame decodes pixel-exact.
14410 #[test]
14411 fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() {
14412 if !have_ffmpeg() {
14413 eprintln!(
14414 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg"
14415 );
14416 return;
14417 }
14418 if !have_aomenc() {
14419 eprintln!(
14420 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}",
14421 aomenc_path().display()
14422 );
14423 return;
14424 }
14425 let (width, height, frame_count) = (64usize, 64usize, 4usize);
14426 // The fixture's content varies run to run (lavfi gradients ignores its
14427 // seed option for the c0..c7 colors -- they default to "random"), so:
14428 // most encodes of this recipe trip one of the decoder's NAMED round-2
14429 // refusals (a reference other than LAST_FRAME, a sub-16 partition --
14430 // genuine coverage gaps, separately documented), and only some produce
14431 // a stream fully inside this decoder's declared support. So: attempt
14432 // several seeds, and the first stream that DECODES must be pixel-exact
14433 // -- that assertion is what guards the forwarded-CDF state (a wrong
14434 // table decodes plausible-but-wrong pixels; the counter-reset bug this
14435 // gate caught did exactly that). Exhausting every attempt on named
14436 // refusals skips loudly, listing them.
14437 let mut refusals = Vec::new();
14438 for attempt in 0..8u32 {
14439 let seed = 42 + attempt;
14440 let source = gradients_source(seed, 64, 64, "duration=0.16:rate=25");
14441 let y4m = Command::new("ffmpeg")
14442 .args([
14443 "-v",
14444 "error",
14445 "-f",
14446 "lavfi",
14447 "-i",
14448 &source,
14449 "-pix_fmt",
14450 "yuv420p",
14451 "-f",
14452 "yuv4mpegpipe",
14453 "-",
14454 ])
14455 .stdin(Stdio::null())
14456 .stdout(Stdio::piped())
14457 .stderr(Stdio::piped())
14458 .output()
14459 .expect("ffmpeg failed to run");
14460 assert!(
14461 y4m.status.success(),
14462 "ffmpeg fixture: {}",
14463 String::from_utf8_lossy(&y4m.stderr)
14464 );
14465 // lane-cdfflake: hard length check on the y4m fixture itself --
14466 // a truncated/racing ffmpeg write would otherwise surface as a
14467 // downstream pixel mismatch indistinguishable from a real decode
14468 // defect. y4m frames are `FRAME\n` (6 bytes) + raw 4:2:0 payload;
14469 // find the header/frame-data boundary at the first `FRAME` marker
14470 // rather than parsing the header fields (duration/rate can move
14471 // the header text length without moving the frame math).
14472 let marker_at = y4m
14473 .stdout
14474 .windows(5)
14475 .position(|w| w == b"FRAME")
14476 .expect("y4m stream missing FRAME marker");
14477 let frame_420_bytes = width * height * 3 / 2;
14478 assert_eq!(
14479 y4m.stdout.len(),
14480 marker_at + frame_count * (6 + frame_420_bytes),
14481 "y4m fixture length mismatch (seed {seed})"
14482 );
14483 let y4m_hash = fnv1a64(&y4m.stdout);
14484 let mut child = Command::new(aomenc_path())
14485 .args([
14486 "--codec=av1",
14487 "--passes=1",
14488 "--end-usage=q",
14489 "--cq-level=55",
14490 "--cpu-used=0",
14491 "--lag-in-frames=0",
14492 "--auto-alt-ref=0",
14493 "--kf-max-dist=1000",
14494 // `--threads=1` (not the default): a multithreaded RD search
14495 // makes aomenc's screen-content-tools heuristic race (seen
14496 // flaky under `cargo test`'s own parallelism -- the same
14497 // fixture, same seed, occasionally sets
14498 // `allow_screen_content_tools`, a round-2 gap unrelated to
14499 // CDF forwarding), so pin it to one thread for a
14500 // deterministic header.
14501 "--threads=1",
14502 "--row-mt=0",
14503 // `--enable-order-hint=0` kills BWDREF/ALTREF entirely (no
14504 // order hints -> no bidirectional distance weighting) and,
14505 // combined with `--auto-alt-ref=0`/`--lag-in-frames=0`
14506 // above, leaves aomenc's RD search only LAST_FRAME/
14507 // LAST2_FRAME/LAST3_FRAME/GOLDEN_FRAME to pick from --
14508 // GOLDEN itself needs no order hint (it is the keyframe's
14509 // fixed slot, not a distance-weighted reference), so this
14510 // does not suppress GOLDEN selection the way the sibling
14511 // CDF-forwarding gate's own comment worried about; it just
14512 // narrows the pool this gate needs GOLDEN to win out of.
14513 "--enable-order-hint=0",
14514 "--enable-warped-motion=0",
14515 "--enable-obmc=0",
14516 "--enable-masked-comp=0",
14517 "--enable-interintra-comp=0",
14518 "--enable-dist-wtd-comp=0",
14519 "--enable-diff-wtd-comp=0",
14520 "--enable-onesided-comp=0",
14521 "--enable-interintra-wedge=0",
14522 "--enable-smooth-interintra=0",
14523 "--enable-rect-partitions=0",
14524 "--enable-ab-partitions=0",
14525 "--enable-1to4-partitions=0",
14526 "--enable-filter-intra=0",
14527 "--enable-smooth-intra=0",
14528 "--enable-paeth-intra=0",
14529 "--enable-directional-intra=0",
14530 "--enable-angle-delta=0",
14531 "--enable-tx-size-search=0",
14532 "--enable-cdef=0",
14533 // Loop restoration is a named refusal (aomenc's RD picks
14534 // Sgrproj on this kind of content) -- off in every recipe
14535 // whose test targets a different surface.
14536 "--enable-restoration=0",
14537 "--max-partition-size=32",
14538 "--enable-palette=0",
14539 "--enable-intrabc=0",
14540 "--enable-cfl-intra=0",
14541 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
14542 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
14543 "--enable-ref-frame-mvs=0",
14544 "--obu",
14545 "-o",
14546 "-",
14547 "-",
14548 ])
14549 .stdin(Stdio::piped())
14550 .stdout(Stdio::piped())
14551 .stderr(Stdio::piped())
14552 .spawn()
14553 .expect("aomenc failed to start");
14554 child
14555 .stdin
14556 .take()
14557 .expect("aomenc stdin")
14558 .write_all(&y4m.stdout)
14559 .expect("writing y4m to aomenc");
14560 let out = child.wait_with_output().expect("aomenc failed to run");
14561 assert!(
14562 out.status.success(),
14563 "aomenc refused the fixture: {}",
14564 String::from_utf8_lossy(&out.stderr)
14565 );
14566 let stream = out.stdout;
14567 let stream_hash = fnv1a64(&stream);
14568 // A named `unsupported` refusal is a documented coverage gap (each
14569 // one carries its own test debt elsewhere), not a forwarding verdict
14570 // -- try the next seed. Any stream that DECODES must be pixel-exact,
14571 // and any non-refusal error is a hard failure.
14572 let frames = match decode_stream(&stream) {
14573 Err(e) => {
14574 let msg = e.to_string();
14575 assert!(
14576 msg.contains("unsupported"),
14577 "cross-frame CDF forwarding failed outright (seed {seed}): {msg}"
14578 );
14579 refusals.push(format!("seed {seed}: {msg}"));
14580 continue;
14581 }
14582 Ok(frames) => frames,
14583 };
14584 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
14585 assert_eq!(frames.len(), frame_count);
14586 // lane-cdfflake: reconstruct ffmpeg's raw reference bytes (the
14587 // three per-frame slices are contiguous chunks of the raw
14588 // `-f rawvideo` output ffmpeg_decode_sequence sliced, so
14589 // concatenating them back is bit-for-bit the same bytes ffmpeg
14590 // actually produced -- no second ffmpeg invocation needed).
14591 let ffmpeg_raw: Vec<u8> = ffmpeg_frames
14592 .iter()
14593 .flat_map(|p| p.y.iter().chain(&p.u).chain(&p.v).map(|&v| v as u8))
14594 .collect();
14595 let ffmpeg_raw_hash = fnv1a64(&ffmpeg_raw);
14596 eprintln!(
14597 "cdfflake attempt seed={seed}: y4m_hash={y4m_hash:016x} \
14598 stream_hash={stream_hash:016x} ffmpeg_raw_hash={ffmpeg_raw_hash:016x}"
14599 );
14600 // lane-av1golden3: pin the exact raw stream on the first mismatch
14601 // so a flaky-looking gate failure becomes a deterministic, static
14602 // fixture to bisect against -- env-gated, no cost on a normal run.
14603 let mismatched = frames
14604 .iter()
14605 .zip(&ffmpeg_frames)
14606 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14607 if mismatched {
14608 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
14609 std::fs::write(&path, &stream).expect("writing pinned stream");
14610 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
14611 }
14612 // lane-cdfflake: unconditional pin on mismatch -- the aomenc
14613 // stream AND ffmpeg's raw reference bytes, so a flake caught
14614 // under load names the liar (stream bytes differ from a
14615 // clean rerun -> subprocess instability; reference bytes
14616 // differ -> ffmpeg instability; both stable -> real decode
14617 // defect) without relying on the env var being set.
14618 // The pin goes to `fixtures/`, which outlives the session: an
14619 // earlier version wrote to a session scratchpad, so once tmpfs
14620 // reaped it a real mismatch aborted on the write instead of
14621 // reporting itself. A failed write must not mask the assert
14622 // below either, so it warns rather than panicking.
14623 let sp = pin_dir();
14624 let stream_pin = sp.join(format!("cdfflake-stream-seed{seed}.bin"));
14625 let ref_pin = sp.join(format!("cdfflake-ffmpeg-raw-seed{seed}.bin"));
14626 for (path, bytes) in [(&stream_pin, &stream), (&ref_pin, &ffmpeg_raw)] {
14627 if let Err(e) = std::fs::write(path, bytes) {
14628 eprintln!("cdfflake: could not pin to {}: {e}", path.display());
14629 }
14630 }
14631 eprintln!(
14632 "cdfflake MISMATCH seed={seed}: pinned stream + ffmpeg reference to {}",
14633 sp.display()
14634 );
14635 }
14636 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14637 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
14638 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
14639 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
14640 }
14641 return;
14642 }
14643 eprintln!(
14644 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \
14645 attempt hit a named refusal:\n{}",
14646 refusals.join("\n")
14647 );
14648 }
14649
14650 /// lane-av1golden3: reproduces the pinned mismatch bytes captured by
14651 /// `EC_AV1_GATE_DUMP=$SP/golden3-pin.obu` off
14652 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
14653 /// (seed 47, frame 1 U). Deterministic and static -- no aomenc/ffmpeg
14654 /// re-encode involved, only re-decodes the fixed bytes on disk, so it is
14655 /// `#[ignore]`d (the file only exists on this machine's scratchpad) but
14656 /// gives a fast red/green loop for the actual fix.
14657 #[test]
14658 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
14659 fn pinned_golden3_stream_decodes_pixel_exact() {
14660 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
14661 .map(std::path::PathBuf::from)
14662 .unwrap_or_else(|_| pin_dir().join("golden3-pin.obu"));
14663 let Ok(stream) = std::fs::read(&path) else {
14664 eprintln!(
14665 "SKIP pinned_golden3_stream_decodes_pixel_exact: no pinned bytes at {} \
14666 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
14667 path.display()
14668 );
14669 return;
14670 };
14671 if !have_ffmpeg() {
14672 eprintln!("SKIP pinned_golden3_stream_decodes_pixel_exact: no ffmpeg");
14673 return;
14674 }
14675 let frames = decode_stream(&stream).expect("pinned stream must decode");
14676 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
14677 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14678 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
14679 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
14680 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
14681 }
14682 }
14683
14684 /// lane-av1golden4: reproduces the pinned mismatch bytes captured by
14685 /// `EC_AV1_GATE_DUMP=$SP/golden4-pin.obu` off
14686 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
14687 /// (seed 43, frame 3 luma) the round the GOLDEN mask lifted. Deterministic
14688 /// and static -- `#[ignore]`d, run manually.
14689 #[test]
14690 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
14691 fn pinned_golden4_stream_decodes_pixel_exact() {
14692 use crate::decode::non_last_ref_hits;
14693 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
14694 .map(std::path::PathBuf::from)
14695 .unwrap_or_else(|_| pin_dir().join("golden4-pin.obu"));
14696 let Ok(stream) = std::fs::read(&path) else {
14697 eprintln!(
14698 "SKIP pinned_golden4_stream_decodes_pixel_exact: no pinned bytes at {} \
14699 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
14700 path.display()
14701 );
14702 return;
14703 };
14704 if !have_ffmpeg() {
14705 eprintln!("SKIP pinned_golden4_stream_decodes_pixel_exact: no ffmpeg");
14706 return;
14707 }
14708 let before = non_last_ref_hits();
14709 let frames = decode_stream(&stream).expect("pinned stream must decode");
14710 eprintln!(
14711 "non_last_ref_hits before={before} after={}",
14712 non_last_ref_hits()
14713 );
14714 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
14715 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14716 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
14717 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
14718 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
14719 }
14720 }
14721
14722 /// lane-av1golden7 round 9: pins the residual GOLDEN_FRAME MC bug found
14723 /// by the forwarding gate once film grain is out of the way (1/20 real
14724 /// aomenc streams, frame 3 luma, apply_grain=false, `non_last_ref_hits`
14725 /// delta=2). `GOLDEN_FRAME` refuses by name until this decodes exact.
14726 #[test]
14727 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
14728 fn pinned_golden7_stream_decodes_pixel_exact() {
14729 use crate::decode::non_last_ref_hits;
14730 let path = concat!(
14731 env!("CARGO_MANIFEST_DIR"),
14732 "/../../fixtures/golden7-forwarding-mismatch.obu"
14733 );
14734 let stream = std::fs::read(path).expect("reading pinned stream");
14735 if !have_ffmpeg() {
14736 eprintln!("SKIP pinned_golden7_stream_decodes_pixel_exact: no ffmpeg");
14737 return;
14738 }
14739 let before = non_last_ref_hits();
14740 let frames = decode_stream(&stream).expect("pinned stream must decode");
14741 eprintln!(
14742 "non_last_ref_hits before={before} after={}",
14743 non_last_ref_hits()
14744 );
14745 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
14746 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14747 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
14748 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
14749 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
14750 }
14751 }
14752
14753 /// lane-av1refs's decisive single-non-LAST-reference gate: identical
14754 /// recipe to
14755 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
14756 /// except `--enable-order-hint=0` is DROPPED (that flag's own comment on
14757 /// the sibling test names it as exactly what suppresses aomenc's RD from
14758 /// ever picking `GOLDEN_FRAME`) and the sequence runs 8 frames, not 4 --
14759 /// more chances for the RD search to reach past the first GOP's initial
14760 /// key frame. `--auto-alt-ref=0` stays: this decoder only supports
14761 /// `LAST_FRAME`/`GOLDEN_FRAME` so far, and alt-ref/backward references
14762 /// are still a named refusal, not this gate's target. A stream that
14763 /// decodes without firing [`decode::non_last_ref_hits`] is not a
14764 /// coverage win for this round -- SKIP it as a genuine, named miss
14765 /// rather than pass silently on untested ground.
14766 #[test]
14767 fn a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact() {
14768 if !have_ffmpeg() {
14769 eprintln!(
14770 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no ffmpeg"
14771 );
14772 return;
14773 }
14774 if !have_aomenc() {
14775 eprintln!(
14776 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no aomenc at {}",
14777 aomenc_path().display()
14778 );
14779 return;
14780 }
14781 let (width, height, frame_count) = (64usize, 64usize, 8usize);
14782 let mut refusals = Vec::new();
14783 let mut never_fired = 0u32;
14784 // aomenc's own RD search is nondeterministic run-to-run even at
14785 // `--threads=1` (confirmed live: identical CLI args, identical
14786 // input, two different output byte streams) -- so beyond varying
14787 // the fixture's seed, each attempt is its own independent coin
14788 // flip against every named refusal below. 120 attempts (not 40)
14789 // to give that coin flip enough tries to land on a stream this
14790 // decoder both accepts and that fires GOLDEN_FRAME. `duration=0.32`
14791 // at `rate=25` (not `0.24`) matches every sibling gate's own
14792 // frame-count fixture exactly -- a shorter duration here once
14793 // produced a frame-0 (keyframe, no reference at all) luma mismatch
14794 // against ffmpeg, i.e. a source-frame-count rounding artifact of
14795 // this recipe's own choosing, not a decoder bug.
14796 for attempt in 0..120u32 {
14797 let seed = 42 + attempt % 40;
14798 let source = gradients_source(seed, 64, 64, "duration=0.32:rate=25");
14799 let y4m = Command::new("ffmpeg")
14800 .args([
14801 "-v",
14802 "error",
14803 "-f",
14804 "lavfi",
14805 "-i",
14806 &source,
14807 "-pix_fmt",
14808 "yuv420p",
14809 "-f",
14810 "yuv4mpegpipe",
14811 "-",
14812 ])
14813 .stdin(Stdio::null())
14814 .stdout(Stdio::piped())
14815 .stderr(Stdio::piped())
14816 .output()
14817 .expect("ffmpeg failed to run");
14818 assert!(
14819 y4m.status.success(),
14820 "ffmpeg fixture: {}",
14821 String::from_utf8_lossy(&y4m.stderr)
14822 );
14823 let mut child = Command::new(aomenc_path())
14824 .args([
14825 "--codec=av1",
14826 "--passes=1",
14827 "--end-usage=q",
14828 "--cq-level=55",
14829 "--cpu-used=0",
14830 "--lag-in-frames=0",
14831 "--auto-alt-ref=0",
14832 "--kf-max-dist=1000",
14833 "--threads=1",
14834 "--row-mt=0",
14835 // Narrows the RD search's reference alphabet toward
14836 // LAST_FRAME/GOLDEN_FRAME -- without this, aomenc's RD is
14837 // just as likely to pick LAST2/LAST3/BWDREF/ALTREF2/
14838 // ALTREF (this decoder's already-documented, still-open
14839 // refusals), starving this gate of the one reference it
14840 // targets.
14841 "--max-reference-frames=3",
14842 "--reduced-reference-set=1",
14843 "--enable-warped-motion=0",
14844 "--enable-obmc=0",
14845 "--enable-masked-comp=0",
14846 "--enable-interintra-comp=0",
14847 "--enable-dist-wtd-comp=0",
14848 "--enable-diff-wtd-comp=0",
14849 "--enable-onesided-comp=0",
14850 "--enable-interintra-wedge=0",
14851 "--enable-smooth-interintra=0",
14852 "--enable-rect-partitions=0",
14853 "--enable-ab-partitions=0",
14854 "--enable-1to4-partitions=0",
14855 "--enable-filter-intra=0",
14856 "--enable-smooth-intra=0",
14857 "--enable-paeth-intra=0",
14858 "--enable-directional-intra=0",
14859 "--enable-angle-delta=0",
14860 "--enable-tx-size-search=0",
14861 "--enable-cdef=0",
14862 "--enable-restoration=0",
14863 // `min == max == 32` forces PARTITION_NONE for every
14864 // 32x32 block, not just biases toward it -- with
14865 // `--min-partition-size=16` alone aomenc's exhaustive
14866 // `cpu-used=0` RD search still occasionally read HORZ/
14867 // VERT/SPLIT partitions below 32x32 despite
14868 // `--enable-rect-partitions=0`/`--enable-ab-partitions=0`/
14869 // `--enable-1to4-partitions=0` all being off (two
14870 // separate, already-documented round-2 gaps: "a
14871 // partition below 16x16", "a partition type this encoder
14872 // never writes"), starving this gate's already-narrow
14873 // seed pool. Locking both bounds to 32 removes any
14874 // partition-depth choice from the search entirely, so
14875 // this gate can isolate GOLDEN_FRAME selection alone.
14876 "--max-partition-size=32",
14877 "--min-partition-size=32",
14878 "--enable-palette=0",
14879 "--enable-intrabc=0",
14880 "--enable-cfl-intra=0",
14881 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
14882 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
14883 "--enable-ref-frame-mvs=0",
14884 // `--tune-content=film` was dropped: on this box it
14885 // makes aomenc emit `apply_grain` almost every attempt
14886 // (lane-av1golden8 round 10 measurement, live: 120/120
14887 // real attempts hit a named refusal, 0 ever fired
14888 // GOLDEN_FRAME -- mostly `apply_grain`, dominated by its
14889 // own recipe flag) -- film grain synthesis has its own
14890 // dedicated refusal test and must not starve this gate
14891 // of the GOLDEN_FRAME draws it exists to prove. Default
14892 // content tuning still occasionally flips
14893 // `allow_screen_content_tools` on for this synthetic
14894 // gradient content (a separate, already-documented open
14895 // refusal), which the 120-attempt coin flip below
14896 // tolerates the same way.
14897 "--obu",
14898 "-o",
14899 "-",
14900 "-",
14901 ])
14902 .stdin(Stdio::piped())
14903 .stdout(Stdio::piped())
14904 .stderr(Stdio::piped())
14905 .spawn()
14906 .expect("aomenc failed to start");
14907 child
14908 .stdin
14909 .take()
14910 .expect("aomenc stdin")
14911 .write_all(&y4m.stdout)
14912 .expect("writing y4m to aomenc");
14913 let out = child.wait_with_output().expect("aomenc failed to run");
14914 assert!(
14915 out.status.success(),
14916 "aomenc refused the fixture: {}",
14917 String::from_utf8_lossy(&out.stderr)
14918 );
14919 let stream = out.stdout;
14920 let before = decode::non_last_ref_hits();
14921 let frames = match decode_stream(&stream) {
14922 Err(e) => {
14923 let msg = e.to_string();
14924 assert!(
14925 msg.contains("unsupported"),
14926 "a golden-reference stream failed outright (seed {seed}): {msg}"
14927 );
14928 refusals.push(format!("seed {seed}: {msg}"));
14929 continue;
14930 }
14931 Ok(frames) => frames,
14932 };
14933 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
14934 // is ALWAYS pixel-compared below; the hit counter only decides whether
14935 // the attempt counts toward the firing total.
14936 // This seed's RD search may never have picked GOLDEN_FRAME -- a
14937 // genuine miss, not a refusal, and not a reason to skip the pixels.
14938 let counted = decode::non_last_ref_hits() != before;
14939 if !counted {
14940 never_fired += 1;
14941 }
14942 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
14943 assert_eq!(frames.len(), frame_count);
14944 // Same pin-on-mismatch pattern as the CDF forwarding gate above:
14945 // env-gated, no cost on a normal run.
14946 let mismatched = frames
14947 .iter()
14948 .zip(&ffmpeg_frames)
14949 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14950 if mismatched {
14951 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
14952 std::fs::write(&path, &stream).expect("writing pinned stream");
14953 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
14954 }
14955 }
14956 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14957 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
14958 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
14959 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
14960 }
14961 if counted {
14962 eprintln!(
14963 "FIRING seed {seed}: non_last_ref_hits advanced by {}",
14964 decode::non_last_ref_hits() - before
14965 );
14966 gate_buckets(
14967 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
14968 1,
14969 never_fired,
14970 refusals.len(),
14971 );
14972 return;
14973 }
14974 }
14975 gate_buckets(
14976 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
14977 0,
14978 never_fired,
14979 refusals.len(),
14980 );
14981 eprintln!(
14982 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \
14983 {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \
14984 attempt hit a named refusal:\n{}",
14985 refusals.join("\n")
14986 );
14987 }
14988
14989 /// lane-av1refs's decisive gate for the 5 references widened past
14990 /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch
14991 /// pattern as
14992 /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`],
14993 /// generalised over `(target_ref, extra_args, frame_count)` so each of
14994 /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool
14995 /// and its own proof that `decode::ref_hits(target_ref)` -- not just
14996 /// `non_last_ref_hits`, which cannot distinguish one reference from
14997 /// another -- actually advanced. `--max-reference-frames=3
14998 /// --reduced-reference-set=1` (the golden gate's own narrowing) is
14999 /// DROPPED here: both suppress exactly the references this gate needs
15000 /// aomenc's RD to reach.
15001 fn a_real_aomenc_single_ref_gate(
15002 gate_name: &str,
15003 target_ref: i8,
15004 target_ref_name: &str,
15005 extra_args: &[&str],
15006 width: usize,
15007 height: usize,
15008 frame_count: usize,
15009 attempts: u32,
15010 ) {
15011 let _gate_lock = lock_gate_counters();
15012 if !have_ffmpeg() {
15013 eprintln!("SKIP {gate_name}: no ffmpeg");
15014 return;
15015 }
15016 if !have_aomenc() {
15017 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
15018 return;
15019 }
15020 let mut refusals = Vec::new();
15021 let mut never_fired = 0u32;
15022 for attempt in 0..attempts {
15023 let seed = 42 + attempt % 40;
15024 let duration = frame_count as f64 / 25.0;
15025 let source =
15026 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
15027 let y4m = Command::new("ffmpeg")
15028 .args([
15029 "-v",
15030 "error",
15031 "-f",
15032 "lavfi",
15033 "-i",
15034 &source,
15035 "-pix_fmt",
15036 "yuv420p",
15037 "-f",
15038 "yuv4mpegpipe",
15039 "-",
15040 ])
15041 .stdin(Stdio::null())
15042 .stdout(Stdio::piped())
15043 .stderr(Stdio::piped())
15044 .output()
15045 .expect("ffmpeg failed to run");
15046 assert!(
15047 y4m.status.success(),
15048 "ffmpeg fixture: {}",
15049 String::from_utf8_lossy(&y4m.stderr)
15050 );
15051 let mut args: Vec<&str> = vec![
15052 "--codec=av1",
15053 "--passes=1",
15054 "--end-usage=q",
15055 "--cq-level=55",
15056 "--cpu-used=0",
15057 "--kf-max-dist=1000",
15058 "--threads=1",
15059 "--row-mt=0",
15060 "--enable-warped-motion=0",
15061 "--enable-obmc=0",
15062 "--enable-masked-comp=0",
15063 "--enable-interintra-comp=0",
15064 "--enable-dist-wtd-comp=0",
15065 "--enable-diff-wtd-comp=0",
15066 "--enable-onesided-comp=0",
15067 "--enable-interintra-wedge=0",
15068 "--enable-smooth-interintra=0",
15069 "--enable-rect-partitions=0",
15070 "--enable-ab-partitions=0",
15071 "--enable-1to4-partitions=0",
15072 "--enable-filter-intra=0",
15073 "--enable-smooth-intra=0",
15074 "--enable-paeth-intra=0",
15075 "--enable-directional-intra=0",
15076 "--enable-angle-delta=0",
15077 "--enable-tx-size-search=0",
15078 "--enable-cdef=0",
15079 "--enable-restoration=0",
15080 "--max-partition-size=32",
15081 "--min-partition-size=32",
15082 "--enable-palette=0",
15083 "--enable-intrabc=0",
15084 "--enable-cfl-intra=0",
15085 // use_ref_frame_mvs (temporal MV projection) is unimplemented in
15086 // mvstack; leaving it on silently desyncs symbols on inter frames.
15087 "--enable-ref-frame-mvs=0",
15088 "--obu",
15089 "-o",
15090 "-",
15091 "-",
15092 ];
15093 // extra_args goes right before the trailing "-o", "-", "-" triple.
15094 let tail = args.split_off(args.len() - 3);
15095 args.extend_from_slice(extra_args);
15096 args.extend_from_slice(&tail);
15097 let mut child = Command::new(aomenc_path())
15098 .args(&args)
15099 .stdin(Stdio::piped())
15100 .stdout(Stdio::piped())
15101 .stderr(Stdio::piped())
15102 .spawn()
15103 .expect("aomenc failed to start");
15104 child
15105 .stdin
15106 .take()
15107 .expect("aomenc stdin")
15108 .write_all(&y4m.stdout)
15109 .expect("writing y4m to aomenc");
15110 let out = child.wait_with_output().expect("aomenc failed to run");
15111 assert!(
15112 out.status.success(),
15113 "aomenc refused the fixture: {}",
15114 String::from_utf8_lossy(&out.stderr)
15115 );
15116 let stream = out.stdout;
15117 let before = decode::ref_hits(target_ref);
15118 let frames = match decode_stream(&stream) {
15119 Err(e) => {
15120 let msg = e.to_string();
15121 assert!(
15122 msg.contains("unsupported"),
15123 "{gate_name} failed outright (seed {seed}): {msg}"
15124 );
15125 refusals.push(format!("seed {seed}: {msg}"));
15126 continue;
15127 }
15128 Ok(frames) => frames,
15129 };
15130 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
15131 // is ALWAYS pixel-compared below; the hit counter only decides whether
15132 // the attempt counts toward the firing total.
15133 let counted = decode::ref_hits(target_ref) != before;
15134 if !counted {
15135 never_fired += 1;
15136 }
15137 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
15138 assert_eq!(frames.len(), frame_count);
15139 let mismatched = frames
15140 .iter()
15141 .zip(&ffmpeg_frames)
15142 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
15143 if mismatched {
15144 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
15145 std::fs::write(&path, &stream).expect("writing pinned stream");
15146 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
15147 }
15148 }
15149 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15150 assert_eq!(
15151 got.y, want.y,
15152 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
15153 );
15154 assert_eq!(
15155 got.u, want.u,
15156 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
15157 );
15158 assert_eq!(
15159 got.v, want.v,
15160 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
15161 );
15162 }
15163 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
15164 // stream again, comparing EVERY decode-order frame -- the hidden
15165 // (show_frame == 0) alt-ref frames the ffmpeg compare above
15166 // cannot see, because both sides of it emit shown frames only.
15167 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, gate_name);
15168 eprintln!(
15169 "{gate_name} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
15170 {hidden_n} hidden, all pixel-exact vs the oracle"
15171 );
15172 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
15173 // libaom's temporal alt-ref filter absorbs this recipe's hidden
15174 // frames, so the compare above is vacuous -- re-encode the same
15175 // fixture with --arnr-maxframes=0 and compare THOSE.
15176 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(gate_name, &y4m.stdout, &args) {
15177 eprintln!(
15178 "{gate_name} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
15179 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
15180 );
15181 }
15182 if counted {
15183 eprintln!(
15184 "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}",
15185 decode::ref_hits(target_ref) - before
15186 );
15187 gate_buckets(gate_name, 1, never_fired, refusals.len());
15188 return;
15189 }
15190 }
15191 gate_buckets(gate_name, 0, never_fired, refusals.len());
15192 eprintln!(
15193 "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \
15194 and every other attempt hit a named refusal:\n{}",
15195 refusals.join("\n")
15196 );
15197 }
15198
15199 /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read
15200 /// off a real bitstream rather than only unit-tested in isolation --
15201 /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward
15202 /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1`
15203 /// is required for it to ever consider compound at all. Three
15204 /// acceptable outcomes: (a) a stream where `reference_select` never
15205 /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end
15206 /// to end (proving the per-block `comp_mode` read did not desync the
15207 /// single-ref blocks around it); (b) a stream that does fire compound
15208 /// is refused by name with [`decode::comp_mode_hits`] having advanced
15209 /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right
15210 /// symbols before refusing, rather than desyncing and refusing for an
15211 /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`)
15212 /// and a partition below 16x16 (a real, separately tracked capability
15213 /// gap) are the two refusal arms this can still legitimately name; (c)
15214 /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a
15215 /// stream that fires compound may also decode fully -- accepted only
15216 /// when every output frame is pixel-exact against ffmpeg.
15217 #[test]
15218 fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() {
15219 const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly";
15220 let _gate_lock = lock_gate_counters();
15221 if !have_ffmpeg() {
15222 eprintln!("SKIP {NAME}: no ffmpeg");
15223 return;
15224 }
15225 if !have_aomenc() {
15226 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15227 return;
15228 }
15229 let (width, height, frame_count) = (64usize, 64usize, 20usize);
15230 let mut refusals = Vec::new();
15231 let mut never_fired = 0u32;
15232 for attempt in 0..60u32 {
15233 let seed = 42 + attempt % 40;
15234 let duration = frame_count as f64 / 25.0;
15235 let source =
15236 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
15237 let y4m = Command::new("ffmpeg")
15238 .args([
15239 "-v",
15240 "error",
15241 "-f",
15242 "lavfi",
15243 "-i",
15244 &source,
15245 "-pix_fmt",
15246 "yuv420p",
15247 "-f",
15248 "yuv4mpegpipe",
15249 "-",
15250 ])
15251 .stdin(Stdio::null())
15252 .stdout(Stdio::piped())
15253 .stderr(Stdio::piped())
15254 .output()
15255 .expect("ffmpeg failed to run");
15256 assert!(
15257 y4m.status.success(),
15258 "ffmpeg fixture: {}",
15259 String::from_utf8_lossy(&y4m.stderr)
15260 );
15261 let args: Vec<&str> = vec![
15262 "--codec=av1",
15263 "--passes=1",
15264 "--end-usage=q",
15265 "--cq-level=45",
15266 "--cpu-used=0",
15267 "--kf-max-dist=1000",
15268 "--threads=1",
15269 "--row-mt=0",
15270 "--auto-alt-ref=1",
15271 "--lag-in-frames=16",
15272 "--enable-order-hint=1",
15273 "--enable-warped-motion=0",
15274 "--enable-obmc=0",
15275 "--enable-masked-comp=0",
15276 "--enable-interintra-comp=0",
15277 "--enable-onesided-comp=0",
15278 "--enable-interintra-wedge=0",
15279 "--enable-smooth-interintra=0",
15280 "--enable-rect-partitions=0",
15281 "--enable-ab-partitions=0",
15282 "--enable-1to4-partitions=0",
15283 "--enable-filter-intra=0",
15284 "--enable-smooth-intra=0",
15285 "--enable-paeth-intra=0",
15286 "--enable-directional-intra=0",
15287 "--enable-angle-delta=0",
15288 "--enable-tx-size-search=0",
15289 "--enable-cdef=0",
15290 "--enable-restoration=0",
15291 "--max-partition-size=32",
15292 "--min-partition-size=32",
15293 "--enable-palette=0",
15294 "--enable-intrabc=0",
15295 "--enable-cfl-intra=0",
15296 "--enable-ref-frame-mvs=0",
15297 "--obu",
15298 "-o",
15299 "-",
15300 "-",
15301 ];
15302 let mut child = Command::new(aomenc_path())
15303 .args(&args)
15304 .stdin(Stdio::piped())
15305 .stdout(Stdio::piped())
15306 .stderr(Stdio::piped())
15307 .spawn()
15308 .expect("aomenc failed to start");
15309 child
15310 .stdin
15311 .take()
15312 .expect("aomenc stdin")
15313 .write_all(&y4m.stdout)
15314 .expect("writing y4m to aomenc");
15315 let out = child.wait_with_output().expect("aomenc failed to run");
15316 assert!(
15317 out.status.success(),
15318 "aomenc refused the fixture: {}",
15319 String::from_utf8_lossy(&out.stderr)
15320 );
15321 let stream = out.stdout;
15322 let before = decode::comp_mode_hits();
15323 match decode_stream(&stream) {
15324 Err(e) => {
15325 let msg = e.to_string();
15326 let fired = decode::comp_mode_hits() > before;
15327 assert!(
15328 msg.contains("unsupported"),
15329 "{NAME} failed outright (seed {seed}): {msg}"
15330 );
15331 if fired {
15332 // `comp_mode` firing does not stop the block walk --
15333 // a later, unrelated block in the same tile can
15334 // still hit any other named refusal this decoder
15335 // carries. A partition below 16x16 is a real, open
15336 // capability gap tracked on its own (not a
15337 // COMPOUND_REFERENCE defect); accept it here too
15338 // rather than fail a compound-specific gate on a
15339 // partition-search coincidence. lane-av1blend r7:
15340 // re-swept the wide gate with the plain-average
15341 // blend unmasked (r6/r7's ref_ctx fix alone) and it
15342 // still mismatches on real streams beyond that one
15343 // bug -- re-masked comp_group_idx == 0 too, so this
15344 // stays a legal named refusal.
15345 assert!(
15346 msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"),
15347 "{NAME}: comp_mode fired (seed {seed}) but the refusal \
15348 was for something else: {msg}"
15349 );
15350 let advanced = decode::comp_mode_hits() - before;
15351 eprintln!(
15352 "{NAME} FIRING seed {seed}: comp_mode hits advanced by \
15353 {advanced}, refused by name as expected: {msg}"
15354 );
15355 return;
15356 }
15357 refusals.push(format!("seed {seed}: {msg}"));
15358 continue;
15359 }
15360 Ok(frames) => {
15361 // class [[gate-skips-on-its-own-failure]]: a decode that
15362 // succeeded is ALWAYS pixel-compared below; the hit counter
15363 // only decides whether the attempt counts as firing.
15364 let counted = decode::comp_mode_hits() != before;
15365 if !counted {
15366 never_fired += 1;
15367 }
15368 // Outcome (c): plain COMPOUND_AVERAGE decoded fully --
15369 // non-negotiable pixel exactness, no tolerance.
15370 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
15371 assert_eq!(frames.len(), frame_count);
15372 let mismatched = frames
15373 .iter()
15374 .zip(&ffmpeg_frames)
15375 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
15376 if mismatched {
15377 let pin = std::env::temp_dir().join("ec-av1-reference-select-gate-fail.obu");
15378 let _ = std::fs::write(&pin, &stream);
15379 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
15380 std::fs::write(&path, &stream).expect("writing pinned stream");
15381 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
15382 }
15383 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15384 assert_eq!(
15385 got.y, want.y,
15386 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
15387 pin.display()
15388 );
15389 assert_eq!(
15390 got.u, want.u,
15391 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
15392 pin.display()
15393 );
15394 assert_eq!(
15395 got.v, want.v,
15396 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
15397 pin.display()
15398 );
15399 }
15400 } else {
15401 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15402 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
15403 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
15404 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
15405 }
15406 }
15407 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
15408 // stream again, comparing EVERY decode-order frame -- the hidden
15409 // (show_frame == 0) alt-ref frames the ffmpeg compare above
15410 // cannot see, because both sides of it emit shown frames only.
15411 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
15412 eprintln!(
15413 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
15414 {hidden_n} hidden, all pixel-exact vs the oracle"
15415 );
15416 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
15417 // libaom's temporal alt-ref filter absorbs this recipe's hidden
15418 // frames, so the compare above is vacuous -- re-encode the same
15419 // fixture with --arnr-maxframes=0 and compare THOSE.
15420 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
15421 eprintln!(
15422 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
15423 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
15424 );
15425 }
15426 if counted {
15427 eprintln!(
15428 "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \
15429 fully and pixel-exact",
15430 decode::comp_mode_hits() - before
15431 );
15432 gate_buckets(NAME, 1, never_fired, refusals.len());
15433 return;
15434 }
15435 }
15436 }
15437 }
15438 gate_buckets(NAME, 0, never_fired, refusals.len());
15439 eprintln!(
15440 "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \
15441 block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \
15442 reached comp_mode:\n{}",
15443 refusals.join("\n")
15444 );
15445 }
15446
15447 /// lane-av1comp round 14's decisive gate for `skip_mode`: same
15448 /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving
15449 /// [`decode::skip_mode_hits`] actually advanced (a real block picked
15450 /// `skip_mode`, not just that the frame header bit was set) and that the
15451 /// resulting forced-compound `NEAREST_NEARESTMV` decode is still
15452 /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16
15453 /// --enable-fwd-kf=0` (backward references) plus
15454 /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection,
15455 /// same as every other gate here) is aomenc's own requirement for
15456 /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs
15457 /// both a forward and a backward reference candidate).
15458 #[test]
15459 fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() {
15460 const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact";
15461 let _gate_lock = lock_gate_counters();
15462 if !have_ffmpeg() {
15463 eprintln!("SKIP {NAME}: no ffmpeg");
15464 return;
15465 }
15466 if !have_aomenc() {
15467 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15468 return;
15469 }
15470 let (width, height, frame_count) = (64usize, 64usize, 24usize);
15471 let mut refusals = Vec::new();
15472 let mut never_fired = 0u32;
15473 for attempt in 0..80u32 {
15474 let seed = 42 + attempt % 40;
15475 let duration = frame_count as f64 / 25.0;
15476 let source =
15477 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
15478 let y4m = Command::new("ffmpeg")
15479 .args([
15480 "-v",
15481 "error",
15482 "-f",
15483 "lavfi",
15484 "-i",
15485 &source,
15486 "-pix_fmt",
15487 "yuv420p",
15488 "-f",
15489 "yuv4mpegpipe",
15490 "-",
15491 ])
15492 .stdin(Stdio::null())
15493 .stdout(Stdio::piped())
15494 .stderr(Stdio::piped())
15495 .output()
15496 .expect("ffmpeg failed to run");
15497 assert!(
15498 y4m.status.success(),
15499 "ffmpeg fixture: {}",
15500 String::from_utf8_lossy(&y4m.stderr)
15501 );
15502 let args: Vec<&str> = vec![
15503 "--codec=av1",
15504 "--passes=1",
15505 "--end-usage=q",
15506 "--cq-level=45",
15507 "--cpu-used=0",
15508 "--kf-max-dist=1000",
15509 "--threads=1",
15510 "--row-mt=0",
15511 "--auto-alt-ref=1",
15512 "--lag-in-frames=16",
15513 "--enable-fwd-kf=0",
15514 "--enable-order-hint=1",
15515 "--enable-warped-motion=0",
15516 "--enable-obmc=0",
15517 "--enable-masked-comp=0",
15518 "--enable-interintra-comp=0",
15519 "--enable-onesided-comp=0",
15520 "--enable-interintra-wedge=0",
15521 "--enable-smooth-interintra=0",
15522 "--enable-rect-partitions=0",
15523 "--enable-ab-partitions=0",
15524 "--enable-1to4-partitions=0",
15525 "--enable-filter-intra=0",
15526 "--enable-smooth-intra=0",
15527 "--enable-paeth-intra=0",
15528 "--enable-directional-intra=0",
15529 "--enable-angle-delta=0",
15530 "--enable-tx-size-search=0",
15531 "--enable-cdef=0",
15532 "--enable-restoration=0",
15533 "--max-partition-size=32",
15534 "--min-partition-size=32",
15535 "--enable-palette=0",
15536 "--enable-intrabc=0",
15537 "--enable-cfl-intra=0",
15538 "--enable-ref-frame-mvs=0",
15539 "--obu",
15540 "-o",
15541 "-",
15542 "-",
15543 ];
15544 let mut child = Command::new(aomenc_path())
15545 .args(&args)
15546 .stdin(Stdio::piped())
15547 .stdout(Stdio::piped())
15548 .stderr(Stdio::piped())
15549 .spawn()
15550 .expect("aomenc failed to start");
15551 child
15552 .stdin
15553 .take()
15554 .expect("aomenc stdin")
15555 .write_all(&y4m.stdout)
15556 .expect("writing y4m to aomenc");
15557 let out = child.wait_with_output().expect("aomenc failed to run");
15558 assert!(
15559 out.status.success(),
15560 "aomenc refused the fixture: {}",
15561 String::from_utf8_lossy(&out.stderr)
15562 );
15563 let stream = out.stdout;
15564 let before = decode::skip_mode_hits();
15565 let frames = match decode_stream(&stream) {
15566 Err(e) => {
15567 let msg = e.to_string();
15568 assert!(
15569 msg.contains("unsupported"),
15570 "{NAME} failed outright (seed {seed}): {msg}"
15571 );
15572 refusals.push(format!("seed {seed}: {msg}"));
15573 continue;
15574 }
15575 Ok(frames) => frames,
15576 };
15577 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
15578 // is ALWAYS pixel-compared below; the hit counter only decides whether
15579 // the attempt counts toward the firing total.
15580 let counted = decode::skip_mode_hits() != before;
15581 if !counted {
15582 never_fired += 1;
15583 }
15584 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
15585 assert_eq!(frames.len(), frame_count);
15586 let mismatched = frames
15587 .iter()
15588 .zip(&ffmpeg_frames)
15589 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
15590 if mismatched {
15591 let pin = std::env::temp_dir().join("ec-av1-compound-refs-gate-fail.obu");
15592 let _ = std::fs::write(&pin, &stream);
15593 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
15594 std::fs::write(&path, &stream).expect("writing pinned stream");
15595 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
15596 }
15597 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15598 assert_eq!(
15599 got.y, want.y,
15600 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
15601 pin.display()
15602 );
15603 assert_eq!(
15604 got.u, want.u,
15605 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
15606 pin.display()
15607 );
15608 assert_eq!(
15609 got.v, want.v,
15610 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
15611 pin.display()
15612 );
15613 }
15614 }
15615 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
15616 // stream again, comparing EVERY decode-order frame -- the hidden
15617 // (show_frame == 0) alt-ref frames the ffmpeg compare above
15618 // cannot see, because both sides of it emit shown frames only.
15619 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
15620 eprintln!(
15621 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
15622 {hidden_n} hidden, all pixel-exact vs the oracle"
15623 );
15624 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
15625 // libaom's temporal alt-ref filter absorbs this recipe's hidden
15626 // frames, so the compare above is vacuous -- re-encode the same
15627 // fixture with --arnr-maxframes=0 and compare THOSE.
15628 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
15629 eprintln!(
15630 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
15631 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
15632 );
15633 }
15634 if counted {
15635 eprintln!(
15636 "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}",
15637 decode::skip_mode_hits() - before
15638 );
15639 gate_buckets(NAME, 1, never_fired, refusals.len());
15640 return;
15641 }
15642 }
15643 gate_buckets(NAME, 0, never_fired, refusals.len());
15644 eprintln!(
15645 "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \
15646 other attempt hit a named refusal:\n{}",
15647 refusals.join("\n")
15648 );
15649 }
15650
15651 /// lane-motionmode round 1: `--enable-obmc=1 --enable-warped-motion=0`
15652 /// on the base recipe (`--auto-alt-ref=1 --lag-in-frames=16
15653 /// --enable-fwd-kf=0 --enable-ref-frame-mvs=0`) -- pixel-exact against
15654 /// ffmpeg, gated on [`decode::obmc_hits`] actually advancing (a real
15655 /// block picked `OBMC_CAUSAL`, not just that the header bit was set).
15656 /// Structure copied from
15657 /// `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`:
15658 /// a seed sweep with a named-refusal escape hatch and an
15659 /// `EC_AV1_GATE_DUMP` pin on mismatch.
15660 #[test]
15661 fn a_real_aomenc_stream_with_obmc_decodes_pixel_exact() {
15662 const NAME: &str = "a_real_aomenc_stream_with_obmc_decodes_pixel_exact";
15663 let _gate_lock = lock_gate_counters();
15664 if !have_ffmpeg() {
15665 eprintln!("SKIP {NAME}: no ffmpeg");
15666 return;
15667 }
15668 if !have_aomenc() {
15669 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15670 return;
15671 }
15672 let (width, height, frame_count) = (64usize, 64usize, 24usize);
15673 let mut refusals = Vec::new();
15674 let mut never_fired = 0u32;
15675 for attempt in 0..80u32 {
15676 let seed = 42 + attempt % 40;
15677 let duration = frame_count as f64 / 25.0;
15678 let source =
15679 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
15680 let y4m = Command::new("ffmpeg")
15681 .args([
15682 "-v",
15683 "error",
15684 "-f",
15685 "lavfi",
15686 "-i",
15687 &source,
15688 "-pix_fmt",
15689 "yuv420p",
15690 "-f",
15691 "yuv4mpegpipe",
15692 "-",
15693 ])
15694 .stdin(Stdio::null())
15695 .stdout(Stdio::piped())
15696 .stderr(Stdio::piped())
15697 .output()
15698 .expect("ffmpeg failed to run");
15699 assert!(
15700 y4m.status.success(),
15701 "ffmpeg fixture: {}",
15702 String::from_utf8_lossy(&y4m.stderr)
15703 );
15704 let args: Vec<&str> = vec![
15705 "--codec=av1",
15706 "--passes=1",
15707 "--end-usage=q",
15708 "--cq-level=45",
15709 "--cpu-used=0",
15710 "--kf-max-dist=1000",
15711 "--threads=1",
15712 "--row-mt=0",
15713 "--auto-alt-ref=1",
15714 "--lag-in-frames=16",
15715 "--enable-fwd-kf=0",
15716 "--enable-order-hint=1",
15717 "--enable-warped-motion=0",
15718 "--enable-obmc=1",
15719 "--enable-masked-comp=0",
15720 "--enable-interintra-comp=0",
15721 "--enable-onesided-comp=0",
15722 "--enable-interintra-wedge=0",
15723 "--enable-smooth-interintra=0",
15724 "--enable-rect-partitions=0",
15725 "--enable-ab-partitions=0",
15726 "--enable-1to4-partitions=0",
15727 "--enable-filter-intra=0",
15728 "--enable-smooth-intra=0",
15729 "--enable-paeth-intra=0",
15730 "--enable-directional-intra=0",
15731 "--enable-angle-delta=0",
15732 "--enable-tx-size-search=0",
15733 "--enable-cdef=0",
15734 "--enable-restoration=0",
15735 "--max-partition-size=32",
15736 "--min-partition-size=32",
15737 "--enable-palette=0",
15738 "--enable-intrabc=0",
15739 "--enable-cfl-intra=0",
15740 "--enable-ref-frame-mvs=0",
15741 "--obu",
15742 "-o",
15743 "-",
15744 "-",
15745 ];
15746 let mut child = Command::new(aomenc_path())
15747 .args(&args)
15748 .stdin(Stdio::piped())
15749 .stdout(Stdio::piped())
15750 .stderr(Stdio::piped())
15751 .spawn()
15752 .expect("aomenc failed to start");
15753 child
15754 .stdin
15755 .take()
15756 .expect("aomenc stdin")
15757 .write_all(&y4m.stdout)
15758 .expect("writing y4m to aomenc");
15759 let out = child.wait_with_output().expect("aomenc failed to run");
15760 assert!(
15761 out.status.success(),
15762 "aomenc refused the fixture: {}",
15763 String::from_utf8_lossy(&out.stderr)
15764 );
15765 let stream = out.stdout;
15766 let before = decode::obmc_hits();
15767 let frames = match decode_stream(&stream) {
15768 Err(e) => {
15769 let msg = e.to_string();
15770 assert!(
15771 msg.contains("unsupported"),
15772 "{NAME} failed outright (seed {seed}): {msg}"
15773 );
15774 refusals.push(format!("seed {seed}: {msg}"));
15775 continue;
15776 }
15777 Ok(frames) => frames,
15778 };
15779 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
15780 // is ALWAYS pixel-compared below; the hit counter only decides whether
15781 // the attempt counts toward the firing total.
15782 let counted = decode::obmc_hits() != before;
15783 if !counted {
15784 never_fired += 1;
15785 }
15786 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
15787 assert_eq!(frames.len(), frame_count);
15788 let mismatched = frames
15789 .iter()
15790 .zip(&ffmpeg_frames)
15791 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
15792 if mismatched {
15793 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
15794 std::fs::write(&path, &stream).expect("writing pinned stream");
15795 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
15796 }
15797 }
15798 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15799 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
15800 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
15801 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
15802 }
15803 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
15804 // stream again, comparing EVERY decode-order frame -- the hidden
15805 // (show_frame == 0) alt-ref frames the ffmpeg compare above
15806 // cannot see, because both sides of it emit shown frames only.
15807 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
15808 eprintln!(
15809 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
15810 {hidden_n} hidden, all pixel-exact vs the oracle"
15811 );
15812 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
15813 // libaom's temporal alt-ref filter absorbs this recipe's hidden
15814 // frames, so the compare above is vacuous -- re-encode the same
15815 // fixture with --arnr-maxframes=0 and compare THOSE.
15816 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
15817 eprintln!(
15818 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
15819 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
15820 );
15821 }
15822 if counted {
15823 eprintln!(
15824 "{NAME} FIRING seed {seed}: obmc hits advanced by {}",
15825 decode::obmc_hits() - before
15826 );
15827 gate_buckets(NAME, 1, never_fired, refusals.len());
15828 return;
15829 }
15830 }
15831 gate_buckets(NAME, 0, never_fired, refusals.len());
15832 eprintln!(
15833 "SKIP {NAME}: {never_fired} attempts decoded but never fired obmc, and every \
15834 other attempt hit a named refusal:\n{}",
15835 refusals.join("\n")
15836 );
15837 }
15838
15839 /// lane-motionmode round 3: same shape as
15840 /// `a_real_aomenc_stream_with_obmc_decodes_pixel_exact`, but relaxed the
15841 /// `--min-partition-size=32 --max-partition-size=32` clamp (that other
15842 /// gate's own doc: locked to remove partition-depth choice from the
15843 /// search entirely) to `8`/`32`, to make an 8x8-leaf `OBMC_CAUSAL` pick
15844 /// possible at all. Gated on [`decode::obmc_hits_8`] specifically, not
15845 /// the aggregate [`decode::obmc_hits`]. Measured live (round 3, this
15846 /// box): 80 attempts, 0 ever called `decode_inter_block8` at all --
15847 /// `cpu-used=0`'s RD search never once splits a 16x16 down to a clean
15848 /// 4-way 8x8 leaf for this smooth `gradients` fixture (large blocks
15849 /// always win the RD cost there); the handful of named refusals seen
15850 /// are `PARTITION_SPLIT` chosen *at* 8x8 (down to 4x4, already refused
15851 /// at `decode.rs`'s `part8 != PARTITION_NONE` check) or
15852 /// `allow_screen_content_tools`, neither reaching a leaf. Kept anyway
15853 /// (mirrors this file's own `never_fired`-skip convention) as the
15854 /// honest record of the attempt; a real 8x8 OBMC fixture needs
15855 /// higher-frequency content than this gate's fixtures use, out of
15856 /// round-3 budget.
15857 #[test]
15858 fn a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact() {
15859 const NAME: &str = "a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact";
15860 let _gate_lock = lock_gate_counters();
15861 if !have_ffmpeg() {
15862 eprintln!("SKIP {NAME}: no ffmpeg");
15863 return;
15864 }
15865 if !have_aomenc() {
15866 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15867 return;
15868 }
15869 let (width, height, frame_count) = (64usize, 64usize, 24usize);
15870 let mut refusals = Vec::new();
15871 let mut never_fired = 0u32;
15872 let mut total_obmc8 = 0usize;
15873 let n_attempts: u32 = std::env::var("EC_OBMC8_ATTEMPTS")
15874 .ok()
15875 .and_then(|s| s.parse().ok())
15876 .unwrap_or(80);
15877 for attempt in 0..n_attempts {
15878 let seed = 42 + attempt % 40;
15879 let duration = frame_count as f64 / 25.0;
15880 // Recipe search hook: `gradients` is smooth, so aomenc's RD never
15881 // splits below 16x16 and this gate never fired one 8x8 OBMC block
15882 // in 45 attempts -- it "passed" by skipping (gate-blind-to-feature).
15883 // EC_AV1_OBMC8_SOURCE overrides the lavfi source so a firing recipe
15884 // can be searched for without a rebuild.
15885 let source = std::env::var("EC_AV1_OBMC8_SOURCE").unwrap_or_else(|_| {
15886 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
15887 });
15888 // A source supplied through EC_AV1_OBMC8_SOURCE need not carry its
15889 // own `duration=`; `-t` is the bound that always holds. Without it
15890 // an endless source (`testsrc2`) fills the pipe forever and the
15891 // gate hangs to its 300 s timeout.
15892 let duration_arg = format!("{duration}");
15893 let y4m = Command::new("ffmpeg")
15894 .args([
15895 "-v",
15896 "error",
15897 "-f",
15898 "lavfi",
15899 "-i",
15900 &source,
15901 "-t",
15902 &duration_arg,
15903 "-pix_fmt",
15904 "yuv420p",
15905 "-f",
15906 "yuv4mpegpipe",
15907 "-",
15908 ])
15909 .stdin(Stdio::null())
15910 .stdout(Stdio::piped())
15911 .stderr(Stdio::piped())
15912 .output()
15913 .expect("ffmpeg failed to run");
15914 assert!(
15915 y4m.status.success(),
15916 "ffmpeg fixture: {}",
15917 String::from_utf8_lossy(&y4m.stderr)
15918 );
15919 let args: Vec<&str> = vec![
15920 "--codec=av1",
15921 "--passes=1",
15922 "--end-usage=q",
15923 "--cq-level=45",
15924 "--cpu-used=0",
15925 "--kf-max-dist=1000",
15926 "--threads=1",
15927 "--row-mt=0",
15928 "--auto-alt-ref=1",
15929 "--lag-in-frames=16",
15930 "--enable-fwd-kf=0",
15931 "--enable-order-hint=1",
15932 "--enable-warped-motion=0",
15933 "--enable-obmc=1",
15934 "--enable-masked-comp=0",
15935 "--enable-interintra-comp=0",
15936 "--enable-onesided-comp=0",
15937 "--enable-interintra-wedge=0",
15938 "--enable-smooth-interintra=0",
15939 "--enable-rect-partitions=0",
15940 "--enable-ab-partitions=0",
15941 "--enable-1to4-partitions=0",
15942 "--enable-filter-intra=0",
15943 "--enable-smooth-intra=0",
15944 "--enable-paeth-intra=0",
15945 "--enable-directional-intra=0",
15946 "--enable-angle-delta=0",
15947 "--enable-tx-size-search=0",
15948 "--enable-cdef=0",
15949 "--enable-restoration=0",
15950 "--min-partition-size=8",
15951 "--max-partition-size=32",
15952 "--enable-palette=0",
15953 "--enable-intrabc=0",
15954 "--enable-cfl-intra=0",
15955 "--enable-ref-frame-mvs=0",
15956 "--obu",
15957 "-o",
15958 "-",
15959 "-",
15960 ];
15961 let mut child = Command::new(aomenc_path())
15962 .args(&args)
15963 .stdin(Stdio::piped())
15964 .stdout(Stdio::piped())
15965 .stderr(Stdio::piped())
15966 .spawn()
15967 .expect("aomenc failed to start");
15968 child
15969 .stdin
15970 .take()
15971 .expect("aomenc stdin")
15972 .write_all(&y4m.stdout)
15973 .expect("writing y4m to aomenc");
15974 let out = child.wait_with_output().expect("aomenc failed to run");
15975 assert!(
15976 out.status.success(),
15977 "aomenc refused the fixture: {}",
15978 String::from_utf8_lossy(&out.stderr)
15979 );
15980 let stream = out.stdout;
15981 let before8 = decode::obmc_hits_8();
15982 let frames = match decode_stream(&stream) {
15983 Err(e) => {
15984 let msg = e.to_string();
15985 assert!(
15986 msg.contains("unsupported"),
15987 "{NAME} failed outright (seed {seed}): {msg}"
15988 );
15989 refusals.push(format!("seed {seed}: {msg}"));
15990 continue;
15991 }
15992 Ok(frames) => frames,
15993 };
15994 let fired8 = decode::obmc_hits_8() - before8;
15995 total_obmc8 += fired8;
15996 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
15997 // is ALWAYS pixel-compared below; the hit counter only decides whether
15998 // the attempt counts toward the firing total.
15999 let counted = fired8 != 0;
16000 if !counted {
16001 never_fired += 1;
16002 }
16003 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
16004 assert_eq!(frames.len(), frame_count);
16005 let mismatched = frames
16006 .iter()
16007 .zip(&ffmpeg_frames)
16008 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16009 if mismatched {
16010 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
16011 std::fs::write(&path, &stream).expect("writing pinned stream");
16012 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
16013 }
16014 }
16015 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16016 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
16017 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
16018 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
16019 }
16020 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
16021 // stream again, comparing EVERY decode-order frame -- the hidden
16022 // (show_frame == 0) alt-ref frames the ffmpeg compare above
16023 // cannot see, because both sides of it emit shown frames only.
16024 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
16025 eprintln!(
16026 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
16027 {hidden_n} hidden, all pixel-exact vs the oracle"
16028 );
16029 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
16030 // libaom's temporal alt-ref filter absorbs this recipe's hidden
16031 // frames, so the compare above is vacuous -- re-encode the same
16032 // fixture with --arnr-maxframes=0 and compare THOSE.
16033 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
16034 eprintln!(
16035 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
16036 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
16037 );
16038 }
16039 if counted {
16040 eprintln!(
16041 "{NAME} FIRING seed {seed}: 8x8 obmc hits {fired8} (total across attempts so far {total_obmc8})"
16042 );
16043 gate_buckets(NAME, 1, never_fired, refusals.len());
16044 return;
16045 }
16046 }
16047 gate_buckets(NAME, 0, never_fired, refusals.len());
16048 // lane-gmaffine r2: this gate fired for three rounds only as a SKIP
16049 // (gate-skips-on-its-own-failure); the 8x8 leaf is reachable now, so a
16050 // sweep that never lands one firing pixel-exact attempt is a FAILURE.
16051 panic!(
16052 "{NAME}: {never_fired} attempts decoded but never fired an 8x8 obmc block \
16053 ({total_obmc8} total 8x8 obmc hits across all attempts), and every other attempt \
16054 hit a named refusal:\n{}",
16055 refusals.join("\n")
16056 );
16057 }
16058
16059 /// lane-warp r5e (flipped from lane-motionmode r1's refuses-or-matches):
16060 /// `--enable-warped-motion=1` streams must DECODE pixel-exact --
16061 /// `av1_findSamples`/`num_proj_ref`, the 3-symbol `motion_mode` read,
16062 /// the affine projection/filter, and the WARPED_CAUSAL interp-filter
16063 /// derivation are all ported. A refusal naming warp, or any pixel
16064 /// mismatch, fails the gate; refusals for OTHER named capabilities
16065 /// (screen content tools) still skip that seed. The sweep must also
16066 /// actually exercise warp (`warp_selected_hits > 0`) so a decoder that
16067 /// silently stops selecting WARPED_CAUSAL cannot pass vacuously.
16068 #[test]
16069 fn a_real_aomenc_stream_with_warped_motion_refuses_or_matches() {
16070 const NAME: &str = "a_real_aomenc_stream_with_warped_motion_refuses_or_matches";
16071 let _gate_lock = lock_gate_counters();
16072 if !have_ffmpeg() {
16073 eprintln!("SKIP {NAME}: no ffmpeg");
16074 return;
16075 }
16076 if !have_aomenc() {
16077 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16078 return;
16079 }
16080 let (width, height, frame_count) = (64usize, 64usize, 24usize);
16081 let mut named_refusals = 0u32;
16082 let mut matched = 0u32;
16083 let n_attempts: u32 = std::env::var("EC_WARP_GATE_ATTEMPTS")
16084 .ok()
16085 .and_then(|s| s.parse().ok())
16086 .unwrap_or(40);
16087 for attempt in 0..n_attempts {
16088 let seed = 42 + attempt;
16089 let duration = frame_count as f64 / 25.0;
16090 let source =
16091 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
16092 let y4m = Command::new("ffmpeg")
16093 .args([
16094 "-v",
16095 "error",
16096 "-f",
16097 "lavfi",
16098 "-i",
16099 &source,
16100 "-pix_fmt",
16101 "yuv420p",
16102 "-f",
16103 "yuv4mpegpipe",
16104 "-",
16105 ])
16106 .stdin(Stdio::null())
16107 .stdout(Stdio::piped())
16108 .stderr(Stdio::piped())
16109 .output()
16110 .expect("ffmpeg failed to run");
16111 assert!(
16112 y4m.status.success(),
16113 "ffmpeg fixture: {}",
16114 String::from_utf8_lossy(&y4m.stderr)
16115 );
16116 let args: Vec<&str> = vec![
16117 "--codec=av1",
16118 "--passes=1",
16119 "--end-usage=q",
16120 "--cq-level=45",
16121 "--cpu-used=0",
16122 "--kf-max-dist=1000",
16123 "--threads=1",
16124 "--row-mt=0",
16125 "--auto-alt-ref=1",
16126 "--lag-in-frames=16",
16127 "--enable-fwd-kf=0",
16128 "--enable-order-hint=1",
16129 "--enable-warped-motion=1",
16130 "--enable-obmc=1",
16131 "--tune-content=default",
16132 "--enable-masked-comp=0",
16133 "--enable-interintra-comp=0",
16134 "--enable-onesided-comp=0",
16135 "--enable-interintra-wedge=0",
16136 "--enable-smooth-interintra=0",
16137 "--enable-rect-partitions=0",
16138 "--enable-ab-partitions=0",
16139 "--enable-1to4-partitions=0",
16140 "--enable-filter-intra=0",
16141 "--enable-smooth-intra=0",
16142 "--enable-paeth-intra=0",
16143 "--enable-directional-intra=0",
16144 "--enable-angle-delta=0",
16145 "--enable-tx-size-search=0",
16146 "--enable-cdef=0",
16147 "--enable-restoration=0",
16148 "--max-partition-size=32",
16149 "--min-partition-size=32",
16150 "--enable-palette=0",
16151 "--enable-intrabc=0",
16152 "--enable-cfl-intra=0",
16153 "--enable-ref-frame-mvs=0",
16154 "--obu",
16155 "-o",
16156 "-",
16157 "-",
16158 ];
16159 let mut child = Command::new(aomenc_path())
16160 .args(&args)
16161 .stdin(Stdio::piped())
16162 .stdout(Stdio::piped())
16163 .stderr(Stdio::piped())
16164 .spawn()
16165 .expect("aomenc failed to start");
16166 child
16167 .stdin
16168 .take()
16169 .expect("aomenc stdin")
16170 .write_all(&y4m.stdout)
16171 .expect("writing y4m to aomenc");
16172 let out = child.wait_with_output().expect("aomenc failed to run");
16173 assert!(
16174 out.status.success(),
16175 "aomenc refused the fixture: {}",
16176 String::from_utf8_lossy(&out.stderr)
16177 );
16178 let stream = out.stdout;
16179 let frames = match decode_stream(&stream) {
16180 Err(e) => {
16181 let msg = e.to_string();
16182 assert!(
16183 msg.contains("unsupported"),
16184 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
16185 );
16186 assert!(
16187 !msg.contains("warp"),
16188 "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \
16189 refusal must not exist: {msg}"
16190 );
16191 named_refusals += 1;
16192 eprintln!("seed {seed} refusal (non-warp capability): {msg}");
16193 continue;
16194 }
16195 Ok(frames) => frames,
16196 };
16197 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
16198 assert_eq!(frames.len(), frame_count);
16199 let mismatched = frames
16200 .iter()
16201 .zip(&ffmpeg_frames)
16202 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16203 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
16204 std::fs::write(&path, &stream).expect("writing pinned stream");
16205 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
16206 }
16207 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16208 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
16209 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
16210 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
16211 }
16212 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
16213 // stream again, comparing EVERY decode-order frame -- the hidden
16214 // (show_frame == 0) alt-ref frames the ffmpeg compare above
16215 // cannot see, because both sides of it emit shown frames only.
16216 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
16217 eprintln!(
16218 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
16219 {hidden_n} hidden, all pixel-exact vs the oracle"
16220 );
16221 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
16222 // libaom's temporal alt-ref filter absorbs this recipe's hidden
16223 // frames, so the compare above is vacuous -- re-encode the same
16224 // fixture with --arnr-maxframes=0 and compare THOSE.
16225 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
16226 eprintln!(
16227 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
16228 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
16229 );
16230 }
16231 matched += 1;
16232 }
16233 assert!(
16234 matched > 0,
16235 "{NAME}: every attempt refused on other capabilities; the gate never exercised warp"
16236 );
16237 assert!(
16238 crate::decode::warp_selected_hits() > 0,
16239 "{NAME}: {matched} matches but zero WARPED_CAUSAL blocks fired -- the gate decodes \
16240 warp streams without ever selecting warp, so it proves nothing about warp"
16241 );
16242 eprintln!(
16243 "{NAME}: {named_refusals} non-warp refusals, {matched} pixel-exact matches out of {n_attempts}, warp_selected_hits={}",
16244 crate::decode::warp_selected_hits()
16245 );
16246 }
16247
16248 /// lane-superres stage 3: a real aomenc `--superres-mode=1` key-frame
16249 /// sequence must decode pixel-exact vs ffmpeg/dav1d's own upscaled
16250 /// output, and must actually run [`crate::superres::upscale_picture`]
16251 /// (`superres_hits > 0`) -- a decoder that silently stopped upscaling
16252 /// would otherwise pass vacuously (class `gate-blind-to-feature`).
16253 /// `--kf-max-dist` set to the frame count keeps every frame a key
16254 /// frame: inter-frame superres (a differently-scaled reference) is a
16255 /// later stage of this lane, refused by name today.
16256 #[test]
16257 fn a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact() {
16258 const NAME: &str = "a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact";
16259 let _gate_lock = lock_gate_counters();
16260 if !have_ffmpeg() {
16261 eprintln!("SKIP {NAME}: no ffmpeg");
16262 return;
16263 }
16264 if !have_aomenc() {
16265 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16266 return;
16267 }
16268 let (width, height, frame_count) = (64usize, 64usize, 3usize);
16269 let duration = frame_count as f64 / 25.0;
16270 let source = gradients_source(7, width, height, &format!("duration={duration}:rate=25"));
16271 let y4m = Command::new("ffmpeg")
16272 .args([
16273 "-v",
16274 "error",
16275 "-f",
16276 "lavfi",
16277 "-i",
16278 &source,
16279 "-pix_fmt",
16280 "yuv420p",
16281 "-f",
16282 "yuv4mpegpipe",
16283 "-",
16284 ])
16285 .stdin(Stdio::null())
16286 .stdout(Stdio::piped())
16287 .stderr(Stdio::piped())
16288 .output()
16289 .expect("ffmpeg failed to run");
16290 assert!(
16291 y4m.status.success(),
16292 "ffmpeg fixture: {}",
16293 String::from_utf8_lossy(&y4m.stderr)
16294 );
16295 let args: Vec<&str> = vec![
16296 "--codec=av1",
16297 "--passes=1",
16298 "--end-usage=q",
16299 "--cq-level=32",
16300 "--cpu-used=0",
16301 "--kf-max-dist=0",
16302 "--threads=1",
16303 "--row-mt=0",
16304 "--superres-mode=1",
16305 "--superres-denominator=12",
16306 "--superres-kf-denominator=12",
16307 "--enable-rect-partitions=0",
16308 "--enable-ab-partitions=0",
16309 "--enable-1to4-partitions=0",
16310 "--enable-filter-intra=0",
16311 "--enable-smooth-intra=0",
16312 "--enable-paeth-intra=0",
16313 "--enable-directional-intra=0",
16314 "--enable-angle-delta=0",
16315 "--enable-tx-size-search=0",
16316 "--enable-cdef=0",
16317 "--enable-restoration=0",
16318 "--max-partition-size=32",
16319 "--min-partition-size=32",
16320 "--enable-palette=0",
16321 "--enable-intrabc=0",
16322 "--enable-cfl-intra=0",
16323 "--obu",
16324 "-o",
16325 "-",
16326 "-",
16327 ];
16328 let mut child = Command::new(aomenc_path())
16329 .args(&args)
16330 .stdin(Stdio::piped())
16331 .stdout(Stdio::piped())
16332 .stderr(Stdio::piped())
16333 .spawn()
16334 .expect("aomenc failed to start");
16335 child
16336 .stdin
16337 .take()
16338 .expect("aomenc stdin")
16339 .write_all(&y4m.stdout)
16340 .expect("writing y4m to aomenc");
16341 let out = child.wait_with_output().expect("aomenc failed to run");
16342 assert!(
16343 out.status.success(),
16344 "aomenc refused the fixture: {}",
16345 String::from_utf8_lossy(&out.stderr)
16346 );
16347 let stream = out.stdout;
16348 if let Ok(path) = std::env::var("EC_SUPERRES_STREAM_DUMP") {
16349 std::fs::write(path, &stream).expect("dump stream");
16350 }
16351 let frames =
16352 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}"));
16353 assert_eq!(frames.len(), frame_count);
16354 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
16355 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16356 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
16357 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
16358 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
16359 }
16360 assert!(
16361 crate::superres::superres_hits() > 0,
16362 "{NAME}: matched but zero superres_hits -- the gate never actually exercised the \
16363 upscaler, it proves nothing"
16364 );
16365 eprintln!(
16366 "{NAME}: {frame_count} frames pixel-exact, superres_hits={}",
16367 crate::superres::superres_hits()
16368 );
16369 }
16370
16371 /// lane-superres r10: a real aomenc key+inter `--superres-mode=1`
16372 /// sequence must DECODE pixel-exact vs ffmpeg, with the frame-level
16373 /// `use_superres` refusal LIFTED for inter frames -- `mc::predict_scaled`
16374 /// (spec 7.11.3.3) is the only path this recipe can reach (warp/OBMC/
16375 /// compound/interintra/palette/intrabc/CDEF/LR are all off, matching the
16376 /// scoped refusals' own unimplemented list). A pixel match alone would
16377 /// pass just as well with an unscaled reference and prove nothing
16378 /// (class `gate-blind-to-feature`) -- hard-assert
16379 /// `crate::mc::predict_scaled_hits() > 0` so the gate can only pass if the
16380 /// scaled MC path actually ran.
16381 #[test]
16382 fn a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact() {
16383 const NAME: &str = "a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact";
16384 let _gate_lock = lock_gate_counters();
16385 if !have_ffmpeg() {
16386 eprintln!("SKIP {NAME}: no ffmpeg");
16387 return;
16388 }
16389 if !have_aomenc() {
16390 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16391 return;
16392 }
16393 let (width, height, frame_count) = (64usize, 64usize, 3usize);
16394 let duration = frame_count as f64 / 25.0;
16395 let source = gradients_source(11, width, height, &format!("duration={duration}:rate=25"));
16396 let y4m = Command::new("ffmpeg")
16397 .args([
16398 "-v",
16399 "error",
16400 "-f",
16401 "lavfi",
16402 "-i",
16403 &source,
16404 "-pix_fmt",
16405 "yuv420p",
16406 "-f",
16407 "yuv4mpegpipe",
16408 "-",
16409 ])
16410 .stdin(Stdio::null())
16411 .stdout(Stdio::piped())
16412 .stderr(Stdio::piped())
16413 .output()
16414 .expect("ffmpeg failed to run");
16415 assert!(
16416 y4m.status.success(),
16417 "ffmpeg fixture: {}",
16418 String::from_utf8_lossy(&y4m.stderr)
16419 );
16420 let args: Vec<&str> = vec![
16421 "--codec=av1",
16422 "--passes=1",
16423 "--end-usage=q",
16424 "--cq-level=32",
16425 "--cpu-used=0",
16426 // `--kf-max-dist` above `frame_count` keeps only frame 0 a key
16427 // frame -- frames 1/2 are the inter frames whose `use_superres`
16428 // refusal this round lifts.
16429 "--kf-max-dist=1000",
16430 "--lag-in-frames=0",
16431 "--auto-alt-ref=0",
16432 "--threads=1",
16433 "--row-mt=0",
16434 "--sb-size=64",
16435 "--superres-mode=1",
16436 "--superres-denominator=12",
16437 "--superres-kf-denominator=12",
16438 // Forces every inter block onto the single-ref, non-warp/OBMC/
16439 // interintra branch `decode_inter_block` threads `predict_scaled`
16440 // through -- the only branch this round's scoped refusals leave
16441 // unrefused under a scaled reference.
16442 "--enable-warped-motion=0",
16443 "--enable-obmc=0",
16444 "--enable-masked-comp=0",
16445 "--enable-interintra-comp=0",
16446 "--enable-dist-wtd-comp=0",
16447 "--enable-diff-wtd-comp=0",
16448 "--enable-onesided-comp=0",
16449 "--enable-interintra-wedge=0",
16450 "--enable-smooth-interintra=0",
16451 "--enable-order-hint=0",
16452 "--enable-ref-frame-mvs=0",
16453 "--enable-rect-partitions=0",
16454 "--enable-ab-partitions=0",
16455 "--enable-1to4-partitions=0",
16456 "--enable-filter-intra=0",
16457 "--enable-smooth-intra=0",
16458 "--enable-paeth-intra=0",
16459 "--enable-directional-intra=0",
16460 "--enable-angle-delta=0",
16461 "--enable-tx-size-search=0",
16462 "--enable-cdef=0",
16463 "--enable-restoration=0",
16464 "--max-partition-size=32",
16465 "--min-partition-size=32",
16466 "--enable-palette=0",
16467 "--enable-intrabc=0",
16468 "--enable-cfl-intra=0",
16469 "--obu",
16470 "-o",
16471 "-",
16472 "-",
16473 ];
16474 let mut child = Command::new(aomenc_path())
16475 .args(&args)
16476 .stdin(Stdio::piped())
16477 .stdout(Stdio::piped())
16478 .stderr(Stdio::piped())
16479 .spawn()
16480 .expect("aomenc failed to start");
16481 child
16482 .stdin
16483 .take()
16484 .expect("aomenc stdin")
16485 .write_all(&y4m.stdout)
16486 .expect("writing y4m to aomenc");
16487 let out = child.wait_with_output().expect("aomenc failed to run");
16488 assert!(
16489 out.status.success(),
16490 "aomenc refused the fixture: {}",
16491 String::from_utf8_lossy(&out.stderr)
16492 );
16493 let stream = out.stdout;
16494 if let Ok(path) = std::env::var("EC_SUPERRES_INTER_STREAM_DUMP") {
16495 std::fs::write(&path, &stream).expect("dump stream");
16496 }
16497 let frames =
16498 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}"));
16499 assert_eq!(frames.len(), frame_count);
16500 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
16501 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16502 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
16503 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
16504 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
16505 }
16506 assert!(
16507 crate::superres::superres_hits() > 0,
16508 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
16509 );
16510 assert!(
16511 crate::mc::predict_scaled_hits() > 0,
16512 "{NAME}: matched but zero predict_scaled_hits -- every block took the unscaled MC \
16513 path, which proves nothing about the scaled-reference code this round adds \
16514 (class gate-blind-to-feature)"
16515 );
16516 eprintln!(
16517 "{NAME}: {frame_count} frames pixel-exact, superres_hits={}, predict_scaled_hits={}",
16518 crate::superres::superres_hits(),
16519 crate::mc::predict_scaled_hits()
16520 );
16521 }
16522
16523 /// lane-t900 r28: the three scaled-reference (superres) refusals are
16524 /// LIFTED -- an 8x8 partition leaf, a sub-8x8 inter block, and warp --
16525 /// so two real `--superres-mode=1` streams whose references are all
16526 /// scaled must decode PIXEL-EXACT vs ffmpeg.
16527 ///
16528 /// Arm A drives `--min-partition-size=4` so the split (4x4) and rect
16529 /// (8x4/4x8) sub-8x8 readers and the 8x8 leaf all run over a scaled
16530 /// reference; arm B turns `--enable-warped-motion=1` on, which is the
16531 /// root cause this round fixed: libaom `motion_mode_allowed` drops
16532 /// WARPED_CAUSAL eligibility when `av1_is_scaled(sf)`, so the 8x8 leaf
16533 /// must read the 2-symbol obmc alphabet (here: no symbol at all, OBMC
16534 /// off) instead of the 3-symbol motion_mode row.
16535 ///
16536 /// Each arm hard-asserts its own counter (class `gate-blind-to-feature`):
16537 /// a pixel match with zero scaled leaves/sub-8x8 blocks/suppressed warp
16538 /// eligibilities would prove nothing.
16539 #[test]
16540 fn real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact() {
16541 const NAME: &str = "real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact";
16542 let _gate_lock = lock_gate_counters();
16543 if !have_ffmpeg() {
16544 eprintln!("SKIP {NAME}: no ffmpeg");
16545 return;
16546 }
16547 if !have_aomenc() {
16548 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16549 return;
16550 }
16551 // Every tool whose scaled-reference path this round does NOT touch is
16552 // off, so a mismatch can only be the lifted paths (the same scoping
16553 // the r10 key+inter superres gate uses).
16554 let common: [&str; 21] = [
16555 "--codec=av1", "--passes=1", "--end-usage=q", "--threads=1", "--row-mt=0",
16556 "--kf-max-dist=9999", "--lag-in-frames=0", "--auto-alt-ref=0", "--cpu-used=0",
16557 "--sb-size=64", "--superres-mode=1", "--superres-denominator=12",
16558 "--superres-kf-denominator=12", "--enable-obmc=0", "--enable-masked-comp=0",
16559 "--enable-interintra-comp=0", "--enable-tx-size-search=0", "--enable-cdef=0",
16560 "--enable-restoration=0", "--enable-palette=0", "--enable-intrabc=0",
16561 ];
16562 struct Arm {
16563 name: &'static str,
16564 frames: usize,
16565 cq: &'static str,
16566 extra: [&'static str; 4],
16567 }
16568 let arms = [
16569 Arm {
16570 name: "sub8+leaf8",
16571 frames: 4,
16572 cq: "--cq-level=4",
16573 extra: [
16574 "--enable-warped-motion=0",
16575 "--enable-rect-partitions=1",
16576 "--max-partition-size=32",
16577 "--min-partition-size=4",
16578 ],
16579 },
16580 Arm {
16581 name: "warp",
16582 frames: 6,
16583 cq: "--cq-level=20",
16584 extra: [
16585 "--enable-warped-motion=1",
16586 "--enable-rect-partitions=1",
16587 "--max-partition-size=32",
16588 "--min-partition-size=8",
16589 ],
16590 },
16591 ];
16592 let (width, height) = (96usize, 96usize);
16593 for arm in &arms {
16594 let duration = format!("{}", arm.frames as f64 / 25.0);
16595 let src = format!("mandelbrot=size={width}x{height}:rate=25");
16596 let y4m = Command::new("ffmpeg")
16597 .args([
16598 "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt",
16599 "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
16600 ])
16601 .stdin(Stdio::null())
16602 .stdout(Stdio::piped())
16603 .stderr(Stdio::piped())
16604 .output()
16605 .expect("ffmpeg failed to run");
16606 assert!(y4m.status.success(), "{NAME}: ffmpeg refused the fixture");
16607 let limit = format!("--limit={}", arm.frames);
16608 let mut args: Vec<&str> = common.to_vec();
16609 args.push(&limit);
16610 args.push(arm.cq);
16611 args.extend_from_slice(&arm.extra);
16612 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
16613 let mut child = Command::new(aomenc_path())
16614 .args(&args)
16615 .stdin(Stdio::piped())
16616 .stdout(Stdio::piped())
16617 .stderr(Stdio::piped())
16618 .spawn()
16619 .expect("aomenc failed to start");
16620 child
16621 .stdin
16622 .take()
16623 .expect("aomenc stdin")
16624 .write_all(&y4m.stdout)
16625 .expect("writing y4m to aomenc");
16626 let out = child.wait_with_output().expect("aomenc failed to run");
16627 assert!(
16628 out.status.success(),
16629 "{NAME} {}: aomenc refused the recipe: {}",
16630 arm.name,
16631 String::from_utf8_lossy(&out.stderr)
16632 );
16633 let stream = out.stdout;
16634 let leaf8_before = crate::decode::scaled_leaf8_hits();
16635 let sub8_before = crate::decode::scaled_sub8_hits();
16636 let warp_before = crate::decode::scaled_warp_suppressed_hits();
16637 let frames = decode_stream(&stream)
16638 .unwrap_or_else(|e| panic!("{NAME} {}: refused: {e}", arm.name));
16639 assert_eq!(frames.len(), arm.frames, "{NAME} {}", arm.name);
16640 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, arm.frames);
16641 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16642 assert_eq!(got.y, want.y, "{NAME} {} frame {i} luma vs ffmpeg", arm.name);
16643 assert_eq!(got.u, want.u, "{NAME} {} frame {i} U vs ffmpeg", arm.name);
16644 assert_eq!(got.v, want.v, "{NAME} {} frame {i} V vs ffmpeg", arm.name);
16645 }
16646 let (leaf8, sub8, warp) = (
16647 crate::decode::scaled_leaf8_hits() - leaf8_before,
16648 crate::decode::scaled_sub8_hits() - sub8_before,
16649 crate::decode::scaled_warp_suppressed_hits() - warp_before,
16650 );
16651 eprintln!(
16652 "{NAME} {}: {} frames pixel-exact, scaled leaf8={leaf8} sub8={sub8} \
16653 warp_suppressed={warp}",
16654 arm.name, arm.frames
16655 );
16656 if arm.name == "sub8+leaf8" {
16657 assert!(leaf8 > 0 && sub8 > 0, "{NAME} {}: the lifted paths never ran (leaf8={leaf8} sub8={sub8})", arm.name);
16658 } else {
16659 assert!(
16660 warp > 0,
16661 "{NAME} {}: no block reached WARPED_CAUSAL eligibility under a scaled \
16662 reference, so the alphabet fix is unexercised",
16663 arm.name
16664 );
16665 }
16666 }
16667 }
16668
16669 /// lane-interintra r1: `--enable-interintra-comp=1` streams must DECODE
16670 /// pixel-exact -- the interintra flag/mode/wedge-flag syntax and the
16671 /// non-wedge smooth blend are ported. A refusal naming interintra fails
16672 /// the gate UNLESS it is the wedge refusal (`use_wedge_interintra == 1`
16673 /// is r2, and this recipe encodes with wedge off so it must not fire
16674 /// either); warp/obmc are enabled and supported; refusals for OTHER
16675 /// named capabilities (screen content tools) still skip that seed. The
16676 /// sweep must actually exercise interintra (`interintra_hits > 0`).
16677 #[test]
16678 fn a_real_aomenc_stream_with_interintra_decodes_pixel_exact() {
16679 const NAME: &str = "a_real_aomenc_stream_with_interintra_decodes_pixel_exact";
16680 let _gate_lock = lock_gate_counters();
16681 if !have_ffmpeg() {
16682 eprintln!("SKIP {NAME}: no ffmpeg");
16683 return;
16684 }
16685 if !have_aomenc() {
16686 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16687 return;
16688 }
16689 let (width, height, frame_count) = (64usize, 64usize, 24usize);
16690 // lane-midcut r1: rect interintra (`write_w != write_h`) built its
16691 // intra predictor at the square `side`; this gate passed with that
16692 // bug, so the shape gets its own delta-counted assert below.
16693 let rect_before = crate::decode::interintra_rect_hits();
16694 let mut named_refusals = 0u32;
16695 let mut matched = 0u32;
16696 let n_attempts: u32 = std::env::var("EC_INTERINTRA_GATE_ATTEMPTS")
16697 .ok()
16698 .and_then(|s| s.parse().ok())
16699 .unwrap_or(40);
16700 for attempt in 0..n_attempts {
16701 let seed = 42 + attempt;
16702 let duration = frame_count as f64 / 25.0;
16703 let source =
16704 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
16705 let y4m = Command::new("ffmpeg")
16706 .args([
16707 "-v",
16708 "error",
16709 "-f",
16710 "lavfi",
16711 "-i",
16712 &source,
16713 "-pix_fmt",
16714 "yuv420p",
16715 "-f",
16716 "yuv4mpegpipe",
16717 "-",
16718 ])
16719 .stdin(Stdio::null())
16720 .stdout(Stdio::piped())
16721 .stderr(Stdio::piped())
16722 .output()
16723 .expect("ffmpeg failed to run");
16724 assert!(
16725 y4m.status.success(),
16726 "ffmpeg fixture: {}",
16727 String::from_utf8_lossy(&y4m.stderr)
16728 );
16729 let args: Vec<&str> = vec![
16730 "--codec=av1",
16731 "--passes=1",
16732 "--end-usage=q",
16733 "--cq-level=45",
16734 "--cpu-used=0",
16735 "--kf-max-dist=1000",
16736 "--threads=1",
16737 "--row-mt=0",
16738 "--auto-alt-ref=1",
16739 "--lag-in-frames=16",
16740 "--enable-fwd-kf=0",
16741 "--enable-order-hint=1",
16742 "--enable-warped-motion=1",
16743 "--enable-obmc=1",
16744 "--tune-content=default",
16745 "--enable-masked-comp=0",
16746 "--enable-interintra-comp=1",
16747 "--enable-onesided-comp=1",
16748 "--enable-interintra-wedge=0",
16749 "--enable-smooth-interintra=1",
16750 "--enable-rect-partitions=0",
16751 "--enable-ab-partitions=0",
16752 "--enable-1to4-partitions=0",
16753 "--enable-filter-intra=0",
16754 "--enable-smooth-intra=0",
16755 "--enable-paeth-intra=0",
16756 "--enable-directional-intra=0",
16757 "--enable-angle-delta=0",
16758 "--enable-tx-size-search=0",
16759 "--enable-cdef=0",
16760 "--enable-restoration=0",
16761 "--max-partition-size=32",
16762 "--min-partition-size=32",
16763 "--enable-palette=0",
16764 "--enable-intrabc=0",
16765 "--enable-cfl-intra=0",
16766 "--enable-ref-frame-mvs=0",
16767 "--obu",
16768 "-o",
16769 "-",
16770 "-",
16771 ];
16772 let mut child = Command::new(aomenc_path())
16773 .args(&args)
16774 .stdin(Stdio::piped())
16775 .stdout(Stdio::piped())
16776 .stderr(Stdio::piped())
16777 .spawn()
16778 .expect("aomenc failed to start");
16779 child
16780 .stdin
16781 .take()
16782 .expect("aomenc stdin")
16783 .write_all(&y4m.stdout)
16784 .expect("writing y4m to aomenc");
16785 let out = child.wait_with_output().expect("aomenc failed to run");
16786 assert!(
16787 out.status.success(),
16788 "aomenc refused the fixture: {}",
16789 String::from_utf8_lossy(&out.stderr)
16790 );
16791 let stream = out.stdout;
16792 let frames = match decode_stream(&stream) {
16793 Err(e) => {
16794 let msg = e.to_string();
16795 assert!(
16796 msg.contains("unsupported"),
16797 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
16798 );
16799 assert!(
16800 !msg.contains("warp"),
16801 "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \
16802 refusal must not exist: {msg}"
16803 );
16804 assert!(
16805 !msg.contains("interintra"),
16806 "{NAME} refused on interintra (seed {seed}) -- non-wedge interintra \
16807 is ported and this recipe encodes with wedge off: {msg}"
16808 );
16809 named_refusals += 1;
16810 eprintln!("seed {seed} refusal (non-warp capability): {msg}");
16811 continue;
16812 }
16813 Ok(frames) => frames,
16814 };
16815 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
16816 assert_eq!(frames.len(), frame_count);
16817 let mismatched = frames
16818 .iter()
16819 .zip(&ffmpeg_frames)
16820 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16821 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
16822 std::fs::write(&path, &stream).expect("writing pinned stream");
16823 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
16824 }
16825 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16826 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
16827 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
16828 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
16829 }
16830 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
16831 // stream again, comparing EVERY decode-order frame -- the hidden
16832 // (show_frame == 0) alt-ref frames the ffmpeg compare above
16833 // cannot see, because both sides of it emit shown frames only.
16834 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
16835 eprintln!(
16836 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
16837 {hidden_n} hidden, all pixel-exact vs the oracle"
16838 );
16839 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
16840 // libaom's temporal alt-ref filter absorbs this recipe's hidden
16841 // frames, so the compare above is vacuous -- re-encode the same
16842 // fixture with --arnr-maxframes=0 and compare THOSE.
16843 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
16844 eprintln!(
16845 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
16846 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
16847 );
16848 }
16849 // lane-midcut r3 RECT ARM: the recipe above spells
16850 // `--enable-rect-partitions=0 --min-partition-size=32`, so it can
16851 // never produce a RECT interintra block -- the delta assert at the
16852 // end of this gate was unsatisfiable on it (the gate disabled the
16853 // very shape it claims to prove). Re-encode the SAME source with
16854 // the rect overrides APPENDED (aomenc keeps the LAST occurrence of
16855 // a repeated flag) and compare every decode-order frame of that
16856 // stream against aomdec, until a rect interintra block fires.
16857 if crate::decode::interintra_rect_hits() == rect_before {
16858 let mut rect_args = args.clone();
16859 rect_args.extend_from_slice(&[
16860 "--enable-rect-partitions=1",
16861 "--min-partition-size=8",
16862 "--max-partition-size=64",
16863 ]);
16864 let mut child = Command::new(aomenc_path())
16865 .args(&rect_args)
16866 .stdin(Stdio::piped())
16867 .stdout(Stdio::piped())
16868 .stderr(Stdio::piped())
16869 .spawn()
16870 .expect("aomenc failed to start");
16871 child
16872 .stdin
16873 .take()
16874 .expect("aomenc stdin")
16875 .write_all(&y4m.stdout)
16876 .expect("writing y4m to aomenc");
16877 let out = child.wait_with_output().expect("aomenc failed to run");
16878 assert!(
16879 out.status.success(),
16880 "{NAME} RECT-ARM: aomenc refused its own recipe plus the rect overrides: {}",
16881 String::from_utf8_lossy(&out.stderr)
16882 );
16883 let rect_stream = out.stdout;
16884 match decode_stream(&rect_stream) {
16885 Err(e) => {
16886 let msg = e.to_string();
16887 assert!(
16888 msg.contains("unsupported"),
16889 "{NAME} RECT-ARM failed outright, not a named refusal (seed {seed}): {msg}"
16890 );
16891 eprintln!("{NAME} RECT-ARM: skipped on a named refusal: {msg}");
16892 }
16893 Ok(_) => {
16894 let (total, hidden) =
16895 decode_all_frames_vs_oracle(&rect_stream, &format!("{NAME}-rect"));
16896 eprintln!(
16897 "{NAME} RECT-ARM: seed {seed}: {total} decode-order frames, {hidden} \
16898 hidden, all pixel-exact vs the oracle, interintra_rect_hits={}",
16899 crate::decode::interintra_rect_hits() - rect_before
16900 );
16901 }
16902 }
16903 }
16904 matched += 1;
16905 }
16906 assert!(
16907 matched > 0,
16908 "{NAME}: every attempt refused on other capabilities; the gate never exercised warp"
16909 );
16910 assert!(
16911 crate::decode::interintra_hits() > 0,
16912 "{NAME}: {matched} matches but zero interintra blocks fired -- the gate decodes \
16913 these streams without ever taking interintra, so it proves nothing"
16914 );
16915 // lane-defon r1: `--enable-onesided-comp=1` is spelled on this
16916 // recipe, so a UNIDIR_COMP_REFERENCE pair must actually have been
16917 // read -- otherwise the on-value proves nothing.
16918 assert!(
16919 crate::decode::uni_comp_hits() > 0,
16920 "{NAME}: {matched} matches but zero UNIDIR_COMP_REFERENCE pairs read -- \
16921 --enable-onesided-comp=1 never reached the uni_comp_ref alphabet"
16922 );
16923 assert!(
16924 crate::decode::interintra_rect_hits() > rect_before,
16925 "{NAME}: {matched} matches but zero RECTANGULAR interintra blocks fired -- the \
16926 square-only blend defect (lane-midcut r1) would pass this gate unseen"
16927 );
16928 eprintln!(
16929 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, interintra_hits={} interintra_rect_hits={} uni_comp_hits={}",
16930 crate::decode::interintra_hits(),
16931 crate::decode::interintra_rect_hits() - rect_before,
16932 crate::decode::uni_comp_hits()
16933 );
16934 }
16935
16936 /// lane-scaledref r1: a real aomenc `--superres-mode=1` sequence with
16937 /// compound, OBMC, interintra and 8x8 leaves ALL enabled must decode
16938 /// pixel-exact -- these are the combinations the three
16939 /// "... with a scaled reference (superres, unimplemented)" refusals used
16940 /// to cover. Each combination gets its OWN hard-asserted hit counter
16941 /// (`crate::decode::scaled_*_hits`), because an unscaled reference would
16942 /// pass the pixels and prove nothing (class `gate-blind-to-feature`), and
16943 /// a stream that scales but never takes compound/OBMC/interintra/8x8
16944 /// would prove nothing about the code this round adds either. A refusal
16945 /// naming a scaled reference is a hard failure: those are exactly the
16946 /// strings this round lifts. Other named capabilities skip that seed.
16947 #[test]
16948 fn a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact()
16949 {
16950 const NAME: &str = "a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact";
16951 let _gate_lock = lock_gate_counters();
16952 if !have_ffmpeg() {
16953 eprintln!("SKIP {NAME}: no ffmpeg");
16954 return;
16955 }
16956 if !have_aomenc() {
16957 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16958 return;
16959 }
16960 let (width, height, frame_count) = (64usize, 64usize, 24usize);
16961 let mut named_refusals = 0u32;
16962 let mut matched = 0u32;
16963 let n_attempts: u32 = std::env::var("EC_SCALEDREF_GATE_ATTEMPTS")
16964 .ok()
16965 .and_then(|s| s.parse().ok())
16966 .unwrap_or(12);
16967 for attempt in 0..n_attempts {
16968 let seed = 42 + attempt;
16969 let duration = frame_count as f64 / 25.0;
16970 let source =
16971 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
16972 let y4m = Command::new("ffmpeg")
16973 .args([
16974 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
16975 "yuv4mpegpipe", "-",
16976 ])
16977 .stdin(Stdio::null())
16978 .stdout(Stdio::piped())
16979 .stderr(Stdio::piped())
16980 .output()
16981 .expect("ffmpeg failed to run");
16982 assert!(
16983 y4m.status.success(),
16984 "ffmpeg fixture: {}",
16985 String::from_utf8_lossy(&y4m.stderr)
16986 );
16987 let on = |name: &str| {
16988 if std::env::var(name).as_deref() == Ok("0") { "0" } else { "1" }
16989 };
16990 // lane-scaledref r2: warp is ON. A warp-capable frame header
16991 // under a scaled reference is exactly the case r1 got wrong
16992 // (the block must read the 2-symbol `obmc_cdf`, not the
16993 // 3-symbol `motion_mode_cdf` -- libaom `motion_mode_allowed`,
16994 // blockd.h:1484), and it decoded silently wrong pixels rather
16995 // than refusing. `EC_SCALEDREF_WARP=0` turns it off for
16996 // bisecting only.
16997 let warp = format!("--enable-warped-motion={}", on("EC_SCALEDREF_WARP"));
16998 // lane-scaledref r2: `EC_SCALEDREF_MODE=3` (qthresh) lets
16999 // superres switch on and off per frame, so a compound block can
17000 // reference one scaled and one unscaled reference -- the mixed
17001 // case mode 1 (every frame scaled) never produces.
17002 let superres_mode = format!(
17003 "--superres-mode={}",
17004 std::env::var("EC_SCALEDREF_MODE").unwrap_or_else(|_| "1".into())
17005 );
17006 let obmc = format!("--enable-obmc={}", on("EC_SCALEDREF_OBMC"));
17007 let interintra = format!("--enable-interintra-comp={}", on("EC_SCALEDREF_II"));
17008 let lag = format!(
17009 "--lag-in-frames={}",
17010 if on("EC_SCALEDREF_COMP") == "0" { "0" } else { "25" }
17011 );
17012 let alt_ref = format!("--auto-alt-ref={}", on("EC_SCALEDREF_COMP"));
17013 let args: Vec<&str> = vec![
17014 "--codec=av1",
17015 "--passes=1",
17016 "--end-usage=q",
17017 "--cq-level=45",
17018 "--cpu-used=0",
17019 "--kf-max-dist=1000",
17020 "--threads=1",
17021 "--row-mt=0",
17022 "--sb-size=64",
17023 // superres on every frame, key and inter alike -- the scaled
17024 // reference this gate is about.
17025 // denominator 16 (the maximum) keeps the CODED frame
17026 // 32x64 -- a multiple of 16 both ways, so no frame-edge
17027 // 16x16 straddle forces a sub-16x16 partition this decoder
17028 // still refuses on the aligned path ("an inter partition
17029 // below 16x16"). Denominator 12 codes 43 columns and every
17030 // seed refused there.
17031 &superres_mode,
17032 "--superres-denominator=16",
17033 "--superres-kf-denominator=16",
17034 // the four combinations this round lifts (each switchable
17035 // by env for bisecting a mismatch without a rebuild)
17036 &alt_ref,
17037 &lag,
17038 "--enable-order-hint=1",
17039 &warp,
17040 &obmc,
17041 &interintra,
17042 "--enable-smooth-interintra=1",
17043 "--enable-interintra-wedge=0",
17044 "--enable-masked-comp=0",
17045 "--enable-onesided-comp=0",
17046 "--enable-fwd-kf=0",
17047 "--tune-content=default",
17048 "--max-partition-size=32",
17049 "--min-partition-size=32",
17050 // everything this decoder still refuses under any reference
17051 "--enable-rect-partitions=0",
17052 "--enable-ab-partitions=0",
17053 "--enable-1to4-partitions=0",
17054 "--enable-filter-intra=0",
17055 "--enable-smooth-intra=0",
17056 "--enable-paeth-intra=0",
17057 "--enable-directional-intra=0",
17058 "--enable-angle-delta=0",
17059 "--enable-tx-size-search=0",
17060 "--enable-cdef=0",
17061 "--enable-restoration=0",
17062 "--enable-palette=0",
17063 "--enable-intrabc=0",
17064 "--enable-cfl-intra=0",
17065 "--enable-ref-frame-mvs=0",
17066 "--obu",
17067 "-o",
17068 "-",
17069 "-",
17070 ];
17071 let mut child = Command::new(aomenc_path())
17072 .args(&args)
17073 .stdin(Stdio::piped())
17074 .stdout(Stdio::piped())
17075 .stderr(Stdio::piped())
17076 .spawn()
17077 .expect("aomenc failed to start");
17078 child
17079 .stdin
17080 .take()
17081 .expect("aomenc stdin")
17082 .write_all(&y4m.stdout)
17083 .expect("writing y4m to aomenc");
17084 let out = child.wait_with_output().expect("aomenc failed to run");
17085 assert!(
17086 out.status.success(),
17087 "aomenc refused the fixture: {}",
17088 String::from_utf8_lossy(&out.stderr)
17089 );
17090 let stream = out.stdout;
17091 let frames = match decode_stream(&stream) {
17092 Err(e) => {
17093 let msg = e.to_string();
17094 assert!(
17095 msg.contains("unsupported"),
17096 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
17097 );
17098 assert!(
17099 !msg.contains("scaled reference"),
17100 "{NAME} refused on a scaled reference (seed {seed}) -- those refusals \
17101 are exactly what this round lifts: {msg}"
17102 );
17103 named_refusals += 1;
17104 eprintln!("seed {seed} refusal (other capability): {msg}");
17105 continue;
17106 }
17107 Ok(frames) => frames,
17108 };
17109 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17110 assert_eq!(frames.len(), frame_count);
17111 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17112 let mismatched = frames
17113 .iter()
17114 .zip(&ffmpeg_frames)
17115 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17116 if mismatched {
17117 std::fs::write(&path, &stream).expect("writing pinned stream");
17118 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
17119 }
17120 }
17121 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17122 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
17123 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
17124 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
17125 }
17126 matched += 1;
17127 }
17128 eprintln!(
17129 "{NAME}: {named_refusals} other-capability refusals, {matched}/{n_attempts} pixel-exact, \
17130 superres_hits={} predict_scaled_hits={} scaled_compound={} scaled_warp_fallback={} \
17131 scaled_obmc={} scaled_interintra={} scaled_block8={} scaled_warp_suppressed={} mixed_scale_compound={}",
17132 crate::superres::superres_hits(),
17133 crate::mc::predict_scaled_hits(),
17134 crate::decode::scaled_compound_hits(),
17135 crate::decode::scaled_warp_fallback_hits(),
17136 crate::decode::scaled_obmc_hits(),
17137 crate::decode::scaled_interintra_hits(),
17138 crate::decode::scaled_block8_hits(),
17139 crate::decode::scaled_warp_suppressed_hits(),
17140 crate::decode::mixed_scale_compound_hits(),
17141 );
17142 assert!(
17143 matched > 0,
17144 "{NAME}: every attempt refused on other capabilities; the gate proves nothing"
17145 );
17146 assert!(
17147 crate::mc::predict_scaled_hits() > 0,
17148 "{NAME}: matched but zero predict_scaled_hits -- no block took the scaled MC path"
17149 );
17150 // The 8x8 leaf is NOT asserted here: it stays refused (no recipe
17151 // produced an 8x8 inter leaf at all), so its counter is a
17152 // diagnostic only -- see this gate's own doc and decode.rs.
17153 // `scaled_warp_suppressed` IS asserted: it counts the blocks whose
17154 // WARPED_CAUSAL eligibility libaom drops because the reference is
17155 // scaled, i.e. the blocks that must read `obmc_cdf`. Zero of them
17156 // would mean this gate's `--enable-warped-motion=1` never reached a
17157 // warp-eligible block and proves nothing about r2's fix.
17158 assert!(
17159 crate::decode::scaled_warp_suppressed_hits() > 0,
17160 "{NAME}: {matched} matches but no block had its warp eligibility \
17161 suppressed by a scaled reference -- the warp arm proves nothing"
17162 );
17163 for (hits, what) in [
17164 (crate::decode::scaled_compound_hits(), "compound with a scaled reference"),
17165 (crate::decode::scaled_obmc_hits(), "OBMC with a scaled reference"),
17166 (crate::decode::scaled_interintra_hits(), "interintra with a scaled reference"),
17167 ] {
17168 assert!(hits > 0, "{NAME}: {matched} matches but zero blocks took {what}");
17169 }
17170 }
17171
17172 /// lane-defon r1: the 10-bit one-sided-compound hole --
17173 /// `--enable-onesided-comp` was spelled on in no 10-bit gate (5 of the 15
17174 /// pin it off, the rest default), so the UNIDIR_COMP_REFERENCE alphabet
17175 /// was proven at 8 bits only while both of his films are 10-bit 4:2:0.
17176 /// `--enable-diff-wtd-comp=1` is deliberately NOT spelled here (a flag a
17177 /// gate turns on without asserting it fired is coverage theatre, class
17178 /// gate-blind-to-feature): measured this round, the 10-bit `gradients`
17179 /// fixture decodes 8/8 pixel-exact with `diffwtd_hits == 0` -- smooth
17180 /// gradients never win
17181 /// a difference-weighted mask (the 8-bit gate needs `mandelbrot`'s hard
17182 /// diagonal edge, and [`ten_bit_tool_gate`] has no mandelbrot source), so
17183 /// hard-asserting it here would fail on encoder choice, not on a decoder
17184 /// defect.
17185 #[test]
17186 fn a_real_aomenc_10bit_stream_with_onesided_compound_decodes_pixel_exact() {
17187 const NAME: &str = "a_real_aomenc_10bit_stream_with_onesided_compound_decodes_pixel_exact";
17188 let _gate_lock = lock_gate_counters();
17189 if !have_ffmpeg() {
17190 eprintln!("SKIP {NAME}: no ffmpeg");
17191 return;
17192 }
17193 if !have_aomenc() {
17194 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17195 return;
17196 }
17197 ten_bit_tool_gate(
17198 NAME,
17199 64,
17200 64,
17201 24,
17202 &[
17203 "--enable-onesided-comp=1",
17204 "--enable-masked-comp=1",
17205 "--enable-dist-wtd-comp=0",
17206 "--cq-level=45",
17207 "--kf-max-dist=1000",
17208 "--auto-alt-ref=1",
17209 "--lag-in-frames=16",
17210 "--enable-fwd-kf=0",
17211 "--enable-order-hint=1",
17212 "--enable-global-motion=0",
17213 "--enable-warped-motion=1",
17214 "--enable-obmc=1",
17215 "--tune-content=default",
17216 "--enable-interintra-comp=0",
17217 "--enable-interintra-wedge=0",
17218 "--enable-smooth-interintra=0",
17219 "--enable-rect-partitions=0",
17220 "--enable-ab-partitions=0",
17221 "--enable-1to4-partitions=0",
17222 "--enable-filter-intra=0",
17223 "--enable-smooth-intra=0",
17224 "--enable-paeth-intra=0",
17225 "--enable-directional-intra=0",
17226 "--enable-angle-delta=0",
17227 "--enable-tx-size-search=0",
17228 "--enable-cdef=0",
17229 "--enable-restoration=0",
17230 "--max-partition-size=32",
17231 "--min-partition-size=32",
17232 "--enable-palette=0",
17233 "--enable-intrabc=0",
17234 "--enable-cfl-intra=0",
17235 "--enable-ref-frame-mvs=0",
17236 ],
17237 &[42, 43, 44, 45, 46, 47, 48, 49],
17238 &[("uni_comp_hits", crate::decode::uni_comp_hits as fn() -> usize)],
17239 );
17240 }
17241
17242 /// lane-defon r1: the 10-bit sibling of
17243 /// [`a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact`] --
17244 /// `--enable-interintra-wedge=1` was spelled on in no 10-bit gate (5 of
17245 /// the 15 pin it off), and his two films are 10-bit, so the 8-bit
17246 /// gate alone proves nothing about the streams that matter. Same tool
17247 /// set as the 8-bit recipe (`--enable-masked-comp=0` keeps inter blocks
17248 /// off the COMPOUND_WEDGE path, fixed 32x32 partitions), driven through
17249 /// [`ten_bit_tool_gate`], which hard-asserts `wii_hits` moved and
17250 /// compares every plane against ffmpeg's own 10-bit decode.
17251 #[test]
17252 fn a_real_aomenc_10bit_stream_with_interintra_wedge_decodes_pixel_exact() {
17253 const NAME: &str = "a_real_aomenc_10bit_stream_with_interintra_wedge_decodes_pixel_exact";
17254 let _gate_lock = lock_gate_counters();
17255 if !have_ffmpeg() {
17256 eprintln!("SKIP {NAME}: no ffmpeg");
17257 return;
17258 }
17259 if !have_aomenc() {
17260 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17261 return;
17262 }
17263 ten_bit_tool_gate(
17264 NAME,
17265 64,
17266 64,
17267 24,
17268 &[
17269 "--enable-interintra-wedge=1",
17270 "--enable-interintra-comp=1",
17271 "--enable-smooth-interintra=1",
17272 "--cq-level=45",
17273 "--kf-max-dist=1000",
17274 "--auto-alt-ref=1",
17275 "--lag-in-frames=16",
17276 "--enable-fwd-kf=0",
17277 "--enable-order-hint=1",
17278 "--enable-warped-motion=1",
17279 "--enable-obmc=1",
17280 "--tune-content=default",
17281 "--enable-masked-comp=0",
17282 "--enable-onesided-comp=0",
17283 "--enable-rect-partitions=0",
17284 "--enable-ab-partitions=0",
17285 "--enable-1to4-partitions=0",
17286 "--enable-filter-intra=0",
17287 "--enable-smooth-intra=0",
17288 "--enable-paeth-intra=0",
17289 "--enable-directional-intra=0",
17290 "--enable-angle-delta=0",
17291 "--enable-tx-size-search=0",
17292 "--enable-cdef=0",
17293 "--enable-restoration=0",
17294 "--max-partition-size=32",
17295 "--min-partition-size=32",
17296 "--enable-palette=0",
17297 "--enable-intrabc=0",
17298 "--enable-cfl-intra=0",
17299 "--enable-ref-frame-mvs=0",
17300 ],
17301 &[42, 43, 44, 45, 46, 47, 48, 49],
17302 &[
17303 ("wii_hits", crate::decode::wii_hits as fn() -> usize),
17304 ("interintra_hits", crate::decode::interintra_hits as fn() -> usize),
17305 ],
17306 );
17307 }
17308
17309 /// lane-wii r2: `--enable-interintra-wedge=1` streams must DECODE
17310 /// pixel-exact -- the wedge-interintra syntax (adapting `wedge_index`
17311 /// CDF symbol, fixed sign 0) and the wedge mask blend are ported over
17312 /// the checksum-verified codebook. `--enable-masked-comp=0` stays so
17313 /// the encoder cannot route inter blocks through the still-unported
17314 /// COMPOUND_WEDGE/DIFFWTD path. A refusal naming interintra/wedge
17315 /// fails the gate; refusals for OTHER named capabilities still skip
17316 /// that seed. Zero `wii_hits` on a run means the encoder never
17317 /// selected wedge-interintra -- soft-skipped (warned), not failed:
17318 /// that is encoder choice, not a decoder bug.
17319 #[test]
17320 fn a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact() {
17321 const NAME: &str = "a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact";
17322 let _gate_lock = lock_gate_counters();
17323 if !have_ffmpeg() {
17324 eprintln!("SKIP {NAME}: no ffmpeg");
17325 return;
17326 }
17327 if !have_aomenc() {
17328 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17329 return;
17330 }
17331 let (width, height, frame_count) = (64usize, 64usize, 24usize);
17332 let mut named_refusals = 0u32;
17333 let mut matched = 0u32;
17334 let n_attempts: u32 = std::env::var("EC_WEDGE_GATE_ATTEMPTS")
17335 .ok()
17336 .and_then(|s| s.parse().ok())
17337 .unwrap_or(40);
17338 for attempt in 0..n_attempts {
17339 let seed = 42 + attempt;
17340 let duration = frame_count as f64 / 25.0;
17341 let source = if attempt % 2 == 0 {
17342 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
17343 } else {
17344 // `end_pts` does NOT bound mandelbrot (it generated 300+
17345 // frames and hung the gate for an hour); `-t` below is the
17346 // real bound, matching every other mandelbrot gate recipe.
17347 format!("mandelbrot=size={width}x{height}:rate=25")
17348 };
17349 let duration_arg = format!("{duration}");
17350 let y4m = Command::new("ffmpeg")
17351 .args([
17352 "-v",
17353 "error",
17354 "-f",
17355 "lavfi",
17356 "-i",
17357 &source,
17358 "-pix_fmt",
17359 "yuv420p",
17360 "-t",
17361 &duration_arg,
17362 "-f",
17363 "yuv4mpegpipe",
17364 "-",
17365 ])
17366 .stdin(Stdio::null())
17367 .stdout(Stdio::piped())
17368 .stderr(Stdio::piped())
17369 .output()
17370 .expect("ffmpeg failed to run");
17371 assert!(
17372 y4m.status.success(),
17373 "ffmpeg fixture: {}",
17374 String::from_utf8_lossy(&y4m.stderr)
17375 );
17376 let args: Vec<&str> = vec![
17377 "--codec=av1",
17378 "--passes=1",
17379 "--end-usage=q",
17380 "--cq-level=45",
17381 "--cpu-used=0",
17382 "--kf-max-dist=1000",
17383 "--threads=1",
17384 "--row-mt=0",
17385 "--auto-alt-ref=1",
17386 "--lag-in-frames=16",
17387 "--enable-fwd-kf=0",
17388 "--enable-order-hint=1",
17389 "--enable-warped-motion=1",
17390 "--enable-obmc=1",
17391 "--tune-content=default",
17392 "--enable-masked-comp=0",
17393 "--enable-interintra-comp=1",
17394 "--enable-onesided-comp=0",
17395 "--enable-interintra-wedge=1",
17396 "--enable-smooth-interintra=1",
17397 "--enable-rect-partitions=0",
17398 "--enable-ab-partitions=0",
17399 "--enable-1to4-partitions=0",
17400 "--enable-filter-intra=0",
17401 "--enable-smooth-intra=0",
17402 "--enable-paeth-intra=0",
17403 "--enable-directional-intra=0",
17404 "--enable-angle-delta=0",
17405 "--enable-tx-size-search=0",
17406 "--enable-cdef=0",
17407 "--enable-restoration=0",
17408 "--max-partition-size=32",
17409 "--min-partition-size=32",
17410 "--enable-palette=0",
17411 "--enable-intrabc=0",
17412 "--enable-cfl-intra=0",
17413 "--enable-ref-frame-mvs=0",
17414 "--obu",
17415 "-o",
17416 "-",
17417 "-",
17418 ];
17419 let mut child = Command::new(aomenc_path())
17420 .args(&args)
17421 .stdin(Stdio::piped())
17422 .stdout(Stdio::piped())
17423 .stderr(Stdio::piped())
17424 .spawn()
17425 .expect("aomenc failed to start");
17426 child
17427 .stdin
17428 .take()
17429 .expect("aomenc stdin")
17430 .write_all(&y4m.stdout)
17431 .expect("writing y4m to aomenc");
17432 let out = child.wait_with_output().expect("aomenc failed to run");
17433 assert!(
17434 out.status.success(),
17435 "aomenc refused the fixture: {}",
17436 String::from_utf8_lossy(&out.stderr)
17437 );
17438 let stream = out.stdout;
17439 let frames = match decode_stream(&stream) {
17440 Err(e) => {
17441 let msg = e.to_string();
17442 assert!(
17443 msg.contains("unsupported"),
17444 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
17445 );
17446 // Verifier note (lane-wii r2): no refusal string containing
17447 // "wedge"/"interintra" exists in the decoder any more, so
17448 // string-forbidding asserts here would be vacuous (class
17449 // gate-blind-to-feature). The proof this gate carries is
17450 // pixel-exact decode plus the wii_hits count printed below.
17451 named_refusals += 1;
17452 eprintln!("seed {seed} refusal (non-wedge capability): {msg}");
17453 continue;
17454 }
17455 Ok(frames) => frames,
17456 };
17457 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17458 assert_eq!(frames.len(), frame_count);
17459 let mismatched = frames
17460 .iter()
17461 .zip(&ffmpeg_frames)
17462 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17463 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17464 std::fs::write(&path, &stream).expect("writing pinned stream");
17465 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
17466 }
17467 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17468 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
17469 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
17470 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
17471 }
17472 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
17473 // stream again, comparing EVERY decode-order frame -- the hidden
17474 // (show_frame == 0) alt-ref frames the ffmpeg compare above
17475 // cannot see, because both sides of it emit shown frames only.
17476 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
17477 eprintln!(
17478 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
17479 {hidden_n} hidden, all pixel-exact vs the oracle"
17480 );
17481 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
17482 // libaom's temporal alt-ref filter absorbs this recipe's hidden
17483 // frames, so the compare above is vacuous -- re-encode the same
17484 // fixture with --arnr-maxframes=0 and compare THOSE.
17485 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
17486 eprintln!(
17487 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
17488 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
17489 );
17490 }
17491 matched += 1;
17492 }
17493 assert!(
17494 matched > 0,
17495 "{NAME}: every attempt refused on other capabilities; the gate never exercised wedge-interintra"
17496 );
17497 // Hardened from a soft-note (verifier: gate-blind-to-feature): the
17498 // recipe fired wedge-interintra on EVERY one of 6 hammer runs
17499 // (wii_hits 2-7), so a zero-hit run is a regression, not sampling.
17500 assert!(
17501 crate::decode::wii_hits() > 0,
17502 "{NAME}: {matched} pixel-exact matches but zero wedge-interintra blocks fired -- \
17503 the blend is unexercised (recipe fired 2-7 hits per run when landed)"
17504 );
17505 eprintln!(
17506 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, wii_hits={}",
17507 crate::decode::wii_hits()
17508 );
17509 }
17510
17511 /// The affine-capable encoder (`scripts/build-aom-affine-oracle.sh`),
17512 /// separate from the shared oracle because stock libaom's global-motion
17513 /// model search is pinned to ROTZOOM and can never emit AFFINE.
17514 fn affine_aomenc_path() -> std::path::PathBuf {
17515 if let Some(p) = std::env::var_os("EC_AV1_AFFINE_AOMENC") {
17516 return std::path::PathBuf::from(p);
17517 }
17518 let home = std::env::var_os("HOME").unwrap_or_default();
17519 std::path::PathBuf::from(home).join(".cache/aom-affine/build/aomenc")
17520 }
17521
17522 fn have_affine_aomenc() -> bool {
17523 let present = affine_aomenc_path().is_file();
17524 assert!(
17525 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
17526 "EC_AV1_REQUIRE_AOMENC is set but no affine-capable aomenc at {} -- run \
17527 scripts/build-aom-affine-oracle.sh",
17528 affine_aomenc_path().display()
17529 );
17530 present
17531 }
17532
17533 /// lane-gmaffine r1: an inter frame whose `global_motion_params` carries a
17534 /// SIX-parameter (`AFFINE`) model for a single-reference frame -- refused
17535 /// by name since lane-gm r4 because no aomenc recipe ever reached it.
17536 /// The reason it never did is in libaom's own encoder, not in the
17537 /// content: `av1/encoder/global_motion_facade.c:24` pins the model search
17538 /// to `ROTZOOM` at both ends, so *no* `--enable-global-motion=1` command
17539 /// line over any source can produce the case. The decoder must still
17540 /// handle it (the bitstream allows it, `read_global_motion_params` reads
17541 /// params 4/5 with their own subexp references, and ffmpeg decodes it),
17542 /// so this gate widens exactly that one encoder-side search range in a
17543 /// side build and encodes with it. Everything downstream is ordinary
17544 /// libaom and the pixel oracle is still ffmpeg.
17545 ///
17546 /// Content: rotation composed with a progressive *anisotropic* stretch --
17547 /// a similarity transform plus unequal axis scaling is precisely what a
17548 /// 4-parameter ROTZOOM model cannot express, which is what makes the
17549 /// encoder's RD pick AFFINE. `affine_gm_hits()` hard-asserts that real
17550 /// blocks were predicted through the 6-parameter warp, not merely that a
17551 /// header parsed one (class `gate-blind-to-feature`).
17552 #[test]
17553 fn a_real_affine_global_motion_stream_decodes_pixel_exact() {
17554 const NAME: &str = "a_real_affine_global_motion_stream_decodes_pixel_exact";
17555 let _gate_lock = lock_gate_counters();
17556 if !have_ffmpeg() {
17557 eprintln!("SKIP {NAME}: no ffmpeg");
17558 return;
17559 }
17560 if !have_affine_aomenc() {
17561 eprintln!(
17562 "SKIP {NAME}: no affine-capable aomenc at {} (scripts/build-aom-affine-oracle.sh)",
17563 affine_aomenc_path().display()
17564 );
17565 return;
17566 }
17567 let (width, height, frame_count) = (64usize, 64usize, 24usize);
17568 let duration = frame_count as f64 / 25.0;
17569 // Both depths: his own AV1 library is yuv420p10le throughout, and a
17570 // 10-bit AFFINE warp runs the same `warp_affine` over wider samples.
17571 for depth in [8u32, 10u32] {
17572 // `-t` is the real bound on mandelbrot (it ignores `end_pts` and
17573 // has hung a gate for an hour); the 96x96 source is rotated and
17574 // then stretched horizontally only, and cropped back to 64x64.
17575 let source = format!(
17576 "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\
17577 scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}"
17578 );
17579 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
17580 let mut ff_args: Vec<&str> =
17581 vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt];
17582 // y4m has no official 10-bit tag, same as the 10-bit gate above.
17583 if depth == 10 {
17584 ff_args.extend(["-strict", "-1"]);
17585 }
17586 let duration_arg = duration.to_string();
17587 ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]);
17588 let y4m = Command::new("ffmpeg")
17589 .args(&ff_args)
17590 .stdin(Stdio::null())
17591 .stdout(Stdio::piped())
17592 .stderr(Stdio::piped())
17593 .output()
17594 .expect("ffmpeg failed to run");
17595 assert!(
17596 y4m.status.success(),
17597 "ffmpeg fixture: {}",
17598 String::from_utf8_lossy(&y4m.stderr)
17599 );
17600 let bit_depth = format!("--bit-depth={depth}");
17601 let input_bit_depth = format!("--input-bit-depth={depth}");
17602 let args: Vec<&str> = vec![
17603 "--codec=av1",
17604 "--passes=1",
17605 "--end-usage=q",
17606 "--cq-level=45",
17607 "--cpu-used=0",
17608 "--kf-max-dist=1000",
17609 "--threads=1",
17610 "--row-mt=0",
17611 "--auto-alt-ref=0",
17612 "--lag-in-frames=0",
17613 "--enable-fwd-kf=0",
17614 "--enable-order-hint=1",
17615 "--enable-global-motion=1",
17616 "--enable-warped-motion=0",
17617 "--enable-obmc=0",
17618 "--tune-content=default",
17619 "--enable-masked-comp=0",
17620 "--enable-interintra-comp=0",
17621 "--enable-onesided-comp=0",
17622 "--enable-rect-partitions=0",
17623 "--enable-ab-partitions=0",
17624 "--enable-1to4-partitions=0",
17625 "--enable-filter-intra=0",
17626 "--enable-smooth-intra=0",
17627 "--enable-paeth-intra=0",
17628 "--enable-directional-intra=0",
17629 "--enable-angle-delta=0",
17630 "--enable-tx-size-search=0",
17631 "--enable-cdef=0",
17632 "--enable-restoration=0",
17633 "--max-partition-size=32",
17634 "--min-partition-size=32",
17635 "--enable-palette=0",
17636 "--enable-intrabc=0",
17637 "--enable-cfl-intra=0",
17638 "--enable-ref-frame-mvs=0",
17639 &bit_depth,
17640 &input_bit_depth,
17641 "--obu",
17642 "-o",
17643 "-",
17644 "-",
17645 ];
17646 let mut child = Command::new(affine_aomenc_path())
17647 .args(&args)
17648 .stdin(Stdio::piped())
17649 .stdout(Stdio::piped())
17650 .stderr(Stdio::piped())
17651 .spawn()
17652 .expect("affine aomenc failed to start");
17653 child
17654 .stdin
17655 .take()
17656 .expect("aomenc stdin")
17657 .write_all(&y4m.stdout)
17658 .expect("writing y4m to aomenc");
17659 let out = child.wait_with_output().expect("aomenc failed to run");
17660 assert!(
17661 out.status.success(),
17662 "aomenc refused the fixture: {}",
17663 String::from_utf8_lossy(&out.stderr)
17664 );
17665 let stream = out.stdout;
17666 let before = crate::decode::affine_gm_hits();
17667 let frames =
17668 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} ({depth}-bit): {e}"));
17669 let ffmpeg_frames = if depth == 10 {
17670 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
17671 } else {
17672 ffmpeg_decode_sequence(&stream, width, height, frame_count)
17673 };
17674 assert_eq!(frames.len(), frame_count);
17675 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17676 assert_eq!(got.y, want.y, "{NAME} {depth}-bit frame {i} luma vs ffmpeg");
17677 assert_eq!(got.u, want.u, "{NAME} {depth}-bit frame {i} U vs ffmpeg");
17678 assert_eq!(got.v, want.v, "{NAME} {depth}-bit frame {i} V vs ffmpeg");
17679 }
17680 let hits = crate::decode::affine_gm_hits() - before;
17681 assert!(
17682 hits > 0,
17683 "{NAME} ({depth}-bit): decoded pixel-exact but no block was predicted through a \
17684 6-parameter global-motion warp -- the AFFINE path is unexercised"
17685 );
17686 eprintln!("{NAME}: {depth}-bit, {frame_count} frames pixel-exact, affine_gm_hits={hits}");
17687 }
17688 }
17689
17690 /// lane-gmaffine r1: the two 8x8-LEAF motion gates. `decode_inter_block8`
17691 /// is a separate function from [`decode_inter_block`], and until this
17692 /// round it refused both `GLOBALMV` ("GLOBALMV (round 3)") and
17693 /// `WARPED_CAUSAL` at that size while the 16x16+ leaf had implemented
17694 /// both for rounds. The reason no earlier gate caught it: the existing
17695 /// 8x8 OBMC gate clamps `--max-partition-size=32` and aomenc's RD then
17696 /// never splits down to a clean 8x8 leaf (that gate has never fired in
17697 /// 80 attempts). `--min-partition-size=8 --max-partition-size=8` removes
17698 /// the choice entirely -- every inter leaf in the stream IS an 8x8 one,
17699 /// so the leaf path is exercised by construction rather than by luck.
17700 ///
17701 /// Content is the affine gate's rotating/zooming mandelbrot (global
17702 /// motion the encoder can actually model), and the hit counters
17703 /// (`globalmv_hits_8` / `warp_hits_8`) are 8x8-leaf-specific: a
17704 /// 16x16-leaf GLOBALMV or warp cannot satisfy them.
17705 fn run_8x8_leaf_motion_gate(
17706 name: &str,
17707 global_motion: bool,
17708 counter: fn() -> usize,
17709 ) {
17710 // 72x64: `decode_inter_block8` is reached ONLY through the
17711 // true-edge-straddling 16x16 path (an interior 16x16
17712 // PARTITION_SPLIT is still refused by name), so the frame is 8
17713 // luma columns wider than its last whole superblock -- every 16x16
17714 // block in that right-hand strip is cut on ONE axis and decodes as
17715 // four 8x8 leaves by construction. `--min-partition-size=16` keeps
17716 // the interior out of the still-refused sub-16x16 case.
17717 let (width, height, frame_count) = (64usize, 64usize, 24usize);
17718 let duration = frame_count as f64 / 25.0;
17719 // The encoder's own RD still chooses WHICH 8x8 leaf codes GLOBALMV /
17720 // WARPED_CAUSAL, and at some quantisers it picks a rect partition at
17721 // 16x16 (still refused) or a non-LAST reference (still refused at the
17722 // 8x8 leaf) before ever reaching one. So sweep a few quantisers and
17723 // require at least one attempt, at each depth, that BOTH decodes
17724 // pixel-exact AND fires the counter -- a refusing attempt is recorded,
17725 // never a pass (class `gate-skips-on-its-own-failure`).
17726 let mut fired_any = [false; 2];
17727 let mut notes: Vec<String> = Vec::new();
17728 for (di, depth) in [8u32, 10u32].into_iter().enumerate() {
17729 for cq in [32u32, 45, 55] {
17730 let cq_arg = format!("--cq-level={cq}");
17731 let max_part_arg = format!(
17732 "--max-partition-size={}",
17733 std::env::var("EC_8X8_MAXPART").unwrap_or_else(|_| "8".into())
17734 );
17735 let source = format!(
17736 "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\
17737 scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}"
17738 );
17739 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
17740 let mut ff_args: Vec<&str> =
17741 vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt];
17742 if depth == 10 {
17743 ff_args.extend(["-strict", "-1"]);
17744 }
17745 let duration_arg = duration.to_string();
17746 ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]);
17747 let y4m = Command::new("ffmpeg")
17748 .args(&ff_args)
17749 .stdin(Stdio::null())
17750 .stdout(Stdio::piped())
17751 .stderr(Stdio::piped())
17752 .output()
17753 .expect("ffmpeg failed to run");
17754 assert!(
17755 y4m.status.success(),
17756 "ffmpeg fixture: {}",
17757 String::from_utf8_lossy(&y4m.stderr)
17758 );
17759 let bit_depth = format!("--bit-depth={depth}");
17760 let input_bit_depth = format!("--input-bit-depth={depth}");
17761 let gm_arg = format!("--enable-global-motion={}", u8::from(global_motion));
17762 let warp_arg = format!("--enable-warped-motion={}", u8::from(!global_motion));
17763 let args: Vec<&str> = vec![
17764 "--codec=av1",
17765 "--passes=1",
17766 "--end-usage=q",
17767 &cq_arg,
17768 "--cpu-used=0",
17769 "--kf-max-dist=1000",
17770 "--threads=1",
17771 "--row-mt=0",
17772 "--auto-alt-ref=0",
17773 "--lag-in-frames=0",
17774 "--enable-fwd-kf=0",
17775 "--enable-order-hint=1",
17776 &gm_arg,
17777 &warp_arg,
17778 "--enable-obmc=0",
17779 "--tune-content=default",
17780 "--enable-masked-comp=0",
17781 "--enable-interintra-comp=0",
17782 "--enable-onesided-comp=0",
17783 "--enable-rect-partitions=0",
17784 "--enable-ab-partitions=0",
17785 "--enable-1to4-partitions=0",
17786 "--enable-filter-intra=0",
17787 "--enable-smooth-intra=0",
17788 "--enable-paeth-intra=0",
17789 "--enable-directional-intra=0",
17790 "--enable-angle-delta=0",
17791 "--enable-tx-size-search=0",
17792 "--enable-cdef=0",
17793 "--enable-restoration=0",
17794 &max_part_arg,
17795 "--min-partition-size=8",
17796 "--enable-palette=0",
17797 "--enable-intrabc=0",
17798 "--enable-cfl-intra=0",
17799 "--enable-ref-frame-mvs=0",
17800 &bit_depth,
17801 &input_bit_depth,
17802 "--obu",
17803 "-o",
17804 "-",
17805 "-",
17806 ];
17807 let mut child = Command::new(aomenc_path())
17808 .args(&args)
17809 .stdin(Stdio::piped())
17810 .stdout(Stdio::piped())
17811 .stderr(Stdio::piped())
17812 .spawn()
17813 .expect("aomenc failed to start");
17814 child
17815 .stdin
17816 .take()
17817 .expect("aomenc stdin")
17818 .write_all(&y4m.stdout)
17819 .expect("writing y4m to aomenc");
17820 let out = child.wait_with_output().expect("aomenc failed to run");
17821 assert!(
17822 out.status.success(),
17823 "aomenc refused the fixture: {}",
17824 String::from_utf8_lossy(&out.stderr)
17825 );
17826 let stream = out.stdout;
17827 let before = counter();
17828 let frames = match decode_stream(&stream) {
17829 Ok(f) => f,
17830 Err(e) => {
17831 let msg = e.to_string();
17832 assert!(
17833 msg.contains("unsupported"),
17834 "{name} ({depth}-bit, cq {cq}) failed outright: {msg}"
17835 );
17836 notes.push(format!("{depth}-bit cq {cq}: {msg}"));
17837 continue;
17838 }
17839 };
17840 let ffmpeg_frames = if depth == 10 {
17841 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
17842 } else {
17843 ffmpeg_decode_sequence(&stream, width, height, frame_count)
17844 };
17845 assert_eq!(frames.len(), frame_count);
17846 let hits = counter() - before;
17847 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17848 assert_eq!(got.y, want.y, "{name} {depth}-bit frame {i} luma vs ffmpeg");
17849 assert_eq!(got.u, want.u, "{name} {depth}-bit frame {i} U vs ffmpeg");
17850 assert_eq!(got.v, want.v, "{name} {depth}-bit frame {i} V vs ffmpeg");
17851 }
17852 if hits == 0 {
17853 notes.push(format!(
17854 "{depth}-bit cq {cq}: {frame_count} frames pixel-exact but 0 8x8-leaf hits"
17855 ));
17856 continue;
17857 }
17858 fired_any[di] = true;
17859 eprintln!(
17860 "{name}: {depth}-bit cq {cq}, {frame_count} frames pixel-exact, 8x8 hits={hits}"
17861 );
17862 }
17863 }
17864 assert!(
17865 fired_any[0] && fired_any[1],
17866 "{name}: no attempt both decoded pixel-exact and fired the 8x8 leaf \
17867 (8-bit fired {}, 10-bit fired {}):\n{}",
17868 fired_any[0], fired_any[1], notes.join("\n")
17869 );
17870 }
17871
17872 /// lane-gmaffine r1 item (3): `GLOBALMV` at an 8x8 leaf, ROTZOOM global
17873 /// motion, warp built from the frame's own model.
17874 #[test]
17875 fn a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact() {
17876 const NAME: &str = "a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact";
17877 let _gate_lock = lock_gate_counters();
17878 if !have_ffmpeg() {
17879 eprintln!("SKIP {NAME}: no ffmpeg");
17880 return;
17881 }
17882 if !have_aomenc() {
17883 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17884 return;
17885 }
17886 run_8x8_leaf_motion_gate(NAME, true, crate::decode::globalmv_hits_8);
17887 }
17888
17889 /// lane-gmaffine r1 item (2): `WARPED_CAUSAL` at an 8x8 leaf --
17890 /// findSamples + `av1_find_projection` + the warp filter at BLOCK_8X8.
17891 #[test]
17892 fn a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact() {
17893 const NAME: &str = "a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact";
17894 let _gate_lock = lock_gate_counters();
17895 if !have_ffmpeg() {
17896 eprintln!("SKIP {NAME}: no ffmpeg");
17897 return;
17898 }
17899 if !have_aomenc() {
17900 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17901 return;
17902 }
17903 run_8x8_leaf_motion_gate(NAME, false, crate::decode::warp_hits_8);
17904 }
17905
17906 /// lane-rect16 r1/r2: a plain default-settings aomenc run over lavfi
17907 /// `mandelbrot` (`--cpu-used=4 --end-usage=q --cq-level=32`, no
17908 /// `--enable-*` flags) used to refuse frame 0 outright with "a partition
17909 /// below 16x16 other than a clean split". r1 root-caused the FIRST hit to
17910 /// a `PARTITION_VERT_B` `partition_w16` symbol at mi=(3,2) and wired it
17911 /// (left 8x16 real `decode_block_rect` strip + two stacked 8x8
17912 /// `decode_leaf8` leaves on the right). r2 re-measured after that fix
17913 /// (`decision-before-quantiser`-shaped: don't trust a stale premise) and
17914 /// found this stream's REAL first-hit blocker in z-order is earlier, at
17915 /// mi=(0,7): a plain `PARTITION_HORZ`. That arm is now wired too
17916 /// (`decode_leaf_rect`, sibling to `decode_leaf8` but real-mi-addressed
17917 /// for a non-square strip) -- `horz_vert_intra_hits` proves it fires.
17918 /// This exact stream's own HORZ block at mi=(0,7) is *coded* (real
17919 /// coefficients), which is NOT ported (same ceiling as VERT_B's own
17920 /// non-skip refusal -- no rectangular-transform coefficient tables at
17921 /// this size), so decode still stops there and `vert_b_intra_hits`
17922 /// never gets a chance to increment on this particular stream. This gate
17923 /// proves the HORZ arm fires and the OLD (now-false) two-clause refusal
17924 /// never reappears, not a pixel-exact decode of this stream.
17925 #[test]
17926 fn a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm() {
17927 const NAME: &str = "a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm";
17928 let _gate_lock = lock_gate_counters();
17929 if !have_ffmpeg() {
17930 eprintln!("SKIP {NAME}: no ffmpeg");
17931 return;
17932 }
17933 if !have_aomenc() {
17934 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17935 return;
17936 }
17937 let (width, height) = (192usize, 128usize);
17938 let y4m = Command::new("ffmpeg")
17939 .args([
17940 "-v",
17941 "error",
17942 "-f",
17943 "lavfi",
17944 "-i",
17945 &format!("mandelbrot=size={width}x{height}"),
17946 "-pix_fmt",
17947 "yuv420p",
17948 "-t",
17949 "1",
17950 "-f",
17951 "yuv4mpegpipe",
17952 "-",
17953 ])
17954 .stdin(Stdio::null())
17955 .stdout(Stdio::piped())
17956 .stderr(Stdio::piped())
17957 .output()
17958 .expect("ffmpeg failed to run");
17959 assert!(
17960 y4m.status.success(),
17961 "ffmpeg fixture: {}",
17962 String::from_utf8_lossy(&y4m.stderr)
17963 );
17964 let mut child = Command::new(aomenc_path())
17965 .args([
17966 "--threads=1",
17967 "--row-mt=0",
17968 "--sb-size=64",
17969 "--cpu-used=4",
17970 "--end-usage=q",
17971 "--cq-level=32",
17972 "--passes=1",
17973 "--obu",
17974 "-o",
17975 "-",
17976 "-",
17977 ])
17978 .stdin(Stdio::piped())
17979 .stdout(Stdio::piped())
17980 .stderr(Stdio::piped())
17981 .spawn()
17982 .expect("aomenc failed to start");
17983 child
17984 .stdin
17985 .take()
17986 .expect("aomenc stdin")
17987 .write_all(&y4m.stdout)
17988 .expect("writing y4m to aomenc");
17989 let out = child.wait_with_output().expect("aomenc failed to run");
17990 assert!(
17991 out.status.success(),
17992 "aomenc refused the fixture: {}",
17993 String::from_utf8_lossy(&out.stderr)
17994 );
17995 let stream = out.stdout;
17996 // lane-rect16 r2: the recipe above was missing `--passes=1` --
17997 // without it aomenc silently ran 2-pass and wrote nothing to stdout
17998 // on pass 1 (still exit 0), so this gate always decoded an EMPTY
17999 // stream and never actually exercised the arm it claims to gate.
18000 assert!(
18001 !stream.is_empty(),
18002 "{NAME}: aomenc wrote an empty stream (missing --passes=1?)"
18003 );
18004 let result = decode_stream(&stream);
18005 // The now-lifted false claim ("codes only the square arms below
18006 // 16x16") must never appear again.
18007 if let Err(e) = &result {
18008 let msg = e.to_string();
18009 assert!(
18010 !msg.contains("this decoder codes only the square arms below 16x16"),
18011 "{NAME}: the OLD (disproved) refusal reappeared: {msg}"
18012 );
18013 }
18014 assert!(
18015 crate::decode::horz_vert_intra_hits() > 0,
18016 "{NAME}: the plain PARTITION_HORZ/VERT arm never fired on this stream (regression -- \
18017 it fired deterministically at mi=(0,7) when this gate was written)"
18018 );
18019 eprintln!(
18020 "{NAME}: horz_vert_intra_hits={}, vert_b_intra_hits={}, decode result: {:?}",
18021 crate::decode::horz_vert_intra_hits(),
18022 crate::decode::vert_b_intra_hits(),
18023 result.as_ref().map(|f| f.len()).map_err(|e| e.to_string())
18024 );
18025 }
18026 /// lane-rectx r3: a real `aomenc` stream whose 16x16-level
18027 /// `PARTITION_HORZ`/`PARTITION_VERT` strips are CODED (non-skip), i.e.
18028 /// carry genuine `TX_16X8`/`TX_8X16` luma coefficients and their
18029 /// `TX_8X4`/`TX_4X8` chroma halves through [`decode_leaf_rect`]'s
18030 /// lane-rectx arm -- the refusal "a coded (non-skip) HORZ/VERT rect strip
18031 /// below 16x16" this round lifts. `--min-partition-size=8
18032 /// --max-partition-size=32 --enable-rect-partitions=1` is what makes
18033 /// aomenc reach for a 16x8 leaf at all; mandelbrot at `cq-level=24` is
18034 /// what makes those leaves non-skip (a gradient fixture codes them all
18035 /// away). `--reduced-tx-type-set=1` pins the five-symbol
18036 /// `EXT_TX_SET_DTT4_IDTX` alphabet: without it aomenc also writes
18037 /// `V_DCT`/`H_DCT`, whose 1D tx classes [`read_coeffs_rect`] still
18038 /// refuses by name (see the r3 report's open residue), so a `=0` run
18039 /// would prove nothing about the 2D path it does support.
18040 ///
18041 /// r2 shipped this path unproven; it was wrong. `TxbSet::LumaRect16x8`
18042 /// read its `tx_type` symbol from the 16x16 row, but libaom's
18043 /// `read_tx_type` indexes `intra_ext_tx_cdf[eset][txsize_sqr_map[tx_size]]`
18044 /// and `txsize_sqr_map[TX_16X8] == TX_8X8` -- a five-symbol CDF where a
18045 /// seven-symbol one belonged, desyncing at the FIRST coded rect leaf
18046 /// (whole frame wrong from pixel (0,0)).
18047 #[test]
18048 fn a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact() {
18049 const NAME: &str =
18050 "a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact";
18051 let _gate_lock = lock_gate_counters();
18052 if !have_ffmpeg() {
18053 eprintln!("SKIP {NAME}: no ffmpeg");
18054 return;
18055 }
18056 if !have_aomenc() {
18057 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18058 return;
18059 }
18060 let (width, height) = (64usize, 64usize);
18061 let y4m = Command::new("ffmpeg")
18062 .args([
18063 "-v",
18064 "error",
18065 "-f",
18066 "lavfi",
18067 "-i",
18068 &format!("mandelbrot=size={width}x{height}:start_x=-0.6"),
18069 "-pix_fmt",
18070 "yuv420p",
18071 "-t",
18072 "1",
18073 "-vframes",
18074 "1",
18075 "-f",
18076 "yuv4mpegpipe",
18077 "-",
18078 ])
18079 .stdin(Stdio::null())
18080 .stdout(Stdio::piped())
18081 .stderr(Stdio::piped())
18082 .output()
18083 .expect("ffmpeg failed to run");
18084 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
18085 let encode = || {
18086 let mut child = Command::new(aomenc_path())
18087 .args([
18088 "--codec=av1",
18089 "--passes=1",
18090 "--end-usage=q",
18091 "--cq-level=16",
18092 "--cpu-used=4",
18093 "--threads=1",
18094 "--row-mt=0",
18095 "--sb-size=64",
18096 "--kf-max-dist=0",
18097 "--enable-rect-partitions=1",
18098 "--enable-ab-partitions=0",
18099 "--enable-1to4-partitions=0",
18100 "--enable-tx-size-search=0",
18101 // Filter intra on a strip is a separate, still-refused
18102 // predictor (`filter intra on a HORZ/VERT strip`); this
18103 // gate is about the rect RESIDUAL path, so it is off here
18104 // and covered by the square filter-intra gate instead.
18105 "--enable-filter-intra=0",
18106 "--reduced-tx-type-set=1",
18107 "--min-partition-size=8",
18108 "--max-partition-size=32",
18109 "--obu",
18110 "-o",
18111 "-",
18112 "-",
18113 ])
18114 .stdin(Stdio::piped())
18115 .stdout(Stdio::piped())
18116 .stderr(Stdio::piped())
18117 .spawn()
18118 .expect("aomenc failed to start");
18119 child
18120 .stdin
18121 .take()
18122 .expect("aomenc stdin")
18123 .write_all(&y4m.stdout)
18124 .expect("writing y4m to aomenc");
18125 let out = child.wait_with_output().expect("aomenc failed to run");
18126 assert!(
18127 out.status.success(),
18128 "aomenc refused the fixture: {}",
18129 String::from_utf8_lossy(&out.stderr)
18130 );
18131 out.stdout
18132 };
18133 // The fixture rule: an encoder output is only a pin if it reproduces.
18134 let stream = encode();
18135 assert_eq!(stream, encode(), "{NAME}: aomenc output is not reproducible for this recipe");
18136 let before = crate::decode::rect_leaf_coeff_hits();
18137 let frames = decode_stream(&stream)
18138 .unwrap_or_else(|e| panic!("{NAME}: decode failed, not a pixel mismatch: {e}"));
18139 let fired = crate::decode::rect_leaf_coeff_hits() - before;
18140 assert!(
18141 fired > 0,
18142 "{NAME}: the stream decoded but no coded (non-skip) rect leaf fired -- \
18143 the gate proves nothing"
18144 );
18145 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
18146 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame");
18147 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
18148 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18149 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg ({fired} coded rect leaves)");
18150 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
18151 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
18152 }
18153 eprintln!("{NAME}: pixel-exact, rect_leaf_coeff_hits={fired}");
18154 }
18155
18156 /// lane-rectx r5: the same 16x8/8x16 rect leaves, but this time proving
18157 /// what a LATER, non-strip block reads from them. `decode_leaf_rect` took
18158 /// the mi-exact intra mode map in r4; `decode_block`/`decode_block_rect`/
18159 /// `decode_block_rect64` did not, so a 32x16 strip whose left neighbour was
18160 /// a 16x8 leaf still read the coarse per-16x16 `left_mode` slot -- which no
18161 /// sub-16x16 block ever writes -- and picked a DIFFERENT `kf_y_mode` CDF row
18162 /// for the same decoded mode value. The stream stayed in sync through mode
18163 /// info (`EC_TRACE_MODE_STEP` ranges match up to that symbol) and then
18164 /// diverged inside the block's own coefficients: the whole bottom-right
18165 /// 32x32 quadrant of this fixture decoded wrong (1650 bytes) while the
18166 /// three earlier quadrants were exact -- wrong pixels returned as success.
18167 /// `mode_mi_override_hits` counts exactly the reads where the mi-exact
18168 /// neighbour disagrees with the coarse slot, so a regression that drops the
18169 /// override again fails the counter as well as the pixels.
18170 #[test]
18171 fn a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact() {
18172 const NAME: &str =
18173 "a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact";
18174 let _gate_lock = lock_gate_counters();
18175 if !have_ffmpeg() {
18176 eprintln!("SKIP {NAME}: no ffmpeg");
18177 return;
18178 }
18179 if !have_aomenc() {
18180 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18181 return;
18182 }
18183 let (width, height) = (64usize, 64usize);
18184 let y4m = Command::new("ffmpeg")
18185 .args([
18186 "-v", "error", "-f", "lavfi", "-i",
18187 &format!("rgbtestsrc=size={width}x{height}"),
18188 "-pix_fmt", "yuv420p", "-t", "1", "-vframes", "1", "-f", "yuv4mpegpipe", "-",
18189 ])
18190 .stdin(Stdio::null())
18191 .stdout(Stdio::piped())
18192 .stderr(Stdio::piped())
18193 .output()
18194 .expect("ffmpeg failed to run");
18195 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
18196 // Two swept cells of the r4 sweep that decoded to completion with
18197 // WRONG pixels (1714 and 1650 bytes): `--reduced-tx-type-set` and
18198 // `--enable-filter-intra` are the two axes that move which block sizes
18199 // aomenc reaches for here; both arms are pinned.
18200 let mut total_overrides = 0usize;
18201 for (rtx, filter_intra) in [("1", "0"), ("0", "1")] {
18202 let encode = || {
18203 let mut child = Command::new(aomenc_path())
18204 .args([
18205 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32",
18206 "--cpu-used=4", "--threads=1", "--row-mt=0", "--sb-size=64",
18207 "--kf-max-dist=0", "--enable-rect-partitions=1",
18208 "--enable-ab-partitions=0", "--enable-1to4-partitions=0",
18209 "--enable-tx-size-search=0", "--enable-cdef=0",
18210 "--enable-restoration=0",
18211 &format!("--enable-filter-intra={filter_intra}"),
18212 &format!("--reduced-tx-type-set={rtx}"),
18213 "--min-partition-size=8", "--max-partition-size=32",
18214 "--obu", "-o", "-", "-",
18215 ])
18216 .stdin(Stdio::piped())
18217 .stdout(Stdio::piped())
18218 .stderr(Stdio::piped())
18219 .spawn()
18220 .expect("aomenc failed to start");
18221 child
18222 .stdin
18223 .take()
18224 .expect("aomenc stdin")
18225 .write_all(&y4m.stdout)
18226 .expect("writing y4m to aomenc");
18227 let out = child.wait_with_output().expect("aomenc failed to run");
18228 assert!(
18229 out.status.success(),
18230 "aomenc refused the fixture: {}",
18231 String::from_utf8_lossy(&out.stderr)
18232 );
18233 out.stdout
18234 };
18235 let stream = encode();
18236 assert_eq!(
18237 stream,
18238 encode(),
18239 "{NAME}: aomenc output is not reproducible (rtx={rtx} filter_intra={filter_intra})"
18240 );
18241 let before = crate::decode::mode_mi_override_hits();
18242 let frames = decode_stream(&stream).unwrap_or_else(|e| {
18243 panic!("{NAME}: decode failed (rtx={rtx} filter_intra={filter_intra}): {e}")
18244 });
18245 // Counted only on an attempt that actually decoded AND is compared
18246 // below -- a refusal never contributes to the firing assert.
18247 let overrides = crate::decode::mode_mi_override_hits() - before;
18248 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
18249 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame");
18250 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
18251 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18252 assert_eq!(
18253 got.y, want.y,
18254 "{NAME} frame {i} luma vs ffmpeg (rtx={rtx} filter_intra={filter_intra}, \
18255 {overrides} mi-exact mode overrides)"
18256 );
18257 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (rtx={rtx})");
18258 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (rtx={rtx})");
18259 }
18260 total_overrides += overrides;
18261 }
18262 assert!(
18263 total_overrides > 0,
18264 "{NAME}: no non-strip block ever read a mi-exact neighbour that disagreed with its \
18265 coarse slot -- the gate proves nothing"
18266 );
18267 eprintln!("{NAME}: pixel-exact, mode_mi_override_hits={total_overrides}");
18268 }
18269
18270 /// lane-cfl r1: the chroma intra-edge FILTER TYPE is the neighbour's
18271 /// `uv_mode` (libaom `get_filt_type`, reconintra.c: `chroma_above_mbmi`/
18272 /// `chroma_left_mbmi` -> `is_smooth` on `uv_mode`), and two whole decode
18273 /// paths passed a hardcoded `false` for it -- `decode_leaf_8x8` (every
18274 /// 8x8 leaf of a SPLIT) and `decode_leaf_rect` (every rect strip below
18275 /// 16x16), on a stale "chroma stays false (exact) until a smooth/paeth
18276 /// uv_mode can reach decode at all" comment. On top of that the coarse
18277 /// `above_uv_mode`/`left_uv_mode` cells are 16px-granular and their
18278 /// `for cell in 0..w / SUB` write runs ZERO times for any block below
18279 /// 16x16, so even the paths that DID read them saw whatever a
18280 /// 16x16-or-larger block had left there (class: context read from one
18281 /// cell / neighbour map at the wrong granularity). Result on this
18282 /// recipe: luma byte-exact, entropy ladder identical, and 40 U + 86 V
18283 /// chroma bytes wrong -- every one of them downstream of one 4x4 chroma
18284 /// block at mi(8,12) whose D135 + `angle_delta_uv=-3` left edge was
18285 /// filtered at the wrong strength (`ft=0` where the instrumented aomdec
18286 /// prints `ft=1`, left edge `95,59,30,28` vs `90,61,37,29`).
18287 ///
18288 /// Both arms hard-assert per-attempt counters for the two chroma block
18289 /// shapes involved (`UV_CFL_PRED` blocks, nonzero `angle_delta_uv`
18290 /// blocks) plus the mi-exact UV-neighbour override, and are counted only
18291 /// on an attempt that decoded AND is pixel-compared.
18292 #[test]
18293 fn a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact()
18294 {
18295 const NAME: &str = "a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact";
18296 let _gate_lock = lock_gate_counters();
18297 if !have_ffmpeg() {
18298 eprintln!("SKIP {NAME}: no ffmpeg");
18299 return;
18300 }
18301 if !have_aomenc() {
18302 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18303 return;
18304 }
18305 let mut compared = 0usize;
18306 let (width, height) = (64usize, 64usize);
18307 // 8-bit arm = the r5 residue cell ("mandfi161"); 10-bit arm = its
18308 // twin through the same recipe at `--bit-depth=10`.
18309 for depth in [8usize, 10] {
18310 let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
18311 let y4m = Command::new("ffmpeg")
18312 .args([
18313 "-v", "error", "-f", "lavfi", "-i",
18314 &format!("mandelbrot=size={width}x{height}:start_x=-0.6"),
18315 "-pix_fmt", pix, "-strict", "-1", "-t", "1", "-vframes", "1",
18316 "-f", "yuv4mpegpipe", "-",
18317 ])
18318 .stdin(Stdio::null())
18319 .stdout(Stdio::piped())
18320 .stderr(Stdio::piped())
18321 .output()
18322 .expect("ffmpeg failed to run");
18323 assert!(
18324 y4m.status.success(),
18325 "{NAME}: ffmpeg fixture (depth={depth}): {}",
18326 String::from_utf8_lossy(&y4m.stderr)
18327 );
18328 let encode = || {
18329 let mut child = Command::new(aomenc_path())
18330 .args([
18331 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=16",
18332 "--cpu-used=4", "--threads=1", "--row-mt=0", "--sb-size=64",
18333 "--kf-max-dist=0", "--enable-rect-partitions=1",
18334 "--enable-ab-partitions=0", "--enable-1to4-partitions=0",
18335 "--enable-tx-size-search=0", "--enable-filter-intra=1",
18336 "--reduced-tx-type-set=1", "--min-partition-size=8",
18337 "--max-partition-size=32",
18338 &format!("--input-bit-depth={depth}"),
18339 &format!("--bit-depth={depth}"),
18340 "--obu", "-o", "-", "-",
18341 ])
18342 .stdin(Stdio::piped())
18343 .stdout(Stdio::piped())
18344 .stderr(Stdio::piped())
18345 .spawn()
18346 .expect("aomenc failed to start");
18347 child
18348 .stdin
18349 .take()
18350 .expect("aomenc stdin")
18351 .write_all(&y4m.stdout)
18352 .expect("writing y4m to aomenc");
18353 let out = child.wait_with_output().expect("aomenc failed to run");
18354 assert!(
18355 out.status.success(),
18356 "aomenc refused the fixture (depth={depth}): {}",
18357 String::from_utf8_lossy(&out.stderr)
18358 );
18359 out.stdout
18360 };
18361 let stream = encode();
18362 assert_eq!(
18363 stream,
18364 encode(),
18365 "{NAME}: aomenc output is not reproducible (depth={depth})"
18366 );
18367 let before_cfl = crate::decode::cfl_block_hits();
18368 let before_angle = crate::decode::uv_angle_delta_hits();
18369 let before_uv = crate::decode::uv_mode_mi_override_hits();
18370 let frames = match decode_stream(&stream) {
18371 Ok(frames) => frames,
18372 // Only a NAMED refusal is tolerated (COMMON rule): the 10-bit
18373 // twin of this recipe still stops at another lane's open
18374 // sub-16 AB-partition / strip-filter-intra refusals, so it
18375 // cannot be compared yet. Any other error is a failure, and
18376 // `compared` below keeps the test from passing vacuously.
18377 Err(e) => {
18378 let msg = e.to_string();
18379 assert!(
18380 msg.contains("unsupported"),
18381 "{NAME}: decode failed (depth={depth}): {msg}"
18382 );
18383 eprintln!("{NAME}: depth={depth} arm refused (not compared): {msg}");
18384 continue;
18385 }
18386 };
18387 compared += 1;
18388 // Read only on an attempt that decoded AND is compared below.
18389 let cfl_blocks = crate::decode::cfl_block_hits() - before_cfl;
18390 let angle_blocks = crate::decode::uv_angle_delta_hits() - before_angle;
18391 let uv_overrides = crate::decode::uv_mode_mi_override_hits() - before_uv;
18392 let ffmpeg_frames = if depth == 10 {
18393 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
18394 } else {
18395 ffmpeg_decode_sequence(&stream, width, height, frames.len())
18396 };
18397 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame (depth={depth})");
18398 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
18399 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18400 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (depth={depth})");
18401 assert_eq!(
18402 got.u, want.u,
18403 "{NAME} frame {i} U vs ffmpeg (depth={depth}, {cfl_blocks} CFL blocks, \
18404 {angle_blocks} nonzero-angle_delta_uv blocks, {uv_overrides} mi-exact UV \
18405 neighbour overrides)"
18406 );
18407 assert_eq!(
18408 got.v, want.v,
18409 "{NAME} frame {i} V vs ffmpeg (depth={depth}, {cfl_blocks} CFL blocks, \
18410 {angle_blocks} nonzero-angle_delta_uv blocks, {uv_overrides} mi-exact UV \
18411 neighbour overrides)"
18412 );
18413 }
18414 assert!(
18415 cfl_blocks > 0,
18416 "{NAME}: no UV_CFL_PRED block decoded (depth={depth}) -- the gate proves nothing"
18417 );
18418 assert!(
18419 angle_blocks > 0,
18420 "{NAME}: no nonzero angle_delta_uv chroma block decoded (depth={depth}) -- \
18421 the chroma intra-edge filter path never ran"
18422 );
18423 assert!(
18424 uv_overrides > 0,
18425 "{NAME}: no chroma edge-filter read ever took a mi-exact UV neighbour that \
18426 disagreed with its coarse 16x16 slot (depth={depth}) -- the r1 defect is \
18427 not exercised"
18428 );
18429 eprintln!(
18430 "{NAME}: pixel-exact at {depth}-bit, cfl_blocks={cfl_blocks} \
18431 angle_delta_uv_blocks={angle_blocks} uv_mi_overrides={uv_overrides}"
18432 );
18433 }
18434 assert!(
18435 compared > 0,
18436 "{NAME}: every arm refused -- the gate compared no pixels at all"
18437 );
18438 }
18439
18440 /// lane-reelckf r1: ReelC's key frames decoded with no refusal and WRONG
18441 /// CHROMA (luma bit-exact at every one of ten seek points), from two
18442 /// defects this gate pins:
18443 ///
18444 /// 1. a SKIPPED intra block whose `uv_mode` is `UV_CFL_PRED` still
18445 /// predicts with the CfL term -- libaom
18446 /// `predict_and_reconstruct_intra_block` (decodeframe.c) calls
18447 /// `av1_predict_intra_block_facade` unconditionally and only guards
18448 /// the residual on `mbmi->skip_txfm`. Three skip arms (the 16x16-level
18449 /// 1:4 chroma pair and the two sub-8x8 4x4 groups) dropped it.
18450 /// 2. the chroma intra-edge FILTER TYPE of a 1:4 pair comes from the
18451 /// CHROMA REFERENCE position (libaom `get_intra_edge_filter_type` ->
18452 /// `chroma_above_mbmi`/`chroma_left_mbmi`), not from the closing
18453 /// strip: at the closing strip the above cell is the pair's own first
18454 /// strip, the mi-exact UV map misses and the coarse fallback answers,
18455 /// which flipped `av1_use_intra_edge_upsample` (blk_wh 12 <= 16 for
18456 /// type 0, no upsample for type 1) and moved directional chroma by
18457 /// +-1..3.
18458 ///
18459 /// Recipe is a real `aomenc --sb-size=128 --cpu-used=0` (the shape ReelC
18460 /// uses) with 1:4 partitions and CfL on, both bit depths, and both
18461 /// counters hard-asserted per compared attempt.
18462 #[test]
18463 fn a_real_aomenc_sb128_stream_whose_skipped_cfl_and_1to4_chroma_pairs_decode_pixel_exact() {
18464 const NAME: &str =
18465 "a_real_aomenc_sb128_stream_whose_skipped_cfl_and_1to4_chroma_pairs_decode_pixel_exact";
18466 let _gate_lock = lock_gate_counters();
18467 if !have_ffmpeg() {
18468 eprintln!("SKIP {NAME}: no ffmpeg");
18469 return;
18470 }
18471 if !have_aomenc() {
18472 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18473 return;
18474 }
18475 let mut compared = 0usize;
18476 let (width, height) = (256usize, 256usize);
18477 for depth in [8usize, 10] {
18478 let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
18479 let y4m = Command::new("ffmpeg")
18480 .args([
18481 "-v", "error", "-f", "lavfi", "-i",
18482 &format!(
18483 "mandelbrot=size={width}x{height},\
18484 noise=alls=20:allf=t+u:all_seed=7"
18485 ),
18486 "-pix_fmt", pix, "-strict", "-1", "-t", "1", "-vframes", "1",
18487 "-f", "yuv4mpegpipe", "-",
18488 ])
18489 .stdin(Stdio::null())
18490 .stdout(Stdio::piped())
18491 .stderr(Stdio::piped())
18492 .output()
18493 .expect("ffmpeg failed to run");
18494 assert!(
18495 y4m.status.success(),
18496 "{NAME}: ffmpeg fixture (depth={depth}): {}",
18497 String::from_utf8_lossy(&y4m.stderr)
18498 );
18499 let encode = || {
18500 let mut child = Command::new(aomenc_path())
18501 .args([
18502 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=52",
18503 "--cpu-used=0", "--threads=1", "--row-mt=0", "--sb-size=128",
18504 "--kf-max-dist=0", "--enable-rect-partitions=1",
18505 "--enable-ab-partitions=0", "--enable-1to4-partitions=1",
18506 "--enable-cfl-intra=1", "--enable-tx-size-search=0",
18507 "--enable-filter-intra=0", "--enable-intra-edge-filter=1",
18508 "--reduced-tx-type-set=1", "--min-partition-size=4",
18509 "--max-partition-size=32",
18510 &format!("--input-bit-depth={depth}"),
18511 &format!("--bit-depth={depth}"),
18512 "--obu", "-o", "-", "-",
18513 ])
18514 .stdin(Stdio::piped())
18515 .stdout(Stdio::piped())
18516 .stderr(Stdio::piped())
18517 .spawn()
18518 .expect("aomenc failed to start");
18519 child
18520 .stdin
18521 .take()
18522 .expect("aomenc stdin")
18523 .write_all(&y4m.stdout)
18524 .expect("writing y4m to aomenc");
18525 let out = child.wait_with_output().expect("aomenc failed to run");
18526 assert!(
18527 out.status.success(),
18528 "aomenc refused the fixture (depth={depth}): {}",
18529 String::from_utf8_lossy(&out.stderr)
18530 );
18531 out.stdout
18532 };
18533 let stream = encode();
18534 assert_eq!(
18535 stream,
18536 encode(),
18537 "{NAME}: aomenc output is not reproducible (depth={depth})"
18538 );
18539 let before = crate::decode::reelc_chroma_counters();
18540 let frames = match decode_stream(&stream) {
18541 Ok(frames) => frames,
18542 Err(e) => {
18543 let msg = e.to_string();
18544 assert!(
18545 msg.contains("unsupported"),
18546 "{NAME}: decode failed (depth={depth}): {msg}"
18547 );
18548 eprintln!("{NAME}: depth={depth} arm refused (not compared): {msg}");
18549 continue;
18550 }
18551 };
18552 compared += 1;
18553 // Counters read only on an attempt that decoded AND is compared.
18554 let after = crate::decode::reelc_chroma_counters();
18555 let (skip_cfl, dir_pairs) = (after.0 - before.0, after.1 - before.1);
18556 let ffmpeg_frames = if depth == 10 {
18557 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
18558 } else {
18559 ffmpeg_decode_sequence(&stream, width, height, frames.len())
18560 };
18561 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
18562 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18563 assert_eq!(got.y, want.y, "{NAME} frame {i} luma (depth={depth})");
18564 assert_eq!(
18565 got.u, want.u,
18566 "{NAME} frame {i} U (depth={depth}, {skip_cfl} skipped-CfL blocks, \
18567 {dir_pairs} directional 1:4 chroma pairs)"
18568 );
18569 assert_eq!(
18570 got.v, want.v,
18571 "{NAME} frame {i} V (depth={depth}, {skip_cfl} skipped-CfL blocks, \
18572 {dir_pairs} directional 1:4 chroma pairs)"
18573 );
18574 }
18575 // Defect 1 (skipped `UV_CFL_PRED`) is NOT asserted here: 20 aomenc
18576 // recipes (cq 40..63, 9 lavfi sources, min/max-partition 4..64,
18577 // both `--sb-size=128` and 64) never made the encoder pick a
18578 // skipped 1:4 / sub-8x8 CfL block, so an assert would only ever
18579 // fire on his real film. Its evidence is ReelC's own key frames
18580 // (lanes/reelckf-r1.report.md): ss=2700 went 499 wrong chroma
18581 // samples -> 0 on this fix alone. The count is printed so a future
18582 // recipe that does reach it is visible immediately. r2 pinned that
18583 // film frame as a fixture instead:
18584 // `a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact`
18585 // hard-asserts the counter.
18586 assert!(
18587 dir_pairs > 0,
18588 "{NAME}: no directional 1:4 chroma pair decoded (depth={depth}) -- defect 2 \
18589 is not exercised"
18590 );
18591 eprintln!(
18592 "{NAME}: pixel-exact at {depth}-bit over {} frames, skipped_cfl={skip_cfl} \
18593 directional_1to4_chroma_pairs={dir_pairs}",
18594 frames.len()
18595 );
18596 }
18597 assert!(
18598 compared > 0,
18599 "{NAME}: every arm refused -- the gate compared no pixels at all"
18600 );
18601 }
18602
18603 /// lane-ab16 r1: real `aomenc --enable-ab-partitions=1` streams whose
18604 /// 16x16 blocks are split T-shaped (`PARTITION_HORZ_A`/`_HORZ_B`/
18605 /// `_VERT_A`/`_VERT_B`: two 8x8 squares plus one 16x8/8x16 strip), the
18606 /// refusals "a HORZ_A/HORZ_B/VERT_A partition below 16x16" and "a coded
18607 /// (non-skip) HORZ_B/VERT_B rect strip below 16x16" this round lifts.
18608 /// `--min-partition-size=8 --max-partition-size=16` pins the level so
18609 /// every AB symbol in the stream is a 16x16 one; the squares go through
18610 /// `decode_leaf8`, the strips through `decode_leaf_rect`'s non-skip
18611 /// coefficient path (lane-rectx). The per-arm counter is sampled per
18612 /// attempt and summed only over attempts that actually decoded AND were
18613 /// compared, and EACH of the four arms must have fired -- a run where
18614 /// aomenc's RD only ever picked HORZ_A cannot pass as proof of four
18615 /// ([[gate-blind-to-feature]]). 8-bit and 10-bit; `--tile-columns=1` is
18616 /// NOT among the attempts (base tile defect, reproducer in the r1
18617 /// report), and `--enable-tx-size-search` is left at aomenc's default
18618 /// (ON) -- pinning it off hid a panic in the TX4 sub-grid of an 8x8
18619 /// square inside a `PARTITION_VERT_A`/`_B` (r2).
18620 #[test]
18621 fn a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact() {
18622 const NAME: &str =
18623 "a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact";
18624 let _gate_lock = lock_gate_counters();
18625 if !have_ffmpeg() {
18626 eprintln!("SKIP {NAME}: no ffmpeg");
18627 return;
18628 }
18629 if !have_aomenc() {
18630 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18631 return;
18632 }
18633 struct Attempt {
18634 src: &'static str,
18635 w: usize,
18636 h: usize,
18637 cq: u32,
18638 ten_bit: bool,
18639 tile_cols: u32,
18640 /// Left at aomenc's default (ON) instead of pinned off: reaches
18641 /// the TX4 sub-grid of an 8x8 square inside a
18642 /// `PARTITION_VERT_A`/`_B` (r2's panic), at the cost of the
18643 /// strip-level split transform lane-rectx still refuses.
18644 tx_size_search: bool,
18645 }
18646 // Recipes chosen by a ~200-cell sweep of {source, size, cq} at this
18647 // level (r1 report): one cell per arm that is pixel-exact end to end,
18648 // plus two 10-bit cells. `--tile-columns=1` is deliberately absent --
18649 // it mismatches on blocks that are plain NONE/VERT with no AB symbol
18650 // in the failing superblock, i.e. a base tile defect this lane
18651 // neither introduced nor owns (reproducer pinned in the r1 report).
18652 let attempts = [
18653 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 22, ten_bit: false, tile_cols: 0, tx_size_search: false },
18654 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 20, ten_bit: false, tile_cols: 0, tx_size_search: false },
18655 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 50, ten_bit: false, tile_cols: 0, tx_size_search: false },
18656 Attempt { src: "mandelbrot=size=64x64:start_x=-1.0", w: 64, h: 64, cq: 14, ten_bit: false, tile_cols: 0, tx_size_search: false },
18657 // 10-bit: the only two cells of the sweep that are exact at this
18658 // depth (HORZ_A and VERT_A); the 10-bit HORZ_B/VERT_B cells all
18659 // trip the base chroma defect the r1 report pins, so those two
18660 // arms are proven 8-bit only.
18661 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 30, ten_bit: true, tile_cols: 0, tx_size_search: false },
18662 Attempt { src: "mandelbrot=size=64x64:start_x=0.4", w: 64, h: 64, cq: 30, ten_bit: true, tile_cols: 0, tx_size_search: false },
18663 // `--enable-tx-size-search` at aomenc's default: an 8x8 square of
18664 // a VERT_A/VERT_B resolves to a 2x2 grid of TX4 units, which is
18665 // the reach lookup that had no table row and panicked (r2). These
18666 // attempts may legitimately stop at lane-rectx's still-standing
18667 // "strip with a split transform" refusal -- an `unsupported`
18668 // message is tolerated, a panic or a pixel mismatch is not, and
18669 // at least one of them must reach a TX4 unit inside a vertical AB
18670 // partition.
18671 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 55, ten_bit: false, tile_cols: 0, tx_size_search: true },
18672 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 22, ten_bit: false, tile_cols: 0, tx_size_search: true },
18673 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 20, ten_bit: false, tile_cols: 0, tx_size_search: true },
18674 Attempt { src: "mandelbrot=size=64x64:start_x=-1.0", w: 64, h: 64, cq: 14, ten_bit: false, tile_cols: 0, tx_size_search: true },
18675 ];
18676 let mut arms = [0usize; 4];
18677 let mut compared = 0usize;
18678 let mut tx4_reached = 0usize;
18679 let mut tx4_compared = 0usize;
18680 for a in &attempts {
18681 let desc =
18682 format!("{} cq={} {}bit tiles={}", a.src, a.cq, if a.ten_bit { 10 } else { 8 }, a.tile_cols);
18683 let mut ff: Vec<String> = vec![
18684 "-v".into(), "error".into(), "-f".into(), "lavfi".into(), "-i".into(), a.src.into(),
18685 "-pix_fmt".into(),
18686 if a.ten_bit { "yuv420p10le".into() } else { "yuv420p".into() },
18687 ];
18688 if a.ten_bit {
18689 ff.push("-strict".into());
18690 ff.push("-1".into());
18691 }
18692 ff.extend(["-t".into(), "1".into(), "-vframes".into(), "1".into(),
18693 "-f".into(), "yuv4mpegpipe".into(), "-".into()]);
18694 let y4m = Command::new("ffmpeg")
18695 .args(&ff)
18696 .stdin(Stdio::null())
18697 .stdout(Stdio::piped())
18698 .stderr(Stdio::piped())
18699 .output()
18700 .expect("ffmpeg failed to run");
18701 assert!(y4m.status.success(), "ffmpeg fixture {desc}: {}", String::from_utf8_lossy(&y4m.stderr));
18702 let encode = || {
18703 let mut args: Vec<String> = vec![
18704 "--codec=av1".into(), "--passes=1".into(), "--end-usage=q".into(),
18705 format!("--cq-level={}", a.cq), "--cpu-used=4".into(), "--threads=1".into(),
18706 "--row-mt=0".into(), "--sb-size=64".into(), "--kf-max-dist=0".into(),
18707 "--limit=1".into(),
18708 "--enable-rect-partitions=1".into(), "--enable-ab-partitions=1".into(),
18709 "--enable-1to4-partitions=0".into(),
18710 format!("--enable-tx-size-search={}", u8::from(a.tx_size_search)),
18711 // Filter intra ON a rect strip is a separate, still-refused
18712 // predictor; this gate is about the AB partition wiring.
18713 "--enable-filter-intra=0".into(),
18714 "--reduced-tx-type-set=1".into(),
18715 "--min-partition-size=8".into(), "--max-partition-size=16".into(),
18716 format!("--tile-columns={}", a.tile_cols),
18717 ];
18718 if a.ten_bit {
18719 args.push("--input-bit-depth=10".into());
18720 args.push("--bit-depth=10".into());
18721 }
18722 args.extend(["--obu".into(), "-o".into(), "-".into(), "-".into()]);
18723 let mut child = Command::new(aomenc_path())
18724 .args(&args)
18725 .stdin(Stdio::piped())
18726 .stdout(Stdio::piped())
18727 .stderr(Stdio::piped())
18728 .spawn()
18729 .expect("aomenc failed to start");
18730 child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("y4m to aomenc");
18731 let out = child.wait_with_output().expect("aomenc failed to run");
18732 assert!(out.status.success(), "aomenc refused {desc}: {}", String::from_utf8_lossy(&out.stderr));
18733 out.stdout
18734 };
18735 let stream = encode();
18736 assert!(!stream.is_empty(), "{NAME}: {desc}: aomenc wrote an empty stream");
18737 assert_eq!(stream, encode(), "{NAME}: {desc}: aomenc output is not reproducible");
18738 let before = crate::decode::ab16_hits_by_arm();
18739 let tx4_before = crate::decode::vert_ab_tx4_hits();
18740 let decoded = decode_stream(&stream);
18741 let tx4_this = crate::decode::vert_ab_tx4_hits() - tx4_before;
18742 // Counted even when the attempt later stops at another lane's
18743 // refusal: reaching this lookup at all is what r2 fixed.
18744 tx4_reached += tx4_this;
18745 let frames = match decoded {
18746 Ok(frames) => frames,
18747 // Only lane-rectx's split-transform strip refusal may stop a
18748 // tx-size-search attempt; a panic never reaches here at all.
18749 Err(e) if a.tx_size_search => {
18750 let msg = e.to_string();
18751 assert!(
18752 msg.contains("unsupported"),
18753 "{NAME}: {desc}: decode failed with a non-refusal error: {msg}"
18754 );
18755 eprintln!("{NAME}: {desc} refused after {tx4_this} vert-AB TX4 units: {msg}");
18756 continue;
18757 }
18758 Err(e) => panic!("{NAME}: {desc}: decode failed, not a pixel mismatch: {e}"),
18759 };
18760 let after = crate::decode::ab16_hits_by_arm();
18761 let this: Vec<usize> = (0..4).map(|i| after[i] - before[i]).collect();
18762 eprintln!("{NAME}: {desc} decoded, arms this attempt={this:?}");
18763 let want = if a.ten_bit {
18764 ffmpeg_decode_sequence_10bit(&stream, a.w, a.h, frames.len())
18765 } else {
18766 ffmpeg_decode_sequence(&stream, a.w, a.h, frames.len())
18767 };
18768 assert_eq!(want.len(), frames.len(), "{NAME}: {desc}: ffmpeg frame count");
18769 for (i, (got, w)) in frames.iter().zip(&want).enumerate() {
18770 assert_eq!(got.y, w.y, "{NAME}: {desc} frame {i} luma vs ffmpeg");
18771 assert_eq!(got.u, w.u, "{NAME}: {desc} frame {i} U vs ffmpeg");
18772 assert_eq!(got.v, w.v, "{NAME}: {desc} frame {i} V vs ffmpeg");
18773 }
18774 // Counted only now: the attempt decoded AND compared exact.
18775 if a.tx_size_search {
18776 tx4_compared += 1;
18777 eprintln!("{NAME}: {desc} pixel-exact, vert-AB TX4 units={tx4_this}");
18778 continue;
18779 }
18780 for i in 0..4 {
18781 arms[i] += after[i] - before[i];
18782 }
18783 compared += 1;
18784 eprintln!("{NAME}: {desc} pixel-exact");
18785 }
18786 assert_eq!(
18787 compared,
18788 attempts.iter().filter(|a| !a.tx_size_search).count(),
18789 "{NAME}: every fixed-transform attempt must decode and compare"
18790 );
18791 // Until the lane-rectsplitx merge every tx-size-search attempt stopped
18792 // at "a HORZ/VERT intra strip below 16x16 with a split transform", so
18793 // this gate could only claim that the TX4 sub-grid of an 8x8 square
18794 // inside a VERT_A/VERT_B was REACHED (`tx4_reached`, counted even on a
18795 // refused attempt). With per-TU rect prediction those same attempts now
18796 // decode to the end and compare pixel-exact, and they carry no vert-AB
18797 // TX4 unit at all -- the pre-merge nonzero count came from decodes that
18798 // were still desynced when they hit the refusal (class
18799 // counter-from-refused-stream). The full pixel compare is the stronger
18800 // claim and replaces it; the lookup's VALUES stay pinned against libaom
18801 // in `of_tu_keeps_the_ordinary_answer_and_uses_the_block_row_under_vert_ab`.
18802 eprintln!("{NAME}: vert-AB TX4 units reached across tx-size-search attempts: {tx4_reached}");
18803 let _ = tx4_reached;
18804 assert_eq!(
18805 tx4_compared,
18806 attempts.iter().filter(|a| a.tx_size_search).count(),
18807 "{NAME}: every --enable-tx-size-search=1 attempt must now decode to the end and \
18808 compare pixel-exact (the split-transform strip refusal these used to stop at is \
18809 lifted); the vert-AB TX4 lookup values stay pinned by \
18810 `of_tu_keeps_the_ordinary_answer_and_uses_the_block_row_under_vert_ab`"
18811 );
18812 for (i, arm) in ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"].iter().enumerate() {
18813 assert!(arms[i] > 0, "{NAME}: PARTITION_{arm} at 16x16 never fired across {compared} \
18814 compared streams -- the gate proves nothing about that arm (arms={arms:?})");
18815 }
18816 eprintln!("{NAME}: pixel-exact on {compared} streams, ab16 arms(HORZ_A,HORZ_B,VERT_A,VERT_B)={arms:?}");
18817 }
18818
18819 #[test]
18820 #[ignore = "lane-rectx r3 scratch sweep"]
18821 fn sweep_rectx_recipes() {
18822 let _gate_lock = lock_gate_counters();
18823 let srcs: Vec<String> = vec![
18824 "mandelbrot=size=64x64:start_x=0.4".into(),
18825 "mandelbrot=size=64x64:start_x=-0.6".into(),
18826 "mandelbrot=size=64x64:start_x=0.1".into(),
18827 "mandelbrot=size=128x128:start_x=0.4".into(),
18828 "mandelbrot=size=128x128:start_x=-0.6".into(),
18829 "testsrc2=size=64x64".into(),
18830 "testsrc2=size=128x128".into(),
18831 "rgbtestsrc=size=64x64".into(),
18832 "smptebars=size=128x128".into(),
18833 ];
18834 for start_x in srcs {
18835 let y4m = Command::new("ffmpeg")
18836 .args([
18837 "-v", "error", "-f", "lavfi", "-i",
18838 &start_x,
18839 "-pix_fmt", "yuv420p", "-t", "1", "-vframes", "1", "-f", "yuv4mpegpipe", "-",
18840 ])
18841 .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped())
18842 .output().expect("ffmpeg");
18843 assert!(y4m.status.success());
18844 let (width, height) = if start_x.contains("128x128") { (128usize, 128usize) } else { (64usize, 64usize) };
18845 for cq in [16u32, 20, 24, 28, 32, 40, 50] {
18846 for rtx in ["0", "1"] {
18847 let mut child = Command::new(aomenc_path())
18848 .args([
18849 "--codec=av1", "--passes=1", "--end-usage=q",
18850 &format!("--cq-level={cq}"), "--cpu-used=4", "--threads=1",
18851 "--row-mt=0", "--sb-size=64", "--kf-max-dist=0",
18852 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
18853 "--enable-1to4-partitions=0", "--enable-tx-size-search=0",
18854 "--enable-cdef=0", "--enable-restoration=0",
18855 &format!("--reduced-tx-type-set={rtx}"),
18856 "--min-partition-size=8", "--max-partition-size=32",
18857 "--obu", "-o", "-", "-",
18858 ])
18859 .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
18860 .spawn().expect("aomenc");
18861 child.stdin.take().unwrap().write_all(&y4m.stdout).unwrap();
18862 let out = child.wait_with_output().unwrap();
18863 assert!(out.status.success());
18864 let stream = out.stdout;
18865 let before = crate::decode::rect_leaf_coeff_hits();
18866 let res = decode_stream(&stream);
18867 let fired = crate::decode::rect_leaf_coeff_hits() - before;
18868 match res {
18869 Err(e) => eprintln!("x={start_x} cq={cq} rtx={rtx} fired={fired} REFUSED {e}"),
18870 Ok(frames) => {
18871 let want = ffmpeg_decode_sequence(&stream, width, height, frames.len());
18872 let bad = frames.iter().zip(&want)
18873 .filter(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v).count();
18874 eprintln!("x={start_x} cq={cq} rtx={rtx} fired={fired} frames={} mismatched={bad}", frames.len());
18875 if bad == 0 { continue; }
18876 let (g, w) = (&frames[0], &want[0]);
18877 for br in 0..height / 8 {
18878 let mut line = String::new();
18879 for bc in 0..width / 8 {
18880 let mut n = 0;
18881 for row in br * 8..br * 8 + 8 {
18882 for col in bc * 8..bc * 8 + 8 {
18883 if g.y[row * width + col] != w.y[row * width + col] {
18884 n += 1;
18885 }
18886 }
18887 }
18888 line.push_str(&format!("{n:4}"));
18889 }
18890 eprintln!(" blk8 row{br}: {line}");
18891 }
18892 }
18893 }
18894 }
18895 }
18896 }
18897 }
18898
18899 /// lane-rectgate r1: every prior gate pins `--enable-rect-partitions=0
18900 /// --enable-ab-partitions=0 --min/max-partition-size=32` so aomenc never
18901 /// gets to choose a real rect/ab split. This charter's premise ("rect
18902 /// HORZ/VERT + HORZ_A/HORZ_B/VERT_A/VERT_B landed during the warp lane")
18903 /// does NOT hold: `decode_frame`'s inter-tile `match part32` only has
18904 /// arms for `PARTITION_NONE`/`SPLIT`/`HORZ_B` -- `HORZ`, `VERT`,
18905 /// `HORZ_A`, `VERT_A`, `VERT_B`, `HORZ_4`, `VERT_4` all fall into the
18906 /// generic "a partition type this encoder never writes" `_` arm. Two
18907 /// recipes were swept empirically (40 attempts each) to characterize the
18908 /// gap:
18909 /// - `--enable-rect-partitions=1 --enable-ab-partitions=1`, no
18910 /// min/max clamp: 0/40 matched -- every attempt hit either the
18911 /// screen-content refusal or a genuinely-unimplemented partition value
18912 /// (1/2/6/7/9 all observed), always somewhere in the 24-frame stream.
18913 /// - Same, but `--enable-1to4-partitions=0` explicit and
18914 /// `--min-partition-size=16`: still 0/40, `value=9` (`VERT_4`)
18915 /// dominates -- this build's `--enable-1to4-partitions=0` does NOT
18916 /// suppress `VERT_4` selection (aomenc-side, confirmed by direct flag
18917 /// toggle; outside this decoder). This recipe (below) restores the
18918 /// `--enable-rect-partitions=0 --min/max-partition-size=32` pin every
18919 /// other gate uses, flipping only `--enable-ab-partitions=1`: matches
18920 /// cleanly (33/40, rest screen-content refusals) but
18921 /// `extended_partition_hits` stayed 0 -- confirmed with the same probe
18922 /// wired into the already-green warp gate too (144 `warp_selected_hits`,
18923 /// 0 `extended_partition_hits`), so `PARTITION_HORZ_B` itself is
18924 /// apparently never chosen by aomenc for this small gradient fixture at
18925 /// `cq-level=45` regardless of clamp. No decode defect (crash or pixel
18926 /// mismatch) was found in any sweep -- every refusal is a correctly
18927 /// named, non-silent "unsupported" error. A refusal or mismatch naming
18928 /// any OTHER already-ported capability (warp, obmc, interintra) still
18929 /// fails the gate outright.
18930 #[test]
18931 fn a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact() {
18932 const NAME: &str = "a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact";
18933 let _gate_lock = lock_gate_counters();
18934 if !have_ffmpeg() {
18935 eprintln!("SKIP {NAME}: no ffmpeg");
18936 return;
18937 }
18938 if !have_aomenc() {
18939 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18940 return;
18941 }
18942 let (width, height, frame_count) = (64usize, 64usize, 24usize);
18943 let mut named_refusals = 0u32;
18944 let mut matched = 0u32;
18945 let n_attempts: u32 = std::env::var("EC_RECTGATE_ATTEMPTS")
18946 .ok()
18947 .and_then(|s| s.parse().ok())
18948 .unwrap_or(40);
18949 for attempt in 0..n_attempts {
18950 let seed = 42 + attempt;
18951 let duration = frame_count as f64 / 25.0;
18952 let source =
18953 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
18954 let y4m = Command::new("ffmpeg")
18955 .args([
18956 "-v",
18957 "error",
18958 "-f",
18959 "lavfi",
18960 "-i",
18961 &source,
18962 "-pix_fmt",
18963 "yuv420p",
18964 "-f",
18965 "yuv4mpegpipe",
18966 "-",
18967 ])
18968 .stdin(Stdio::null())
18969 .stdout(Stdio::piped())
18970 .stderr(Stdio::piped())
18971 .output()
18972 .expect("ffmpeg failed to run");
18973 assert!(
18974 y4m.status.success(),
18975 "ffmpeg fixture: {}",
18976 String::from_utf8_lossy(&y4m.stderr)
18977 );
18978 let args: Vec<&str> = vec![
18979 "--codec=av1",
18980 "--passes=1",
18981 "--end-usage=q",
18982 "--cq-level=45",
18983 "--cpu-used=0",
18984 "--kf-max-dist=1000",
18985 "--threads=1",
18986 "--row-mt=0",
18987 "--auto-alt-ref=1",
18988 "--lag-in-frames=16",
18989 "--enable-fwd-kf=0",
18990 "--enable-order-hint=1",
18991 "--enable-warped-motion=1",
18992 "--enable-obmc=1",
18993 "--tune-content=default",
18994 "--enable-masked-comp=0",
18995 "--enable-interintra-comp=0",
18996 "--enable-onesided-comp=0",
18997 "--enable-interintra-wedge=0",
18998 "--enable-smooth-interintra=0",
18999 // lane-rect r2: HORZ/VERT decode for real (rect-flake-1
19000 // byte-exact: size_h + warp dims + OBMC overlap + tx height)
19001 // -- free recipe restored; remaining partition kinds refuse
19002 // by name and skip their seeds.
19003 "--enable-rect-partitions=1",
19004 "--enable-ab-partitions=1",
19005 "--enable-1to4-partitions=0",
19006 "--enable-filter-intra=0",
19007 "--enable-smooth-intra=0",
19008 "--enable-paeth-intra=0",
19009 "--enable-directional-intra=0",
19010 "--enable-angle-delta=0",
19011 "--enable-tx-size-search=0",
19012 "--enable-cdef=0",
19013 "--enable-restoration=0",
19014 "--max-partition-size=32",
19015 "--min-partition-size=16",
19016 "--enable-palette=0",
19017 "--enable-intrabc=0",
19018 "--enable-cfl-intra=0",
19019 "--enable-ref-frame-mvs=0",
19020 "--obu",
19021 "-o",
19022 "-",
19023 "-",
19024 ];
19025 let mut child = Command::new(aomenc_path())
19026 .args(&args)
19027 .stdin(Stdio::piped())
19028 .stdout(Stdio::piped())
19029 .stderr(Stdio::piped())
19030 .spawn()
19031 .expect("aomenc failed to start");
19032 child
19033 .stdin
19034 .take()
19035 .expect("aomenc stdin")
19036 .write_all(&y4m.stdout)
19037 .expect("writing y4m to aomenc");
19038 let out = child.wait_with_output().expect("aomenc failed to run");
19039 assert!(
19040 out.status.success(),
19041 "aomenc refused the fixture: {}",
19042 String::from_utf8_lossy(&out.stderr)
19043 );
19044 let stream = out.stdout;
19045 let frames = match decode_stream(&stream) {
19046 Err(e) => {
19047 let msg = e.to_string();
19048 assert!(
19049 msg.contains("unsupported"),
19050 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
19051 );
19052 for banned in ["warp", "obmc", "interintra"] {
19053 assert!(
19054 !msg.contains(banned),
19055 "{NAME} refused on {banned} (seed {seed}) -- that capability is \
19056 ported and this recipe does not need it: {msg}"
19057 );
19058 }
19059 named_refusals += 1;
19060 eprintln!("seed {seed} refusal: {msg}");
19061 continue;
19062 }
19063 Ok(frames) => frames,
19064 };
19065 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
19066 assert_eq!(frames.len(), frame_count);
19067 let mismatched = frames
19068 .iter()
19069 .zip(&ffmpeg_frames)
19070 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
19071 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
19072 std::fs::write(&path, &stream).expect("writing pinned stream");
19073 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
19074 }
19075 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19076 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
19077 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
19078 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
19079 }
19080 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
19081 // stream again, comparing EVERY decode-order frame -- the hidden
19082 // (show_frame == 0) alt-ref frames the ffmpeg compare above
19083 // cannot see, because both sides of it emit shown frames only.
19084 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
19085 eprintln!(
19086 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
19087 {hidden_n} hidden, all pixel-exact vs the oracle"
19088 );
19089 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
19090 // libaom's temporal alt-ref filter absorbs this recipe's hidden
19091 // frames, so the compare above is vacuous -- re-encode the same
19092 // fixture with --arnr-maxframes=0 and compare THOSE.
19093 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
19094 eprintln!(
19095 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
19096 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
19097 );
19098 }
19099 matched += 1;
19100 }
19101 assert!(
19102 matched > 0,
19103 "{NAME}: every attempt refused; the gate never decoded a free-partition stream"
19104 );
19105 // lane-partitions r1: HORZ/VERT arms landed, so the diversity probe
19106 // graduates from rectgate r1's eprintln to a report line on
19107 // `rect_partition_hits`; a zero-hit run SOFT-reports (aomenc RD may
19108 // legitimately never pick a rect split in a small window -- same
19109 // sampling caveat as the masked-compound gate's zero-hit runs).
19110 // `extended_partition_hits` (HORZ_B) stays unasserted per rectgate r1.
19111 if crate::decode::rect_partition_hits() == 0 {
19112 eprintln!(
19113 "{NAME}: SOFT-NOTE -- zero HORZ/VERT strips fired this run \
19114 ({matched} matches, {named_refusals} refusals); sampling, not a regression"
19115 );
19116 } else {
19117 // r5: the desync was the tx-depth symbol being read
19118 // unconditionally where both square paths gate it on `tx_select`
19119 // -- with --enable-tx-size-search=0 the encoder writes no such
19120 // symbol and the decoder consumed one that was never there. With
19121 // that fixed the real coefficient decode is pixel-exact, so this
19122 // is a HARD assert again: strips fired but no coefficients read
19123 // would mean the coded path silently stopped being exercised.
19124 assert!(
19125 crate::decode::rect_coeff_hits() > 0,
19126 "{NAME}: {} HORZ/VERT strips fired but rect_coeff_hits==0 -- the \
19127 coded rect path is no longer exercised",
19128 crate::decode::rect_partition_hits()
19129 );
19130 }
19131 eprintln!(
19132 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of {n_attempts}, rect_partition_hits={} rect_coeff_hits={} extended_partition_hits={} partab_hits={}",
19133 crate::decode::rect_partition_hits(),
19134 crate::decode::rect_coeff_hits(),
19135 crate::decode::extended_partition_hits(),
19136 crate::decode::partab_hits()
19137 );
19138 }
19139
19140 /// lane-partab r1: `--enable-ab-partitions=1` (aomenc default-on) INTER
19141 /// streams must consume PARTITION_HORZ_A/VERT_A/VERT_B entropy-exact AND
19142 /// decode pixel-exact -- `partab_hits() > 0` is soft-skipped on a
19143 /// zero-hit run (aomenc RD may legitimately never pick an AB split in a
19144 /// small window, same sampling caveat as wedge/rect). The INTER AB
19145 /// refusal is FORBIDDEN (decode.rs names it "an INTER 32x32 partition
19146 /// ..."); intra-frame AB refusals stay accepted named refusals -- the
19147 /// intra dispatch is a later lane. Recipe = the free-partition gate's,
19148 /// which fires AB live (r1: partab_hits 6/2/4/3/1/5 over six
19149 /// 40-attempt runs).
19150 #[test]
19151 fn a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact() {
19152 const NAME: &str = "a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact";
19153 let _gate_lock = lock_gate_counters();
19154 if !have_ffmpeg() {
19155 eprintln!("SKIP {NAME}: no ffmpeg");
19156 return;
19157 }
19158 if !have_aomenc() {
19159 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19160 return;
19161 }
19162 let (width, height, frame_count) = (64usize, 64usize, 24usize);
19163 let mut named_refusals = 0u32;
19164 let mut matched = 0u32;
19165 let n_attempts: u32 = std::env::var("EC_RECTGATE_ATTEMPTS")
19166 .ok()
19167 .and_then(|s| s.parse().ok())
19168 .unwrap_or(40);
19169 for attempt in 0..n_attempts {
19170 let seed = 42 + attempt;
19171 let duration = frame_count as f64 / 25.0;
19172 let source =
19173 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
19174 let y4m = Command::new("ffmpeg")
19175 .args([
19176 "-v",
19177 "error",
19178 "-f",
19179 "lavfi",
19180 "-i",
19181 &source,
19182 "-pix_fmt",
19183 "yuv420p",
19184 "-f",
19185 "yuv4mpegpipe",
19186 "-",
19187 ])
19188 .stdin(Stdio::null())
19189 .stdout(Stdio::piped())
19190 .stderr(Stdio::piped())
19191 .output()
19192 .expect("ffmpeg failed to run");
19193 assert!(
19194 y4m.status.success(),
19195 "ffmpeg fixture: {}",
19196 String::from_utf8_lossy(&y4m.stderr)
19197 );
19198 let args: Vec<&str> = vec![
19199 "--codec=av1",
19200 "--passes=1",
19201 "--end-usage=q",
19202 "--cq-level=45",
19203 "--cpu-used=0",
19204 "--kf-max-dist=1000",
19205 "--threads=1",
19206 "--row-mt=0",
19207 "--auto-alt-ref=1",
19208 "--lag-in-frames=16",
19209 "--enable-fwd-kf=0",
19210 "--enable-order-hint=1",
19211 "--enable-warped-motion=1",
19212 "--enable-obmc=1",
19213 "--tune-content=default",
19214 "--enable-masked-comp=0",
19215 "--enable-interintra-comp=0",
19216 "--enable-onesided-comp=0",
19217 "--enable-interintra-wedge=0",
19218 "--enable-smooth-interintra=0",
19219 // lane-rect r2 recipe, kept byte-identical by lane-partab
19220 // r1: free partition search, 1to4 off, intra tools off.
19221 "--enable-rect-partitions=1",
19222 "--enable-ab-partitions=1",
19223 "--enable-1to4-partitions=0",
19224 "--enable-filter-intra=0",
19225 "--enable-smooth-intra=0",
19226 "--enable-paeth-intra=0",
19227 "--enable-directional-intra=0",
19228 "--enable-angle-delta=0",
19229 "--enable-tx-size-search=0",
19230 "--enable-cdef=0",
19231 "--enable-restoration=0",
19232 "--max-partition-size=32",
19233 "--min-partition-size=16",
19234 "--enable-palette=0",
19235 "--enable-intrabc=0",
19236 "--enable-cfl-intra=0",
19237 "--enable-ref-frame-mvs=0",
19238 "--obu",
19239 "-o",
19240 "-",
19241 "-",
19242 ];
19243 let mut child = Command::new(aomenc_path())
19244 .args(&args)
19245 .stdin(Stdio::piped())
19246 .stdout(Stdio::piped())
19247 .stderr(Stdio::piped())
19248 .spawn()
19249 .expect("aomenc failed to start");
19250 child
19251 .stdin
19252 .take()
19253 .expect("aomenc stdin")
19254 .write_all(&y4m.stdout)
19255 .expect("writing y4m to aomenc");
19256 let out = child.wait_with_output().expect("aomenc failed to run");
19257 assert!(
19258 out.status.success(),
19259 "aomenc refused the fixture: {}",
19260 String::from_utf8_lossy(&out.stderr)
19261 );
19262 let stream = out.stdout;
19263 let frames = match decode_stream(&stream) {
19264 Err(e) => {
19265 let msg = e.to_string();
19266 assert!(
19267 msg.contains("unsupported"),
19268 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
19269 );
19270 for banned in ["warp", "obmc", "interintra"] {
19271 assert!(
19272 !msg.contains(banned),
19273 "{NAME} refused on {banned} (seed {seed}) -- that capability is \
19274 ported and this recipe does not need it: {msg}"
19275 );
19276 }
19277 for v in [4, 6, 7] {
19278 assert!(
19279 !msg.contains(&format!(
19280 "an INTER 32x32 partition type this encoder never writes \
19281 (value={v})"
19282 )),
19283 "{NAME} refused an INTER AB partition (value={v}, seed {seed}) -- \
19284 all three AB arms are ported, this refusal is forbidden: {msg}"
19285 );
19286 }
19287 named_refusals += 1;
19288 eprintln!("seed {seed} refusal: {msg}");
19289 continue;
19290 }
19291 Ok(frames) => frames,
19292 };
19293 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
19294 assert_eq!(frames.len(), frame_count);
19295 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19296 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
19297 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
19298 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
19299 }
19300 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
19301 // stream again, comparing EVERY decode-order frame -- the hidden
19302 // (show_frame == 0) alt-ref frames the ffmpeg compare above
19303 // cannot see, because both sides of it emit shown frames only.
19304 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
19305 eprintln!(
19306 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
19307 {hidden_n} hidden, all pixel-exact vs the oracle"
19308 );
19309 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
19310 // libaom's temporal alt-ref filter absorbs this recipe's hidden
19311 // frames, so the compare above is vacuous -- re-encode the same
19312 // fixture with --arnr-maxframes=0 and compare THOSE.
19313 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
19314 eprintln!(
19315 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
19316 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
19317 );
19318 }
19319 matched += 1;
19320 }
19321 assert!(
19322 matched > 0,
19323 "{NAME}: every attempt refused; the gate never decoded a stream"
19324 );
19325 if crate::decode::partab_hits() == 0 {
19326 eprintln!(
19327 "{NAME}: SOFT-NOTE -- zero AB partitions fired this run \
19328 ({matched} matches, {named_refusals} refusals); sampling, not a regression"
19329 );
19330 }
19331 eprintln!(
19332 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of {n_attempts}, partab_hits={}",
19333 crate::decode::partab_hits()
19334 );
19335 }
19336
19337 /// lane-ab32 r1: the 32x32-level AB arms (`PARTITION_HORZ_A`/`_HORZ_B`/
19338 /// `_VERT_A`/`_VERT_B` -- two 16x16 squares plus one 32x16/16x32 strip)
19339 /// are decoded on the INTRA path (decode.rs `PARTITION_HORZ_A` .. the
19340 /// 32x32 refusal) but nothing asserted they fire: the INTER AB gate above
19341 /// only SOFT-notes `partab_hits`, and the four per-arm counters
19342 /// lane-part32 added had no consumer at all (class
19343 /// `refusal-lifted-without-a-gate`). This drives a real key-frame-only
19344 /// aomenc at `--enable-ab-partitions=1 --enable-rect-partitions=1
19345 /// --sb-size=64 --min-partition-size=16 --max-partition-size=32`, so every
19346 /// AB split aomenc picks is a 32-level one, pixel-compares every
19347 /// successful decode against ffmpeg's decode of the same bytes, and
19348 /// hard-asserts each arm fired at least once over the seed sweep --
19349 /// counting deltas only from attempts that decoded AND compared (class
19350 /// `counter-from-refused-stream`).
19351 #[test]
19352 fn a_real_aomenc_stream_with_a_32_level_ab_partition_decodes_pixel_exact() {
19353 const NAME: &str = "a_real_aomenc_stream_with_a_32_level_ab_partition_decodes_pixel_exact";
19354 let _gate_lock = lock_gate_counters();
19355 if !have_ffmpeg() {
19356 eprintln!("SKIP {NAME}: no ffmpeg");
19357 return;
19358 }
19359 if !have_aomenc() {
19360 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19361 return;
19362 }
19363 let (width, height) = (256usize, 256usize);
19364 let arms: [(&str, fn() -> usize); 4] = [
19365 ("HORZ_A_32", crate::decode::intra_horz_a_hits),
19366 ("HORZ_B_32", crate::decode::intra_horz_b_hits),
19367 ("VERT_A_32", crate::decode::intra_vert_a_hits),
19368 ("VERT_B_32", crate::decode::intra_vert_b_hits),
19369 ];
19370 let mut totals = [0usize; 4];
19371 let mut refusals: Vec<String> = Vec::new();
19372 let mut compared = 0usize;
19373 for &seed in &LR_SEEDS {
19374 // Smooth gradients code as PARTITION_NONE everywhere (r1: 16/16
19375 // attempts decoded pixel-exact with zero AB hits), so the fixture
19376 // carries seeded noise to give the intra RD a reason to split.
19377 let source = format!(
19378 "{},noise=alls=40:all_seed={seed}",
19379 gradients_source(seed, width, height, "duration=0.04:rate=25")
19380 );
19381 let y4m = Command::new("ffmpeg")
19382 .args([
19383 "-v",
19384 "error",
19385 "-f",
19386 "lavfi",
19387 "-i",
19388 &source,
19389 "-frames:v",
19390 "1",
19391 "-pix_fmt",
19392 "yuv420p",
19393 "-f",
19394 "yuv4mpegpipe",
19395 "-",
19396 ])
19397 .stdin(Stdio::null())
19398 .stdout(Stdio::piped())
19399 .stderr(Stdio::piped())
19400 .output()
19401 .expect("ffmpeg failed to run");
19402 assert!(
19403 y4m.status.success(),
19404 "{NAME}: ffmpeg fixture (seed {seed}): {}",
19405 String::from_utf8_lossy(&y4m.stderr)
19406 );
19407 // The flags under test come LAST: aomenc keeps the LAST
19408 // occurrence of a repeated flag (measured 2026-09-02 by md5 of
19409 // four orderings), so an override appended after the base recipe
19410 // is the one that lands. Nothing here is repeated, and each of the
19411 // four arm counters below proves the AB flag actually arrived.
19412 let args: Vec<&str> = vec![
19413 "--codec=av1",
19414 "--passes=1",
19415 "--end-usage=q",
19416 "--cq-level=45",
19417 "--cpu-used=0",
19418 "--limit=1",
19419 "--kf-max-dist=0",
19420 "--lag-in-frames=0",
19421 "--threads=1",
19422 "--row-mt=0",
19423 "--enable-1to4-partitions=0",
19424 "--enable-filter-intra=0",
19425 "--enable-smooth-intra=0",
19426 "--enable-paeth-intra=0",
19427 "--enable-directional-intra=0",
19428 "--enable-angle-delta=0",
19429 "--enable-tx-size-search=0",
19430 "--enable-cdef=0",
19431 "--enable-restoration=0",
19432 "--enable-palette=0",
19433 "--enable-intrabc=0",
19434 "--enable-cfl-intra=0",
19435 "--enable-ref-frame-mvs=0",
19436 "--sb-size=64",
19437 "--enable-rect-partitions=1",
19438 "--enable-ab-partitions=1",
19439 "--min-partition-size=16",
19440 "--max-partition-size=32",
19441 "--obu",
19442 "-o",
19443 "-",
19444 "-",
19445 ];
19446 let mut child = Command::new(aomenc_path())
19447 .args(&args)
19448 .stdin(Stdio::piped())
19449 .stdout(Stdio::piped())
19450 .stderr(Stdio::piped())
19451 .spawn()
19452 .expect("aomenc failed to start");
19453 child
19454 .stdin
19455 .take()
19456 .expect("aomenc stdin")
19457 .write_all(&y4m.stdout)
19458 .expect("writing y4m to aomenc");
19459 let out = child.wait_with_output().expect("aomenc failed to run");
19460 assert!(
19461 out.status.success(),
19462 "aomenc refused the fixture (seed {seed}): {}",
19463 String::from_utf8_lossy(&out.stderr)
19464 );
19465 let stream = out.stdout;
19466 let before: Vec<usize> = arms.iter().map(|(_, f)| f()).collect();
19467 let frames = match decode_stream(&stream) {
19468 Err(e) => {
19469 let msg = e.to_string();
19470 assert!(
19471 msg.contains("unsupported"),
19472 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
19473 );
19474 for v in [4, 5, 6, 7] {
19475 assert!(
19476 !msg.contains(&format!(
19477 "a 32x32 partition type this decoder does not code (value={v})"
19478 )),
19479 "{NAME} refused a 32-level AB partition (value={v}, seed {seed}) -- \
19480 all four arms are ported, this refusal is forbidden: {msg}"
19481 );
19482 }
19483 refusals.push(format!("seed {seed}: {msg}"));
19484 continue;
19485 }
19486 Ok(frames) => frames,
19487 };
19488 let deltas: Vec<usize> = arms
19489 .iter()
19490 .zip(before.iter())
19491 .map(|((_, f), b)| f() - b)
19492 .collect();
19493 let fired: Vec<String> = arms
19494 .iter()
19495 .zip(deltas.iter())
19496 .map(|((label, _), d)| format!("{label}={d}"))
19497 .collect();
19498 let fired = fired.join(" ");
19499 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
19500 assert_eq!(
19501 frames.len(),
19502 ffmpeg_frames.len(),
19503 "{NAME}: seed {seed}: shown-frame count vs ffmpeg"
19504 );
19505 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19506 assert_eq!(
19507 got.y, want.y,
19508 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) [{fired}]"
19509 );
19510 assert_eq!(
19511 got.u, want.u,
19512 "{NAME} frame {i} U vs ffmpeg (seed {seed}) [{fired}]"
19513 );
19514 assert_eq!(
19515 got.v, want.v,
19516 "{NAME} frame {i} V vs ffmpeg (seed {seed}) [{fired}]"
19517 );
19518 }
19519 compared += 1;
19520 for (i, d) in deltas.iter().enumerate() {
19521 totals[i] += d;
19522 }
19523 }
19524 assert!(
19525 compared > 0,
19526 "{NAME}: every attempt hit a named refusal:\n{}",
19527 refusals.join("\n")
19528 );
19529 for (i, (label, _)) in arms.iter().enumerate() {
19530 assert!(
19531 totals[i] > 0,
19532 "{NAME}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
19533 the gate would prove nothing about that arm. refusals:\n{}",
19534 refusals.join("\n")
19535 );
19536 }
19537 eprintln!(
19538 "{NAME}: {compared}/{} attempts pixel-exact, HORZ_A_32={} HORZ_B_32={} \
19539 VERT_A_32={} VERT_B_32={}, {} named refusals",
19540 LR_SEEDS.len(),
19541 totals[0],
19542 totals[1],
19543 totals[2],
19544 totals[3],
19545 refusals.len()
19546 );
19547 }
19548
19549 /// lane-ab32 r1: the 10-bit twin of the gate above -- his two films are
19550 /// yuv420p10le, so an 8-bit-only AB gate proves nothing about the streams
19551 /// that matter. Same recipe through [`ten_bit_tool_gate`], which sums the
19552 /// per-arm counters only over attempts that decoded and pixel-compared.
19553 #[test]
19554 fn a_real_aomenc_10bit_stream_with_a_32_level_ab_partition_decodes_pixel_exact() {
19555 const NAME: &str =
19556 "a_real_aomenc_10bit_stream_with_a_32_level_ab_partition_decodes_pixel_exact";
19557 if !have_ffmpeg() {
19558 eprintln!("SKIP {NAME}: no ffmpeg");
19559 return;
19560 }
19561 if !have_aomenc() {
19562 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19563 return;
19564 }
19565 ten_bit_tool_gate(
19566 NAME,
19567 256,
19568 256,
19569 1,
19570 &[
19571 "--ec-fixture-noise",
19572 "--cq-level=45",
19573 "--limit=1",
19574 "--kf-max-dist=0",
19575 "--enable-1to4-partitions=0",
19576 "--enable-filter-intra=0",
19577 "--enable-smooth-intra=0",
19578 "--enable-paeth-intra=0",
19579 "--enable-directional-intra=0",
19580 "--enable-angle-delta=0",
19581 "--enable-tx-size-search=0",
19582 "--enable-cdef=0",
19583 "--enable-restoration=0",
19584 "--enable-palette=0",
19585 "--enable-intrabc=0",
19586 "--enable-cfl-intra=0",
19587 "--enable-ref-frame-mvs=0",
19588 // last wins: the flags under test go after the base recipe
19589 "--enable-rect-partitions=1",
19590 "--enable-ab-partitions=1",
19591 "--min-partition-size=16",
19592 "--max-partition-size=32",
19593 ],
19594 &LR_SEEDS,
19595 &[
19596 ("HORZ_A_32", crate::decode::intra_horz_a_hits),
19597 ("HORZ_B_32", crate::decode::intra_horz_b_hits),
19598 ("VERT_A_32", crate::decode::intra_vert_a_hits),
19599 ("VERT_B_32", crate::decode::intra_vert_b_hits),
19600 ],
19601 );
19602 }
19603
19604 /// lane-cwarp r1: a real `--enable-global-motion=1 --enable-dist-wtd-comp=1`
19605 /// stream over a rotating/zooming source, so a `GLOBAL_GLOBALMV` compound
19606 /// block lands under a ROTZOOM/AFFINE model and each of its two references
19607 /// is predicted through its OWN global warp
19608 /// (`crate::warp::warp_affine_compound`, libaom `av1_warp_plane` with
19609 /// `conv_params->is_compound`) rather than translationally. Before r1 that
19610 /// path was SILENTLY WRONG -- no refusal named it, both taps went through
19611 /// `mc::predict_compound_intermediate`. `compound_warp_hits() > 0` is a
19612 /// hard assert: a run where the encoder never emitted one proves nothing.
19613 /// A decode error or a pixel mismatch is a FAILURE, never a skip.
19614 fn run_compound_global_warp_gate(name: &str, ten_bit: bool) {
19615 let _gate_lock = lock_gate_counters();
19616 assert!(have_ffmpeg(), "{name}: ffmpeg required");
19617 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
19618 let (width, height, frame_count) = (64usize, 64usize, 24usize);
19619 let before = crate::decode::compound_warp_hits();
19620 let mut matched = 0u32;
19621 let mut named_refusals = 0u32;
19622 let mut attempts = 0u32;
19623 for cq in [32u32, 45, 55] {
19624 for (i, rate) in [0.010f64, 0.022].iter().enumerate() {
19625 attempts += 1;
19626 let duration = frame_count as f64 / 25.0;
19627 // A rotation about the frame centre plus a slow zoom is what
19628 // aomenc's global-motion search fits a ROTZOOM/AFFINE model to;
19629 // mandelbrot gives it real, non-flat texture to track.
19630 let source = format!(
19631 "mandelbrot=size={w}x{h}:rate=25:start_x={sx}:start_y=-0.4,\
19632 rotate=a={rate}*n:ow={w}:oh={h}:c=black,scale={width}:{height}",
19633 w = width * 2,
19634 h = height * 2,
19635 sx = -0.6 + 0.01 * (i as f64),
19636 );
19637 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
19638 let y4m = Command::new("ffmpeg")
19639 .args([
19640 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
19641 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
19642 "-f", "yuv4mpegpipe", "-",
19643 ])
19644 .stdin(Stdio::null())
19645 .stdout(Stdio::piped())
19646 .stderr(Stdio::piped())
19647 .output()
19648 .expect("ffmpeg failed to run");
19649 assert!(
19650 y4m.status.success(),
19651 "ffmpeg fixture: {}",
19652 String::from_utf8_lossy(&y4m.stderr)
19653 );
19654 let cq_arg = format!("--cq-level={cq}");
19655 let mut args: Vec<&str> = vec![
19656 "--codec=av1",
19657 "--passes=1",
19658 "--end-usage=q",
19659 &cq_arg,
19660 "--cpu-used=0",
19661 "--kf-max-dist=1000",
19662 "--threads=1",
19663 "--row-mt=0",
19664 "--auto-alt-ref=1",
19665 "--lag-in-frames=25",
19666 "--enable-fwd-kf=0",
19667 "--enable-order-hint=1",
19668 // the two tools this gate exists for
19669 "--enable-global-motion=1",
19670 "--enable-dist-wtd-comp=1",
19671 "--enable-warped-motion=1",
19672 "--enable-obmc=1",
19673 "--enable-masked-comp=1",
19674 "--enable-onesided-comp=0",
19675 "--enable-interintra-comp=1",
19676 "--enable-interintra-wedge=0",
19677 "--enable-smooth-interintra=1",
19678 "--tune-content=default",
19679 // partition/intra tools this decoder does not code yet --
19680 // same exclusion list every compound gate carries.
19681 "--enable-rect-partitions=0",
19682 "--enable-ab-partitions=0",
19683 "--enable-1to4-partitions=0",
19684 "--enable-filter-intra=0",
19685 "--enable-smooth-intra=0",
19686 "--enable-paeth-intra=0",
19687 "--enable-directional-intra=0",
19688 "--enable-angle-delta=0",
19689 "--enable-tx-size-search=0",
19690 "--enable-cdef=0",
19691 "--enable-restoration=0",
19692 "--max-partition-size=32",
19693 "--min-partition-size=32",
19694 "--enable-palette=0",
19695 "--enable-intrabc=0",
19696 "--enable-cfl-intra=0",
19697 "--enable-ref-frame-mvs=0",
19698 ];
19699 if ten_bit {
19700 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
19701 }
19702 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
19703 let mut child = Command::new(aomenc_path())
19704 .args(&args)
19705 .stdin(Stdio::piped())
19706 .stdout(Stdio::piped())
19707 .stderr(Stdio::piped())
19708 .spawn()
19709 .expect("aomenc failed to start");
19710 child
19711 .stdin
19712 .take()
19713 .expect("aomenc stdin")
19714 .write_all(&y4m.stdout)
19715 .expect("writing y4m to aomenc");
19716 let out = child.wait_with_output().expect("aomenc failed to run");
19717 assert!(
19718 out.status.success(),
19719 "aomenc refused the fixture: {}",
19720 String::from_utf8_lossy(&out.stderr)
19721 );
19722 let stream = out.stdout;
19723 let frames = match decode_stream(&stream) {
19724 Err(e) => {
19725 let msg = e.to_string();
19726 assert!(
19727 msg.contains("unsupported"),
19728 "{name} failed outright, not a named refusal (cq {cq}): {msg}"
19729 );
19730 assert!(
19731 !msg.contains("warp"),
19732 "{name} refused on warp (cq {cq}) -- warp decode is ported: {msg}"
19733 );
19734 named_refusals += 1;
19735 eprintln!("{name} cq {cq} rate {rate} refusal: {msg}");
19736 continue;
19737 }
19738 Ok(frames) => frames,
19739 };
19740 let want = if ten_bit {
19741 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
19742 } else {
19743 ffmpeg_decode_sequence(&stream, width, height, frame_count)
19744 };
19745 assert_eq!(frames.len(), frame_count);
19746 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
19747 && frames
19748 .iter()
19749 .zip(&want)
19750 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
19751 {
19752 std::fs::write(&path, &stream).expect("writing pinned stream");
19753 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
19754 }
19755 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
19756 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq})");
19757 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq})");
19758 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq})");
19759 }
19760 matched += 1;
19761 }
19762 }
19763 let hits = crate::decode::compound_warp_hits() - before;
19764 eprintln!(
19765 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
19766 compound_warp_hits={hits}"
19767 );
19768 assert!(
19769 hits > 0,
19770 "{name}: no compound block was predicted through a per-ref global warp \
19771 ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
19772 );
19773 assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran");
19774 }
19775
19776 /// lane-fimv r1 (class `wrong-alphabet-same-value`): libaom
19777 /// `motion_mode_allowed` (blockd.h ~1484) only returns `WARPED_CAUSAL`
19778 /// when `!xd->cur_frame_force_integer_mv`, so on a frame whose header set
19779 /// `force_integer_mv` an otherwise warp-eligible block reads the 2-symbol
19780 /// `obmc_cdf`, not the 3-symbol `motion_mode_cdf`. This decoder read the
19781 /// 3-symbol alphabet there (silent tile desync, no refusal named it).
19782 ///
19783 /// The fixture is screen content that is mostly static with only
19784 /// whole-pixel motion, which is exactly what aomenc's own
19785 /// `av1_is_integer_mv` (`encoder_utils.c:1357`, >=80% of blocks matching
19786 /// their collocated block) needs to set `cur_frame_force_integer_mv`
19787 /// under `--tune-content=screen` (seq `force_integer_mv == 2`, adaptive:
19788 /// `encoder.c:4171`). Two hard asserts, both class
19789 /// `gate-blind-to-feature`: at least one decoded frame header carried
19790 /// `force_integer_mv = 1`, and at least one block took the 2-symbol
19791 /// alphabet where `allow_warped_motion = 1` and `num_proj_ref >= 1` would
19792 /// have picked the 3-symbol one. A decode error or a pixel mismatch is a
19793 /// FAILURE, never a skip.
19794 #[track_caller]
19795 fn run_fimv_motion_mode_gate(name: &str, ten_bit: bool) {
19796 let _gate_lock = lock_gate_counters();
19797 assert!(have_ffmpeg(), "{name}: ffmpeg required");
19798 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
19799 let (width, height, frame_count) = (64usize, 64usize, 20usize);
19800 let fimv_frames_before = crate::decode::fimv_frame_hits();
19801 let alphabet_before = crate::decode::fimv_alphabet_hits();
19802 let mut matched = 0u32;
19803 let mut named_refusals = 0u32;
19804 let mut attempts = 0u32;
19805 let mut refusals = Vec::new();
19806 for cq in [32u32, 45, 55] {
19807 for step in [4u32, 8] {
19808 attempts += 1;
19809 // lane-fimv r1: per-attempt snapshots. The aggregate
19810 // assertions below are satisfied by a single lucky cq/step
19811 // cell; these prove EVERY attempt that decoded and
19812 // pixel-compared really carried the header state and the
19813 // forced alphabet under test (class gate-blind-to-feature).
19814 let attempt_fimv_before = crate::decode::fimv_frame_hits();
19815 let attempt_alphabet_before = crate::decode::fimv_alphabet_hits();
19816 let duration = frame_count as f64 / 25.0;
19817 // Flat screen-content tiles with hard edges, translating by a
19818 // whole number of pixels per frame: static enough for
19819 // `av1_is_integer_mv`, moving enough for a real inter block
19820 // with overlappable neighbours.
19821 let source = format!(
19822 "color=c=black:s={width}x{height}:r=25,\
19823 drawbox=x='8+{step}*mod(trunc(t*25)\\,3)':y=8:w=20:h=20:color=white:t=fill,\
19824 drawbox=x=36:y='6+{step}*mod(trunc(t*25)+1\\,3)':w=16:h=16:color=0x808080:t=fill,\
19825 drawbox=x=4:y=44:w=56:h=12:color=0xC0C0C0:t=fill"
19826 );
19827 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
19828 let y4m = Command::new("ffmpeg")
19829 .args([
19830 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
19831 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
19832 "-f", "yuv4mpegpipe", "-",
19833 ])
19834 .stdin(Stdio::null())
19835 .stdout(Stdio::piped())
19836 .stderr(Stdio::piped())
19837 .output()
19838 .expect("ffmpeg failed to run");
19839 assert!(
19840 y4m.status.success(),
19841 "ffmpeg fixture: {}",
19842 String::from_utf8_lossy(&y4m.stderr)
19843 );
19844 let cq_arg = format!("--cq-level={cq}");
19845 let mut args: Vec<&str> = vec![
19846 "--codec=av1",
19847 "--passes=1",
19848 "--end-usage=q",
19849 &cq_arg,
19850 "--cpu-used=0",
19851 "--kf-max-dist=1000",
19852 "--threads=1",
19853 "--row-mt=0",
19854 // single reference only: the 10-bit compound MC defect
19855 // (see `a_real_compound_global_warp_10bit_stream_...`)
19856 // is unrelated to this lane and would mask it.
19857 "--auto-alt-ref=0",
19858 "--lag-in-frames=0",
19859 "--enable-fwd-kf=0",
19860 "--enable-order-hint=1",
19861 // the flag combination this gate exists for: warp allowed
19862 // by the header, OBMC available, global motion off (so the
19863 // GLOBALMV suppression is not what picks the alphabet).
19864 "--tune-content=screen",
19865 "--enable-warped-motion=1",
19866 "--enable-obmc=1",
19867 "--enable-global-motion=0",
19868 "--enable-masked-comp=0",
19869 "--enable-onesided-comp=0",
19870 "--enable-interintra-comp=0",
19871 "--enable-interintra-wedge=0",
19872 "--enable-smooth-interintra=0",
19873 "--enable-dist-wtd-comp=0",
19874 // partition/intra tools this decoder does not code yet --
19875 // the same exclusion list every inter gate here carries.
19876 "--enable-rect-partitions=0",
19877 "--enable-ab-partitions=0",
19878 "--enable-1to4-partitions=0",
19879 "--enable-filter-intra=0",
19880 "--enable-smooth-intra=0",
19881 "--enable-paeth-intra=0",
19882 "--enable-directional-intra=0",
19883 "--enable-angle-delta=0",
19884 "--enable-tx-size-search=0",
19885 "--enable-cdef=0",
19886 "--enable-restoration=0",
19887 "--max-partition-size=32",
19888 "--min-partition-size=32",
19889 "--enable-palette=0",
19890 "--enable-intrabc=0",
19891 "--enable-cfl-intra=0",
19892 "--enable-ref-frame-mvs=0",
19893 ];
19894 if ten_bit {
19895 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
19896 }
19897 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
19898 let mut child = Command::new(aomenc_path())
19899 .args(&args)
19900 .stdin(Stdio::piped())
19901 .stdout(Stdio::piped())
19902 .stderr(Stdio::piped())
19903 .spawn()
19904 .expect("aomenc failed to start");
19905 child
19906 .stdin
19907 .take()
19908 .expect("aomenc stdin")
19909 .write_all(&y4m.stdout)
19910 .expect("writing y4m to aomenc");
19911 let out = child.wait_with_output().expect("aomenc failed to run");
19912 assert!(
19913 out.status.success(),
19914 "aomenc refused the fixture: {}",
19915 String::from_utf8_lossy(&out.stderr)
19916 );
19917 let stream = out.stdout;
19918 let frames = match decode_stream(&stream) {
19919 Err(e) => {
19920 let msg = e.to_string();
19921 assert!(
19922 msg.contains("unsupported"),
19923 "{name} failed outright (cq {cq} step {step}): {msg}"
19924 );
19925 named_refusals += 1;
19926 refusals.push(format!("cq {cq} step {step}: {msg}"));
19927 continue;
19928 }
19929 Ok(frames) => frames,
19930 };
19931 let want = if ten_bit {
19932 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
19933 } else {
19934 ffmpeg_decode_sequence(&stream, width, height, frame_count)
19935 };
19936 assert_eq!(frames.len(), frame_count);
19937 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
19938 && frames
19939 .iter()
19940 .zip(&want)
19941 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
19942 {
19943 std::fs::write(&path, &stream).expect("writing pinned stream");
19944 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
19945 }
19946 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
19947 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq} step {step})");
19948 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq} step {step})");
19949 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq} step {step})");
19950 }
19951 assert!(
19952 crate::decode::fimv_frame_hits() > attempt_fimv_before,
19953 "{name} (cq {cq} step {step}): decoded and compared all \
19954 frames but no frame header had force_integer_mv=1 -- \
19955 this attempt is vacuous"
19956 );
19957 assert!(
19958 crate::decode::fimv_alphabet_hits() > attempt_alphabet_before,
19959 "{name} (cq {cq} step {step}): no block was forced onto the \
19960 2-symbol obmc alphabet by force_integer_mv while \
19961 allow_warped_motion=1 and num_proj_ref>=1 -- this attempt \
19962 is vacuous"
19963 );
19964 matched += 1;
19965 }
19966 }
19967 let fimv_frames = crate::decode::fimv_frame_hits() - fimv_frames_before;
19968 let alphabet = crate::decode::fimv_alphabet_hits() - alphabet_before;
19969 eprintln!(
19970 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
19971 force_integer_mv frames={fimv_frames}, forced-2-symbol blocks={alphabet}\n{}",
19972 refusals.join("\n")
19973 );
19974 assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran");
19975 assert!(
19976 fimv_frames > 0,
19977 "{name}: no decoded frame header had force_integer_mv=1 \
19978 ({matched} matches of {attempts}) -- gate vacuous"
19979 );
19980 assert!(
19981 alphabet > 0,
19982 "{name}: no block read the 2-symbol obmc alphabet where \
19983 allow_warped_motion=1 and num_proj_ref>=1 would have picked the \
19984 3-symbol motion_mode alphabet -- gate vacuous"
19985 );
19986 }
19987
19988 /// 8-bit arm of [`run_fimv_motion_mode_gate`].
19989 #[test]
19990 fn a_real_force_integer_mv_warp_stream_decodes_pixel_exact() {
19991 run_fimv_motion_mode_gate("a_real_force_integer_mv_warp_stream_decodes_pixel_exact", false);
19992 }
19993
19994 /// 10-bit arm of [`run_fimv_motion_mode_gate`] -- both of his films are
19995 /// `yuv420p10le`.
19996 #[test]
19997 fn a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact() {
19998 run_fimv_motion_mode_gate(
19999 "a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact",
20000 true,
20001 );
20002 }
20003
20004 /// 8-bit arm of [`run_compound_global_warp_gate`].
20005 #[test]
20006 fn a_real_compound_global_warp_stream_decodes_pixel_exact() {
20007 run_compound_global_warp_gate("a_real_compound_global_warp_stream_decodes_pixel_exact", false);
20008 }
20009
20010 /// 10-bit arm of [`run_compound_global_warp_gate`] -- both of his films are
20011 /// `yuv420p10le`, and `warp_affine`'s `bd` was hardcoded 8 before r1.
20012 ///
20013 /// Un-ignored 2026-09-04: the pre-existing 10-bit compound MC defect that blocked it is gone. Ablation run by lane-cwarp r1 on this
20014 /// very recipe: with `--enable-global-motion=0 --enable-warped-motion=0`
20015 /// (no warp of any kind reachable) the 10-bit stream STILL mismatches at
20016 /// frame 1 luma, cq 32; with `--auto-alt-ref=0 --lag-in-frames=0
20017 /// --enable-dist-wtd-comp=0` (single-reference 10-bit inter only) the same
20018 /// recipe is 6/6 pixel-exact. So: 10-bit single-ref inter is exact, 10-bit
20019 /// compound is not. `mc::diffwtd_mask`'s missing `(bd - 8)` round term was
20020 /// found and fixed while bisecting this, but is NOT the whole defect.
20021 /// The warp wiring under test here is bit-depth generic.
20022 #[test]
20023 fn a_real_compound_global_warp_10bit_stream_decodes_pixel_exact() {
20024 run_compound_global_warp_gate(
20025 "a_real_compound_global_warp_10bit_stream_decodes_pixel_exact",
20026 true,
20027 );
20028 }
20029
20030 /// lane-mcomp64 r1: at 64x64 `av1_is_wedge_used` is false
20031 /// (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`), so libaom's
20032 /// `read_compound_type` codes NO `compound_type` symbol and INFERS
20033 /// `COMPOUND_DIFFWTD`; only the 1-bit `mask_type` literal follows. This
20034 /// decoder used to refuse such a block by name ("a masked compound 64x64
20035 /// inter block..."), because reading the symbol would have desynced.
20036 ///
20037 /// The recipe pins every block to 64x64 (`--sb-size=64
20038 /// --max-partition-size=64 --min-partition-size=64`) with masked compound
20039 /// on and distance-weighted compound off, so the only way a
20040 /// `comp_group_idx == 1` block can be coded is through the inferred arm.
20041 /// `diffwtd_inferred_hits` is snapshotted PER ATTEMPT and only accumulated
20042 /// for attempts that decoded AND pixel-compared (class
20043 /// `counter-from-refused-stream`), and is hard-asserted at the end. A
20044 /// decode error or a pixel mismatch is a FAILURE, never a skip.
20045 #[track_caller]
20046 fn run_diffwtd_inferred_64x64_gate(name: &str, ten_bit: bool) {
20047 let _gate_lock = lock_gate_counters();
20048 assert!(have_ffmpeg(), "{name}: ffmpeg required");
20049 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
20050 let (width, height, frame_count) = (128usize, 128usize, 16usize);
20051 let mut matched = 0u32;
20052 let mut named_refusals = 0u32;
20053 let mut attempts = 0u32;
20054 let mut fired = 0usize;
20055 let mut refusals: Vec<String> = Vec::new();
20056 for cq in [32u32, 45, 55] {
20057 for (i, zoom) in [0.004f64, 0.010].iter().enumerate() {
20058 attempts += 1;
20059 let attempt_before = crate::decode::diffwtd_inferred_hits();
20060 let duration = frame_count as f64 / 25.0;
20061 // Hard-edged, moving content: a difference-weighted mask only
20062 // wins where the two references genuinely disagree over part
20063 // of a 64x64 block (a smooth `gradients` source measured
20064 // diffwtd_hits == 0, memory `gate-blind-to-feature`).
20065 let source = format!(
20066 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y=-0.4:\
20067 end_scale=0.3:maxiter=200,\
20068 noise=alls=6:allf=t+u:all_seed={seed}",
20069 sx = -0.6 + zoom * (i as f64 + 1.0),
20070 seed = 1000 + cq,
20071 );
20072 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
20073 let y4m = Command::new("ffmpeg")
20074 .args([
20075 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
20076 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
20077 "-f", "yuv4mpegpipe", "-",
20078 ])
20079 .stdin(Stdio::null())
20080 .stdout(Stdio::piped())
20081 .stderr(Stdio::piped())
20082 .output()
20083 .expect("ffmpeg failed to run");
20084 assert!(
20085 y4m.status.success(),
20086 "ffmpeg fixture: {}",
20087 String::from_utf8_lossy(&y4m.stderr)
20088 );
20089 let cq_arg = format!("--cq-level={cq}");
20090 let mut args: Vec<&str> = vec![
20091 "--codec=av1",
20092 "--passes=1",
20093 "--end-usage=q",
20094 &cq_arg,
20095 "--cpu-used=0",
20096 "--kf-max-dist=1000",
20097 "--threads=1",
20098 "--row-mt=0",
20099 "--auto-alt-ref=1",
20100 "--lag-in-frames=16",
20101 "--enable-fwd-kf=0",
20102 "--enable-order-hint=1",
20103 // the tools this gate exists for: masked compound on, the
20104 // difference-weighted arm on, the distance-weighted
20105 // competitor off so comp_group_idx==1 is the encoder's
20106 // only masked choice at a size where wedge does not exist.
20107 "--enable-masked-comp=1",
20108 "--enable-diff-wtd-comp=1",
20109 "--enable-dist-wtd-comp=0",
20110 "--enable-onesided-comp=0",
20111 "--enable-interintra-comp=0",
20112 "--enable-global-motion=0",
20113 "--enable-warped-motion=1",
20114 "--enable-obmc=1",
20115 "--tune-content=default",
20116 // partition/intra tools this decoder does not code yet --
20117 // same exclusion list every compound gate carries.
20118 "--enable-rect-partitions=0",
20119 "--enable-ab-partitions=0",
20120 "--enable-1to4-partitions=0",
20121 "--enable-filter-intra=0",
20122 "--enable-smooth-intra=0",
20123 "--enable-paeth-intra=0",
20124 "--enable-directional-intra=0",
20125 "--enable-angle-delta=0",
20126 "--enable-tx-size-search=0",
20127 "--enable-cdef=0",
20128 "--enable-restoration=0",
20129 "--enable-palette=0",
20130 "--enable-intrabc=0",
20131 "--enable-cfl-intra=0",
20132 "--enable-ref-frame-mvs=0",
20133 // every block is a whole 64x64 superblock: the ONLY size
20134 // where compound_type is inferred rather than coded.
20135 "--sb-size=64",
20136 "--max-partition-size=64",
20137 "--min-partition-size=64",
20138 ];
20139 if ten_bit {
20140 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
20141 }
20142 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
20143 let mut child = Command::new(aomenc_path())
20144 .args(&args)
20145 .stdin(Stdio::piped())
20146 .stdout(Stdio::piped())
20147 .stderr(Stdio::piped())
20148 .spawn()
20149 .expect("aomenc failed to start");
20150 child
20151 .stdin
20152 .take()
20153 .expect("aomenc stdin")
20154 .write_all(&y4m.stdout)
20155 .expect("writing y4m to aomenc");
20156 let out = child.wait_with_output().expect("aomenc failed to run");
20157 assert!(
20158 out.status.success(),
20159 "aomenc refused the fixture: {}",
20160 String::from_utf8_lossy(&out.stderr)
20161 );
20162 let stream = out.stdout;
20163 let frames = match decode_stream(&stream) {
20164 Err(e) => {
20165 let msg = e.to_string();
20166 assert!(
20167 msg.contains("unsupported"),
20168 "{name} failed outright, not a named refusal (cq {cq}): {msg}"
20169 );
20170 assert!(
20171 !msg.contains("masked compound 64x64"),
20172 "{name} refused the inferred-DIFFWTD 64x64 block (cq {cq}) -- \
20173 that refusal is lifted, this is forbidden: {msg}"
20174 );
20175 named_refusals += 1;
20176 refusals.push(msg.clone());
20177 eprintln!("{name} cq {cq} variant {i} refusal: {msg}");
20178 continue;
20179 }
20180 Ok(frames) => frames,
20181 };
20182 let want = if ten_bit {
20183 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20184 } else {
20185 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20186 };
20187 assert_eq!(frames.len(), frame_count);
20188 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
20189 && frames
20190 .iter()
20191 .zip(&want)
20192 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
20193 {
20194 std::fs::write(&path, &stream).expect("writing pinned stream");
20195 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
20196 }
20197 for (f, (got, want)) in frames.iter().zip(&want).enumerate() {
20198 assert_eq!(got.y, want.y, "{name} frame {f} luma vs ffmpeg (cq {cq})");
20199 assert_eq!(got.u, want.u, "{name} frame {f} U vs ffmpeg (cq {cq})");
20200 assert_eq!(got.v, want.v, "{name} frame {f} V vs ffmpeg (cq {cq})");
20201 }
20202 // decoded AND compared: only now does this attempt's own
20203 // inferred-DIFFWTD count mean anything.
20204 fired += crate::decode::diffwtd_inferred_hits() - attempt_before;
20205 matched += 1;
20206 }
20207 }
20208 eprintln!(
20209 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
20210 diffwtd_inferred_hits (decoded+compared attempts only)={fired}"
20211 );
20212 assert!(matched > 0, "{name}: every attempt refused ({refusals:?}) -- no pixel compare ran");
20213 assert!(
20214 fired > 0,
20215 "{name}: no inferred-DIFFWTD 64x64 block fired on a compared attempt \
20216 ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
20217 );
20218 }
20219
20220 /// 8-bit arm of [`run_diffwtd_inferred_64x64_gate`].
20221 #[test]
20222 fn a_real_aomenc_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact() {
20223 run_diffwtd_inferred_64x64_gate(
20224 "a_real_aomenc_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact",
20225 false,
20226 );
20227 }
20228
20229 /// 10-bit arm of [`run_diffwtd_inferred_64x64_gate`] -- both of his films
20230 /// are `yuv420p10le`.
20231 #[test]
20232 fn a_real_aomenc_10bit_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact() {
20233 run_diffwtd_inferred_64x64_gate(
20234 "a_real_aomenc_10bit_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact",
20235 true,
20236 );
20237 }
20238
20239 /// lane-maskcomp r2 / lane-wedge r3: `--enable-masked-comp=1` streams
20240 /// must consume `compound_type`/`wedge_idx`/`wedge_sign`/`mask_type`
20241 /// entropy-exact AND build the real blend, DIFFWTD or WEDGE --
20242 /// `masked_compound_hits() > 0` is a hard assert and BOTH
20243 /// `COMPOUND_DIFFWTD` and `COMPOUND_WEDGE` refusals are now FORBIDDEN
20244 /// (matches interintra's own gate). r3: `--enable-dist-wtd-comp=0`
20245 /// (forces the masked choice toward wedge when comp_group_idx==1) plus
20246 /// a hard-diagonal-edge `geq` source (wedge's OBLIQUE directions favor
20247 /// a real diagonal edge over the r2 gradients content) to fire
20248 /// COMPOUND_WEDGE live; `wedge_hits()` is soft-skipped (not hard
20249 /// asserted) on a zero-hit run -- the recipe search is not proven to
20250 /// converge every run, see charter's "if no recipe fires" fallback.
20251 #[test]
20252 fn a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact() {
20253 const NAME: &str = "a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact";
20254 let _gate_lock = lock_gate_counters();
20255 if !have_ffmpeg() {
20256 eprintln!("SKIP {NAME}: no ffmpeg");
20257 return;
20258 }
20259 if !have_aomenc() {
20260 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20261 return;
20262 }
20263 let (width, height, frame_count) = (64usize, 64usize, 24usize);
20264 let mut named_refusals = 0u32;
20265 let mut matched = 0u32;
20266 let n_attempts: u32 = std::env::var("EC_MASKCOMP_GATE_ATTEMPTS")
20267 .ok()
20268 .and_then(|s| s.parse().ok())
20269 .unwrap_or(80);
20270 for attempt in 0..n_attempts {
20271 let seed = 42 + attempt;
20272 let duration = frame_count as f64 / 25.0;
20273 // lane-wedge r3: a hard diagonal edge (not a smooth gradient)
20274 // is the content wedge's OBLIQUE master masks are shaped for --
20275 // `mandelbrot`'s pan position varies the edge angle/position
20276 // across attempts the way the r2 gradients seed did.
20277 let source = format!(
20278 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
20279 sx = -0.6 + 0.005 * (attempt as f64),
20280 sy = -0.4 + 0.005 * (attempt as f64)
20281 );
20282 let y4m = Command::new("ffmpeg")
20283 .args([
20284 "-v",
20285 "error",
20286 "-f",
20287 "lavfi",
20288 "-i",
20289 &source,
20290 "-t",
20291 &duration.to_string(),
20292 "-pix_fmt",
20293 "yuv420p",
20294 "-f",
20295 "yuv4mpegpipe",
20296 "-",
20297 ])
20298 .stdin(Stdio::null())
20299 .stdout(Stdio::piped())
20300 .stderr(Stdio::piped())
20301 .output()
20302 .expect("ffmpeg failed to run");
20303 assert!(
20304 y4m.status.success(),
20305 "ffmpeg fixture: {}",
20306 String::from_utf8_lossy(&y4m.stderr)
20307 );
20308 let args: Vec<&str> = vec![
20309 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
20310 // occurrence, so overrides go before the base list).
20311 "--enable-diff-wtd-comp=1",
20312 "--codec=av1",
20313 "--passes=1",
20314 "--end-usage=q",
20315 "--cq-level=45",
20316 "--cpu-used=0",
20317 "--kf-max-dist=1000",
20318 "--threads=1",
20319 "--row-mt=0",
20320 "--auto-alt-ref=1",
20321 "--lag-in-frames=16",
20322 "--enable-fwd-kf=0",
20323 "--enable-order-hint=1",
20324 "--enable-warped-motion=1",
20325 // r3: mandelbrot's pan/zoom triggers aomenc's single-ref
20326 // GLOBALMV global-motion search (a capability distinct from
20327 // and outside this lane's scope) -- off, matching this
20328 // gate's own goal of exercising masked compound, not GM.
20329 "--enable-global-motion=0",
20330 "--enable-obmc=1",
20331 "--tune-content=default",
20332 "--enable-masked-comp=1",
20333 // r3: force the masked choice toward wedge (r2 always set
20334 // this =1; distance-weighted compound competes with the
20335 // wedge/diffwtd choice for the same comp_group_idx==1 slot).
20336 "--enable-dist-wtd-comp=0",
20337 "--enable-interintra-comp=1",
20338 "--enable-onesided-comp=0",
20339 "--enable-interintra-wedge=0",
20340 "--enable-smooth-interintra=1",
20341 "--enable-rect-partitions=0",
20342 "--enable-ab-partitions=0",
20343 "--enable-1to4-partitions=0",
20344 "--enable-filter-intra=0",
20345 "--enable-smooth-intra=0",
20346 "--enable-paeth-intra=0",
20347 "--enable-directional-intra=0",
20348 "--enable-angle-delta=0",
20349 "--enable-tx-size-search=0",
20350 "--enable-cdef=0",
20351 "--enable-restoration=0",
20352 "--max-partition-size=32",
20353 "--min-partition-size=32",
20354 "--enable-palette=0",
20355 "--enable-intrabc=0",
20356 "--enable-cfl-intra=0",
20357 "--enable-ref-frame-mvs=0",
20358 "--obu",
20359 "-o",
20360 "-",
20361 "-",
20362 ];
20363 let mut child = Command::new(aomenc_path())
20364 .args(&args)
20365 .stdin(Stdio::piped())
20366 .stdout(Stdio::piped())
20367 .stderr(Stdio::piped())
20368 .spawn()
20369 .expect("aomenc failed to start");
20370 child
20371 .stdin
20372 .take()
20373 .expect("aomenc stdin")
20374 .write_all(&y4m.stdout)
20375 .expect("writing y4m to aomenc");
20376 let out = child.wait_with_output().expect("aomenc failed to run");
20377 assert!(
20378 out.status.success(),
20379 "aomenc refused the fixture: {}",
20380 String::from_utf8_lossy(&out.stderr)
20381 );
20382 let stream = out.stdout;
20383 let frames = match decode_stream(&stream) {
20384 Err(e) => {
20385 let msg = e.to_string();
20386 assert!(
20387 msg.contains("unsupported"),
20388 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
20389 );
20390 assert!(
20391 !msg.contains("warp"),
20392 "{NAME} refused on warp (seed {seed}) -- warp decode is ported: {msg}"
20393 );
20394 assert!(
20395 !msg.contains("masked COMPOUND_REFERENCE"),
20396 "{NAME} refused a masked-compound block (seed {seed}) -- both DIFFWTD \
20397 and WEDGE blends are ported, this refusal is forbidden: {msg}"
20398 );
20399 assert!(
20400 !msg.contains("interintra"),
20401 "{NAME} refused on interintra (seed {seed}) -- non-wedge \
20402 interintra is ported: {msg}"
20403 );
20404 named_refusals += 1;
20405 eprintln!("seed {seed} refusal: {msg}");
20406 if std::env::var_os("EC_AV1_GATE_DUMP").is_some() {
20407 // r1's self-pin is armed via EC_AV1_GATE_DUMP=<path>
20408 // only for a real pixel MISMATCH below, not for this
20409 // still-expected named refusal.
20410 }
20411 continue;
20412 }
20413 Ok(frames) => frames,
20414 };
20415 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
20416 assert_eq!(frames.len(), frame_count);
20417 let mismatched = frames
20418 .iter()
20419 .zip(&ffmpeg_frames)
20420 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
20421 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
20422 std::fs::write(&path, &stream).expect("writing pinned stream");
20423 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
20424 }
20425 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20426 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
20427 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
20428 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
20429 }
20430 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
20431 // stream again, comparing EVERY decode-order frame -- the hidden
20432 // (show_frame == 0) alt-ref frames the ffmpeg compare above
20433 // cannot see, because both sides of it emit shown frames only.
20434 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
20435 eprintln!(
20436 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
20437 {hidden_n} hidden, all pixel-exact vs the oracle"
20438 );
20439 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
20440 // libaom's temporal alt-ref filter absorbs this recipe's hidden
20441 // frames, so the compare above is vacuous -- re-encode the same
20442 // fixture with --arnr-maxframes=0 and compare THOSE.
20443 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
20444 eprintln!(
20445 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
20446 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
20447 );
20448 }
20449 matched += 1;
20450 }
20451 // r1: observed flaky at 40 attempts -- aomenc's cpu-used=0 RD is
20452 // run-to-run nondeterministic in whether it ever picks
20453 // comp_group_idx == 1 for this synthetic gradients content, and
20454 // allow_screen_content_tools sometimes eats most of a small seed
20455 // window (class gate-recipe-confound / never-fired-gate, memory).
20456 // 80 attempts is the mitigation, not a fix; a still-zero run here
20457 // is that sampling flake, not a decode regression -- check
20458 // masked_compound_hits/named_refusals in the panic message before
20459 // assuming a real bug.
20460 // r2: DIFFWTD is ported and gated, so a zero-hit run is no longer
20461 // soft-skipped -- hard assert, matching the interintra gate.
20462 assert!(
20463 crate::decode::masked_compound_hits() > 0,
20464 "{NAME}: zero masked-compound blocks fired ({matched} matches, {named_refusals} \
20465 other refusals out of {n_attempts}) -- gate proved nothing this run"
20466 );
20467 // lane-defon r1: `--enable-diff-wtd-comp=1` is now spelled on this
20468 // recipe, so the DIFFWTD half of MASKED_COMPOUND_HITS must fire.
20469 assert!(
20470 crate::decode::diffwtd_hits() > 0,
20471 "{NAME}: zero COMPOUND_DIFFWTD blends ({matched} matches, {named_refusals} \
20472 other refusals out of {n_attempts}) -- --enable-diff-wtd-comp=1 proved nothing"
20473 );
20474 // r3: wedge_hits() is soft-skipped, not hard-asserted -- the recipe
20475 // search (dist-wtd-comp=0 + diagonal mandelbrot content) is not
20476 // proven to fire wedge on every run; charter's fallback is to land
20477 // the checksum-verified codebook + blend with this soft path.
20478 if crate::decode::wedge_hits() == 0 {
20479 eprintln!(
20480 "{NAME}: WARNING wedge_hits()==0 this run -- COMPOUND_WEDGE never fired \
20481 ({matched} matches, {named_refusals} refusals out of {n_attempts}); codebook \
20482 is checksum-verified but unexercised live this run"
20483 );
20484 }
20485 eprintln!(
20486 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
20487 out of {n_attempts}, masked_compound_hits={} wedge_hits={}",
20488 crate::decode::masked_compound_hits(),
20489 crate::decode::wedge_hits()
20490 );
20491 }
20492
20493
20494 /// lane-inter16ab r5: `COMPOUND_WEDGE` on a RECTANGULAR inter block --
20495 /// the shapes `av1_wedge_params_lookup` gives the `hgtw`/`hltw`
20496 /// codebooks (8x16/16x32/8x32 and 16x8/32x16/32x8), which this decoder
20497 /// refused by name until this round ("the wedge codebook is
20498 /// square-only"). `--enable-rect-partitions=1` with
20499 /// `--min-partition-size=16 --max-partition-size=32` is what makes
20500 /// aomenc's RD put a masked compound block on a 16x32/32x16 strip
20501 /// (measured: ~/.cache/inter16ab-tmp/rw2.sh, 24/24 streams at cq 50/55
20502 /// carry one and decode to the end at BOTH bit depths).
20503 ///
20504 /// Class `counter-from-refused-stream`: the per-shape counters are read
20505 /// as a DELTA around one attempt and only counted for attempts that
20506 /// decoded fully AND compared pixel-exact -- a refused attempt's hits
20507 /// are discarded. Every decode-order frame (including hidden alt-ref
20508 /// frames) is compared via [`decode_all_frames_vs_oracle`], and an
20509 /// attempt that mismatches while carrying NO rect wedge fails the gate
20510 /// through `oos_mismatch` rather than being blamed on this lane.
20511 #[test]
20512 fn a_real_aomenc_stream_with_a_rectangular_compound_wedge_decodes_pixel_exact() {
20513 const NAME: &str =
20514 "a_real_aomenc_stream_with_a_rectangular_compound_wedge_decodes_pixel_exact";
20515 let _gate_lock = lock_gate_counters();
20516 if !have_ffmpeg() {
20517 eprintln!("SKIP {NAME}: no ffmpeg");
20518 return;
20519 }
20520 if !have_aomenc() {
20521 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20522 return;
20523 }
20524 let (width, height, frame_count) = (96usize, 96usize, 24usize);
20525 // Per rect shape (8x16, 16x8, 16x32, 32x16, 8x32, 32x8), summed over
20526 // the attempts that decoded AND matched.
20527 let mut shapes_proved = [0usize; 6];
20528 let (mut named_refusals, mut matched, mut oos_mismatch) = (0u32, 0u32, 0u32);
20529 let mut attempts = 0u32;
20530 for bit_depth in [8u32, 10u32] {
20531 for &cq in &[50u32, 55] {
20532 for a in 0..4u32 {
20533 attempts += 1;
20534 let duration = frame_count as f64 / 25.0;
20535 // Same hard-diagonal-edge content the square wedge gate
20536 // uses (wedge's masters are OBLIQUE), panned per attempt.
20537 let source = format!(
20538 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
20539 sx = -0.6 + 0.01 * (a as f64),
20540 sy = -0.4 + 0.01 * (a as f64)
20541 );
20542 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
20543 let y4m = Command::new("ffmpeg")
20544 .args([
20545 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
20546 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
20547 "-f", "yuv4mpegpipe", "-strict", "-1", "-",
20548 ])
20549 .stdin(Stdio::null())
20550 .stdout(Stdio::piped())
20551 .stderr(Stdio::piped())
20552 .output()
20553 .expect("ffmpeg failed to run");
20554 assert!(
20555 y4m.status.success(),
20556 "{NAME}: ffmpeg fixture: {}",
20557 String::from_utf8_lossy(&y4m.stderr)
20558 );
20559 let cq_arg = format!("--cq-level={cq}");
20560 let depth_arg = format!("--bit-depth={bit_depth}");
20561 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
20562 let args: Vec<&str> = vec![
20563 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
20564 &depth_arg, &input_depth_arg,
20565 "--kf-max-dist=1000", "--threads=1", "--row-mt=0", "--auto-alt-ref=1",
20566 "--lag-in-frames=16", "--enable-fwd-kf=0", "--enable-order-hint=1",
20567 "--enable-warped-motion=1", "--enable-global-motion=0",
20568 "--enable-obmc=1", "--enable-diff-wtd-comp=1",
20569 "--enable-interintra-comp=1", "--enable-onesided-comp=0",
20570 "--enable-interintra-wedge=1", "--enable-smooth-interintra=1",
20571 "--enable-ab-partitions=0", "--enable-1to4-partitions=0",
20572 "--enable-filter-intra=0", "--enable-smooth-intra=0",
20573 "--enable-paeth-intra=0", "--enable-directional-intra=0",
20574 "--enable-angle-delta=0", "--enable-tx-size-search=0",
20575 "--enable-cdef=0", "--enable-restoration=0", "--enable-palette=0",
20576 "--enable-intrabc=0", "--enable-cfl-intra=0",
20577 "--enable-ref-frame-mvs=0",
20578 // Per-arm overrides LAST (aomenc keeps the last
20579 // occurrence of a repeated --enable-* flag): masked
20580 // compound ON, distance-weighted OFF so the
20581 // comp_group_idx==1 slot goes to wedge/diffwtd, and
20582 // rectangular partitions ON at 16/32 -- the shapes
20583 // the hgtw/hltw codebooks exist for.
20584 "--enable-masked-comp=1", "--enable-dist-wtd-comp=0",
20585 "--enable-rect-partitions=1",
20586 "--min-partition-size=16", "--max-partition-size=32",
20587 "--obu", "-o", "-", "-",
20588 ];
20589 let mut child = Command::new(aomenc_path())
20590 .args(&args)
20591 .stdin(Stdio::piped())
20592 .stdout(Stdio::piped())
20593 .stderr(Stdio::piped())
20594 .spawn()
20595 .expect("aomenc failed to start");
20596 child
20597 .stdin
20598 .take()
20599 .expect("aomenc stdin")
20600 .write_all(&y4m.stdout)
20601 .expect("writing y4m to aomenc");
20602 let out = child.wait_with_output().expect("aomenc failed to run");
20603 assert!(
20604 out.status.success(),
20605 "aomenc refused the fixture: {}",
20606 String::from_utf8_lossy(&out.stderr)
20607 );
20608 let stream = out.stdout;
20609 let before = crate::stream::rect_wedge_hits();
20610 let frames = match decode_stream(&stream) {
20611 Err(e) => {
20612 let msg = e.to_string();
20613 assert!(
20614 msg.contains("unsupported"),
20615 "{NAME} failed outright, not a named refusal \
20616 ({bit_depth}-bit cq{cq} attempt {a}): {msg}"
20617 );
20618 assert!(
20619 !msg.contains("wedge codebook is square-only"),
20620 "{NAME}: the rect wedge codebook is ported -- this refusal is \
20621 forbidden ({bit_depth}-bit cq{cq} attempt {a}): {msg}"
20622 );
20623 named_refusals += 1;
20624 eprintln!("{bit_depth}-bit cq{cq} attempt {a} refusal: {msg}");
20625 continue;
20626 }
20627 Ok(frames) => frames,
20628 };
20629 let after = crate::stream::rect_wedge_hits();
20630 let fired: Vec<usize> =
20631 (0..6).map(|k| after[k] - before[k]).collect();
20632 let ffmpeg_frames = if bit_depth == 10 {
20633 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20634 } else {
20635 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20636 };
20637 assert_eq!(frames.len(), ffmpeg_frames.len());
20638 let mismatched = frames
20639 .iter()
20640 .zip(&ffmpeg_frames)
20641 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
20642 if fired.iter().sum::<usize>() == 0 {
20643 if mismatched {
20644 oos_mismatch += 1;
20645 eprintln!(
20646 "{NAME}: {bit_depth}-bit cq{cq} attempt {a} MISMATCHES with zero \
20647 rectangular wedge block -- another shape's defect"
20648 );
20649 }
20650 continue;
20651 }
20652 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20653 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit cq{cq} attempt {a}, shapes {fired:?})");
20654 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit cq{cq} attempt {a}, shapes {fired:?})");
20655 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit cq{cq} attempt {a}, shapes {fired:?})");
20656 }
20657 // class gate-blind-to-hidden-frames: the shown-frame
20658 // compare above cannot see the alt-ref frames this
20659 // recipe's --lag-in-frames=16 produces.
20660 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
20661 eprintln!(
20662 "{NAME}: {bit_depth}-bit cq{cq} attempt {a}: shapes {fired:?}, \
20663 {hidden_total} decode-order frames ({hidden_n} hidden) pixel-exact"
20664 );
20665 for k in 0..6 {
20666 shapes_proved[k] += fired[k];
20667 }
20668 matched += 1;
20669 }
20670 }
20671 }
20672 eprintln!(
20673 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact attempts out of \
20674 {attempts}, rect wedge blocks per shape \
20675 (8x16,16x8,16x32,32x16,8x32,32x8)={shapes_proved:?}, {oos_mismatch} zero-wedge \
20676 mismatches"
20677 );
20678 assert_eq!(
20679 oos_mismatch, 0,
20680 "{NAME}: {oos_mismatch} attempt(s) carrying no rectangular wedge mismatched ffmpeg \
20681 -- a defect of another shape, not a pass"
20682 );
20683 // The claim: a rectangular wedge codebook row (hgtw AND hltw) was
20684 // used on a stream that then decoded pixel-exact. 16x32 is hgtw
20685 // (h > w), 32x16 is hltw (h < w) -- one of each, so a transposed
20686 // codebook/signflip pair cannot pass this.
20687 assert!(
20688 shapes_proved[2] > 0 && shapes_proved[3] > 0,
20689 "{NAME}: no pixel-exact attempt used both an hgtw (16x32) and an hltw (32x16) \
20690 rectangular wedge codebook row (per shape {shapes_proved:?}, {matched} matches, \
20691 {named_refusals} refusals out of {attempts}) -- the recipe proved nothing"
20692 );
20693 }
20694
20695
20696 /// lane-lr r3: proves stage 1/2's exit criterion -- a real
20697 /// `--enable-restoration=1` aomenc stream must survive the whole
20698 /// partition walk (every symbol read entropy-exact) and land on the
20699 /// NEW, narrowed refusal ("read but not applied"), never desync into
20700 /// some other named refusal or an outright decode panic. Multi-superblock
20701 /// fixture (192x128 = 3x2 SBs of 64px) per the charter's own trap
20702 /// warning -- a single-SB fixture can never re-enter `read_lr` a second
20703 /// time and would leave `SWITCHABLE_HITS`/etc. proving only one call
20704 /// site, not the per-SB loop.
20705 #[test]
20706 fn a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly() {
20707 const NAME: &str = "a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly";
20708 let _gate_lock = lock_gate_counters();
20709 if !have_ffmpeg() {
20710 eprintln!("SKIP {NAME}: no ffmpeg");
20711 return;
20712 }
20713 if !have_aomenc() {
20714 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20715 return;
20716 }
20717 // lane-reelckf2 r1: 152 = 2*64+24, not 128 -- the 8-bit twin of the
20718 // partial-bottom-stripe LR gate below. Stripe shapes at 128 rows are
20719 // a strict subset of those at 152 (56, 64, then the 32-row tail whose
20720 // below boundary is the frame's own last row).
20721 let (width, height) = (192usize, 152usize);
20722 let n_attempts: u32 = std::env::var("EC_LR_GATE_ATTEMPTS")
20723 .ok()
20724 .and_then(|s| s.parse().ok())
20725 .unwrap_or(40);
20726 let mut lr_refusals = 0u32;
20727 let mut other_refusals = Vec::new();
20728 // lane-reelckf2 r1: the two special stripe shapes this size now has.
20729 let stripe0_before = crate::restoration::lr_stripe0_hits();
20730 let last_stripe_before = crate::restoration::lr_last_stripe_hits();
20731 for attempt in 0..n_attempts {
20732 let seed = 42 + attempt;
20733 // Diagnosis knob: which content makes RD pick an 8x16/16x8 strip
20734 // AND filter intra on it is a search (see lanes/fistrip-r1.report.md).
20735 let source = match std::env::var("EC_FISTRIP_SRC").unwrap_or_default().as_str() {
20736 "bars" => format!("smptebars=size={width}x{height}:duration=0.04:rate=25"),
20737 "src2" => format!("testsrc2=size={width}x{height}:duration=0.04:rate=25"),
20738 "noise" => format!(
20739 "nullsrc=size={width}x{height}:duration=0.04:rate=25,geq=random(1)*255:128:128"
20740 ),
20741 _ => gradients_source(seed, width, height, "duration=0.04:rate=25"),
20742 };
20743 let y4m = Command::new("ffmpeg")
20744 .args(["-v", "error", "-f", "lavfi", "-i"])
20745 .arg(&source)
20746 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
20747 .stdin(Stdio::null())
20748 .stdout(Stdio::piped())
20749 .stderr(Stdio::piped())
20750 .output()
20751 .expect("ffmpeg failed to run");
20752 assert!(
20753 y4m.status.success(),
20754 "ffmpeg fixture: {}",
20755 String::from_utf8_lossy(&y4m.stderr)
20756 );
20757 let mut child = Command::new(aomenc_path())
20758 .args([
20759 "--codec=av1",
20760 "--passes=1",
20761 "--end-usage=q",
20762 // r3: a low cq-level (high quality/bitrate) is load-bearing --
20763 // sampled live (2026-08-30) that aomenc's RD only ever picks a
20764 // non-`RESTORE_NONE` frame_restoration_type at cq-level<=20 for
20765 // this fixture; cq-level=45 (this gate's sibling gates' usual
20766 // value) landed `uses_lr=false` on every attempt.
20767 "--cq-level=15",
20768 "--cpu-used=0",
20769 "--threads=1",
20770 "--row-mt=0",
20771 // r3: this decoder always assumes 64px superblocks
20772 // (`decode.rs` hardcodes `SB_MI=16`, ledger `lane-sb128`
20773 // dead-ends) -- force aomenc to match rather than risk
20774 // the unrelated sb128 gap eating this gate's own window.
20775 "--sb-size=64",
20776 "--enable-restoration=1",
20777 "--enable-cdef=0",
20778 "--enable-rect-partitions=0",
20779 "--enable-ab-partitions=0",
20780 "--enable-1to4-partitions=0",
20781 "--enable-filter-intra=0",
20782 "--enable-smooth-intra=0",
20783 "--enable-paeth-intra=0",
20784 "--enable-tx-size-search=0",
20785 "--max-partition-size=32",
20786 "--min-partition-size=16",
20787 "--enable-palette=0",
20788 "--enable-intrabc=0",
20789 "--enable-cfl-intra=0",
20790 "--enable-ref-frame-mvs=0",
20791 "--enable-warped-motion=0",
20792 "--enable-global-motion=0",
20793 "--enable-masked-comp=0",
20794 "--enable-interintra-comp=0",
20795 "--enable-obmc=0",
20796 "--obu",
20797 "-o",
20798 "-",
20799 "-",
20800 ])
20801 .stdin(Stdio::piped())
20802 .stdout(Stdio::piped())
20803 .stderr(Stdio::piped())
20804 .spawn()
20805 .expect("aomenc failed to start");
20806 child
20807 .stdin
20808 .take()
20809 .expect("aomenc stdin")
20810 .write_all(&y4m.stdout)
20811 .expect("writing y4m to aomenc");
20812 let out = child.wait_with_output().expect("aomenc failed to run");
20813 assert!(
20814 out.status.success(),
20815 "aomenc refused the fixture: {}",
20816 String::from_utf8_lossy(&out.stderr)
20817 );
20818 let stream = out.stdout;
20819 match decode_stream(&stream) {
20820 Ok(pics) => {
20821 // r4: the pixel filters are wired -- every `uses_lr`
20822 // frame must now decode Ok AND match an independent
20823 // decoder pixel-exact, not just refuse cleanly.
20824 let reference = ffmpeg_decode_sequence(&stream, width, height, pics.len());
20825 let mismatched = pics
20826 .iter()
20827 .zip(&reference)
20828 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
20829 // r7: pin a mismatching stream the same way the
20830 // masked-compound gate does -- lets a follow-up round
20831 // decode this exact seed's bytes directly instead of
20832 // re-deriving them from a live 40-attempt sweep.
20833 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
20834 std::fs::write(&path, &stream).expect("writing pinned stream");
20835 eprintln!(
20836 "EC_AV1_GATE_DUMP: wrote mismatching LR stream (seed {seed}) to {path}"
20837 );
20838 }
20839 for (i, (pic, refpic)) in pics.iter().zip(reference.iter()).enumerate() {
20840 assert_eq!(pic.y, refpic.y, "{NAME}: luma mismatch (seed {seed} frame {i})");
20841 assert_eq!(pic.u, refpic.u, "{NAME}: U mismatch (seed {seed} frame {i})");
20842 assert_eq!(pic.v, refpic.v, "{NAME}: V mismatch (seed {seed} frame {i})");
20843 }
20844 lr_refusals += 1; // reused below as "attempts that actually exercised LR pixels"
20845 }
20846 Err(e) => {
20847 let msg = e.to_string();
20848 other_refusals.push(format!("seed {seed}: {msg}"));
20849 }
20850 }
20851 }
20852 assert!(
20853 other_refusals.is_empty(),
20854 "{NAME}: {} attempts failed outright instead of decoding:\n{}",
20855 other_refusals.len(),
20856 other_refusals.join("\n")
20857 );
20858 assert!(
20859 lr_refusals > 0,
20860 "{NAME}: no attempt ever decoded pixel-exact ({n_attempts} attempts)"
20861 );
20862 // Any real (non-`RESTORE_NONE`) filter kind is acceptable proof --
20863 // aomenc's RD picks the frame-level `restoration_type` itself (not
20864 // always `Switchable`; observed `Sgrproj` live at cq-level=15 for
20865 // this fixture), so hard-requiring one specific arm would be the
20866 // gate-recipe-confound class (ledger).
20867 let total_hits = crate::restoration::wiener_hits()
20868 + crate::restoration::sgrproj_hits()
20869 + crate::restoration::switchable_hits();
20870 assert!(
20871 total_hits > 0,
20872 "{NAME}: {lr_refusals} LR refusals fired but read_lr_unit never decoded a real \
20873 (non-None) filter -- gate proved nothing about the symbol path"
20874 );
20875 // lane-reelckf2 r1: a size with a partial bottom stripe proves nothing
20876 // about the two frame-edge stripe shapes unless a real filter actually
20877 // ran on them (`filter_restoration_unit`).
20878 assert!(
20879 crate::restoration::lr_stripe0_hits() > stripe0_before
20880 && crate::restoration::lr_last_stripe_hits() > last_stripe_before,
20881 "{NAME}: no filtered stripe took the frame's own top/bottom row as its boundary \
20882 (stripe0 +{}, last +{})",
20883 crate::restoration::lr_stripe0_hits() - stripe0_before,
20884 crate::restoration::lr_last_stripe_hits() - last_stripe_before
20885 );
20886 eprintln!(
20887 "{NAME}: {lr_refusals} LR refusals, {} other refusals out of {n_attempts}, \
20888 wiener_hits={} sgrproj_hits={} switchable_hits={}",
20889 other_refusals.len(),
20890 crate::restoration::wiener_hits(),
20891 crate::restoration::sgrproj_hits(),
20892 crate::restoration::switchable_hits()
20893 );
20894 }
20895
20896 /// r8: decode the ONE pinned stream `EC_AV1_GATE_DUMP` captured in r7
20897 /// (`fixtures/lr-sgr-r7.obu`, seed 46) directly -- not the live
20898 /// 40-attempt sweep, which reuses `v_start` coordinates across unrelated
20899 /// seeds/frames and made r6's captured 9 bytes unprovable. Run with
20900 /// `EC_LR_CALL_DUMP=1` set (see `restoration.rs`'s `apply_sgrproj_stripe`)
20901 /// to get the real window on stderr, call-uniquely keyed to `xqd ==
20902 /// [-16,-32]` rather than any coordinate.
20903 #[test]
20904 #[ignore = "reads a pinned fixture under the gitignored fixtures dir; run manually with EC_LR_CALL_DUMP=1"]
20905 fn pinned_lr_sgr_stream_call_unique_dump() {
20906 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/lr-sgr-r7.obu");
20907 let stream = std::fs::read(path).expect("reading pinned lr-sgr-r7.obu");
20908 let pics = decode_stream(&stream).expect("pinned lr-sgr-r7.obu must decode");
20909 if have_ffmpeg() {
20910 let reference = ffmpeg_decode_sequence(&stream, 192, 128, pics.len());
20911 for (i, (got, want)) in pics.iter().zip(&reference).enumerate() {
20912 let y_mismatch = got.y != want.y;
20913 let u_mismatch = got.u != want.u;
20914 let v_mismatch = got.v != want.v;
20915 eprintln!(
20916 "frame {i}: y_mismatch={y_mismatch} u_mismatch={u_mismatch} v_mismatch={v_mismatch}"
20917 );
20918 if y_mismatch {
20919 let n = got.y.iter().zip(&want.y).filter(|(a, b)| a != b).count();
20920 eprintln!(" {n} luma bytes differ / {}", got.y.len());
20921 }
20922 if v_mismatch {
20923 let w = 96usize; // chroma plane width (192/2)
20924 for (idx, (a, b)) in got.v.iter().zip(&want.v).enumerate() {
20925 if a != b {
20926 eprintln!(" V[{},{}] got={a} want={b}", idx / w, idx % w);
20927 }
20928 }
20929 }
20930 }
20931 }
20932 }
20933
20934 /// lane-realworld r2: `read_cdef` (spec 5.11.56) ported -- per-superblock
20935 /// `cdef_idx`, wired at all five `skip`-decode sites, `apply_cdef` looks
20936 /// up strength through the grid instead of a hardcoded `[0]`. Structure
20937 /// copied from `a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact`
20938 /// but `--enable-cdef=1` (the one thing that gate turns off) and every
20939 /// *other* filter/mode feature this lane doesn't touch disabled, so a
20940 /// mismatch here can only be attributed to CDEF. `cdef_idx_hits()` is a
20941 /// hard assert -- a run that never reads a real cdef_idx symbol proves
20942 /// nothing (class `gate-blind-to-feature`).
20943 #[test]
20944 fn a_real_aomenc_stream_with_cdef_decodes_pixel_exact() {
20945 const NAME: &str = "a_real_aomenc_stream_with_cdef_decodes_pixel_exact";
20946 let _gate_lock = lock_gate_counters();
20947 if !have_ffmpeg() {
20948 eprintln!("SKIP {NAME}: no ffmpeg");
20949 return;
20950 }
20951 if !have_aomenc() {
20952 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20953 return;
20954 }
20955 // cdef_bits selects among PER-SUPERBLOCK strengths -- a single-SB
20956 // 64x64 frame (the other gates' size) gives aomenc nothing to
20957 // differentiate, so it always writes bits=0 and cdef_idx is never
20958 // read. 128x64 = 2 SBs is the minimum that lets aomenc's RD ever
20959 // pick bits > 0. Multi-SB content at --cpu-used=0 (every other
20960 // gate's setting) makes aomenc pick PARTITION_HORZ_4/VERT_B etc.
20961 // at the top SB level regardless of the ab/1to4-partitions=0
20962 // flags below (a real gap: this decoder's intra part64 match only
20963 // covers NONE/SPLIT, and the inter path blindly assumes SPLIT --
20964 // both pre-existing, out of this lane's scope); --cpu-used=4
20965 // avoids that RD path entirely and needs --aq-mode=0
20966 // --deltaq-mode=0 to keep delta_q/delta_lf (next lane step) off.
20967 let (width, height, frame_count) = (128usize, 64usize, 24usize);
20968 let mut named_refusals = 0u32;
20969 let mut matched = 0u32;
20970 let n_attempts: u32 = std::env::var("EC_CDEF_GATE_ATTEMPTS")
20971 .ok()
20972 .and_then(|s| s.parse().ok())
20973 .unwrap_or(40);
20974 for attempt in 0..n_attempts {
20975 let seed = 42 + attempt;
20976 let duration = frame_count as f64 / 25.0;
20977 // mandelbrot's ringing-prone hard edges are what CDEF's RD
20978 // search targets; flat gradients (charter's first guess) may
20979 // never make aomenc choose cdef_bits > 0.
20980 let source = format!(
20981 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
20982 sx = -0.6 + 0.005 * (attempt as f64),
20983 sy = -0.4 + 0.005 * (attempt as f64)
20984 );
20985 let y4m = Command::new("ffmpeg")
20986 .args([
20987 "-v",
20988 "error",
20989 "-f",
20990 "lavfi",
20991 "-i",
20992 &source,
20993 "-t",
20994 &duration.to_string(),
20995 "-pix_fmt",
20996 "yuv420p",
20997 "-f",
20998 "yuv4mpegpipe",
20999 "-",
21000 ])
21001 .stdin(Stdio::null())
21002 .stdout(Stdio::piped())
21003 .stderr(Stdio::piped())
21004 .output()
21005 .expect("ffmpeg failed to run");
21006 assert!(
21007 y4m.status.success(),
21008 "ffmpeg fixture: {}",
21009 String::from_utf8_lossy(&y4m.stderr)
21010 );
21011 let args: Vec<&str> = vec![
21012 "--codec=av1",
21013 "--passes=1",
21014 "--end-usage=q",
21015 "--cq-level=45",
21016 "--cpu-used=4",
21017 "--aq-mode=0",
21018 "--deltaq-mode=0",
21019 "--enable-cdef=0",
21020 "--kf-max-dist=1000",
21021 "--threads=1",
21022 "--row-mt=0",
21023 "--auto-alt-ref=1",
21024 "--lag-in-frames=16",
21025 "--enable-fwd-kf=0",
21026 "--enable-order-hint=1",
21027 // r2: a starved inter toolset (everything below off) pushes
21028 // aomenc's RD toward exotic partition shapes (HORZ_4/VERT_B
21029 // etc.) at the SB(64) level even with those partition
21030 // flags off -- this decoder's part64 8/9/10-way arms and
21031 // the inter path's blind SPLIT assumption don't cover that;
21032 // keeping the same rich toolset the (working, ab/1to4-off)
21033 // masked-compound gate uses avoids it.
21034 "--enable-warped-motion=1",
21035 "--enable-global-motion=0",
21036 "--enable-obmc=1",
21037 "--tune-content=default",
21038 "--enable-masked-comp=1",
21039 "--enable-dist-wtd-comp=0",
21040 "--enable-interintra-comp=1",
21041 "--enable-onesided-comp=0",
21042 "--enable-interintra-wedge=0",
21043 "--enable-smooth-interintra=1",
21044 "--enable-rect-partitions=0",
21045 "--enable-ab-partitions=0",
21046 "--enable-1to4-partitions=0",
21047 "--enable-filter-intra=0",
21048 "--enable-smooth-intra=0",
21049 "--enable-paeth-intra=0",
21050 "--enable-directional-intra=0",
21051 "--enable-angle-delta=0",
21052 "--enable-tx-size-search=0",
21053 "--enable-cdef=1",
21054 "--enable-restoration=0",
21055 "--max-partition-size=32",
21056 "--min-partition-size=32",
21057 "--enable-palette=0",
21058 "--enable-intrabc=0",
21059 "--enable-cfl-intra=0",
21060 "--enable-ref-frame-mvs=0",
21061 "--obu",
21062 "-o",
21063 "-",
21064 "-",
21065 ];
21066 let mut child = Command::new(aomenc_path())
21067 .args(&args)
21068 .stdin(Stdio::piped())
21069 .stdout(Stdio::piped())
21070 .stderr(Stdio::piped())
21071 .spawn()
21072 .expect("aomenc failed to start");
21073 child
21074 .stdin
21075 .take()
21076 .expect("aomenc stdin")
21077 .write_all(&y4m.stdout)
21078 .expect("writing y4m to aomenc");
21079 let out = child.wait_with_output().expect("aomenc failed to run");
21080 assert!(
21081 out.status.success(),
21082 "aomenc refused the fixture: {}",
21083 String::from_utf8_lossy(&out.stderr)
21084 );
21085 let stream = out.stdout;
21086 let frames = match decode_stream(&stream) {
21087 Err(e) => {
21088 let msg = e.to_string();
21089 assert!(
21090 msg.contains("unsupported"),
21091 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
21092 );
21093 assert!(
21094 !msg.contains("cdef"),
21095 "{NAME} refused on cdef (seed {seed}) -- cdef_idx decode is ported: {msg}"
21096 );
21097 named_refusals += 1;
21098 eprintln!("seed {seed} refusal: {msg}");
21099 continue;
21100 }
21101 Ok(frames) => frames,
21102 };
21103 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
21104 assert_eq!(frames.len(), frame_count);
21105 let mismatched = frames
21106 .iter()
21107 .zip(&ffmpeg_frames)
21108 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
21109 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
21110 std::fs::write(&path, &stream).expect("writing pinned stream");
21111 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
21112 }
21113 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21114 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
21115 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
21116 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
21117 }
21118 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
21119 // stream again, comparing EVERY decode-order frame -- the hidden
21120 // (show_frame == 0) alt-ref frames the ffmpeg compare above
21121 // cannot see, because both sides of it emit shown frames only.
21122 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
21123 eprintln!(
21124 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
21125 {hidden_n} hidden, all pixel-exact vs the oracle"
21126 );
21127 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
21128 // libaom's temporal alt-ref filter absorbs this recipe's hidden
21129 // frames, so the compare above is vacuous -- re-encode the same
21130 // fixture with --arnr-maxframes=0 and compare THOSE.
21131 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
21132 eprintln!(
21133 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
21134 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
21135 );
21136 }
21137 matched += 1;
21138 }
21139 assert!(
21140 crate::decode::cdef_idx_hits() > 0,
21141 "{NAME}: zero cdef_idx blocks fired ({matched} matches, {named_refusals} other \
21142 refusals out of {n_attempts}) -- gate proved nothing this run"
21143 );
21144 eprintln!(
21145 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
21146 out of {n_attempts}, cdef_idx_hits={}",
21147 crate::decode::cdef_idx_hits()
21148 );
21149 }
21150 /// lane-edgeboth r1 GATE: frame sizes whose width AND height are both
21151 /// 8 mod 16, so the bottom-right corner of the frame is a partition node
21152 /// with `has_rows == false && has_cols == false` at every level it
21153 /// reaches -- libaom `decode_partition` forces PARTITION_SPLIT there and
21154 /// reads NO symbol (`else if (!has_rows && !has_cols) partition =
21155 /// PARTITION_SPLIT;`), then drops the out-of-frame children on its
21156 /// `if (mi_row >= mi_rows || mi_col >= mi_cols) return;` early return.
21157 /// The 64 and 32 levels already inferred that split; the 16 level refused
21158 /// by name until r1, on both the intra (key) and the inter path -- so both
21159 /// arms are swept here. Every compared attempt must show a 16-level
21160 /// both-cut hit, and the sweep must show 32- and 64-level hits too (200x72
21161 /// puts all three levels in that state: mi_cols 50, mi_rows 18, so the
21162 /// nodes at mi (16,48) of size 64, 32 and 16 are all cut on both axes).
21163 #[test]
21164 fn a_real_aomenc_both_axes_cut_corner_block_decodes_pixel_exact() {
21165 both_axes_cut_sweep(
21166 "a_real_aomenc_both_axes_cut_corner_block_decodes_pixel_exact",
21167 ("key", 1, "--kf-max-dist=0", "--limit=1"),
21168 );
21169 }
21170
21171 /// lane-edgeboth r1, INTER half of the same lift. Un-ignored 2026-09-04: the inter frame-edge half-strip band defect that blocked it is gone. As measured then: the inter path's both-cut corner block
21172 /// itself decodes exactly (200x72 inter cq 32, luma diff bounding box rows
21173 /// 64..=71 cols 15..=186 -- the corner at cols 192..=199 is clean), but the
21174 /// bottom 8-row frame-edge BAND of an inter frame is wrong, and the
21175 /// control 192x72 (width a multiple of 16, so zero both-cut nodes: hits
21176 /// [0,0,0,0]) fails identically at rows 64..=71 cols 8..=188. That band is
21177 /// the forced one-axis HORZ half strip on the inter path -- lane-oddh's
21178 /// own inter gate is `#[ignore]`d for the same arm -- so this gate turns
21179 /// green with that defect, not with anything this lane changed.
21180 #[test]
21181 fn a_real_aomenc_both_axes_cut_corner_inter_frames_decode_pixel_exact() {
21182 both_axes_cut_sweep(
21183 "a_real_aomenc_both_axes_cut_corner_inter_frames_decode_pixel_exact",
21184 ("inter", 6, "--kf-max-dist=9999", "--limit=6"),
21185 );
21186 }
21187
21188 fn both_axes_cut_sweep(
21189 name: &'static str,
21190 (arm, frames, kf_arg, limit_arg): (&str, usize, &str, &str),
21191 ) {
21192 // Kept upper-case so every message string below reads the same as in
21193 // the sibling gates.
21194 #[allow(non_snake_case)]
21195 let NAME = name;
21196 let _gate_lock = lock_gate_counters();
21197 if !have_ffmpeg() || !have_aomenc() {
21198 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
21199 return;
21200 }
21201 let sizes: &[(usize, usize)] = &[(200, 72), (136, 104), (264, 136), (72, 200), (104, 136)];
21202 let mut compared = 0u32;
21203 let mut refusals: Vec<String> = Vec::new();
21204 let mut totals = [0usize; 4];
21205 for &(width, height) in sizes {
21206 let mut size_compared = 0u32;
21207 {
21208 for bit_depth in [8u32, 10u32] {
21209 // cq 58 is left out on purpose: measured r1, it is where
21210 // libaom starts answering the frame-edge gathered symbol
21211 // with a rect strip and other lanes' refusals fire first
21212 // ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs
21213 // rectangular residual coding").
21214 for cq in [32u32, 45] {
21215 let source = format!("mandelbrot=size={width}x{height}:rate=25");
21216 // Feed exactly `frames` frames: --limit=1 makes
21217 // aomenc stop reading after the first one and the
21218 // y4m write then dies on a broken pipe.
21219 let dur = format!("{}", frames as f64 / 25.0);
21220 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
21221 let y4m = Command::new("ffmpeg")
21222 .args([
21223 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &dur,
21224 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
21225 ])
21226 .stdin(Stdio::null())
21227 .stdout(Stdio::piped())
21228 .stderr(Stdio::piped())
21229 .output()
21230 .expect("ffmpeg failed to run");
21231 assert!(
21232 y4m.status.success(),
21233 "{NAME}: ffmpeg refused the {width}x{height} {bit_depth}-bit \
21234 fixture: {}",
21235 String::from_utf8_lossy(&y4m.stderr)
21236 );
21237 let depth_arg = format!("--bit-depth={bit_depth}");
21238 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
21239 let cq_arg = format!("--cq-level={cq}");
21240 let mut child = Command::new(aomenc_path())
21241 .args([
21242 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg,
21243 // cpu-used >= 1 keeps libaom on 64x64
21244 // superblocks at these sizes
21245 // (`av1_select_sb_size`).
21246 "--cpu-used=4", "--threads=1", "--row-mt=0",
21247 // --lag-in-frames=0: no hidden alt-ref, so
21248 // decode order == display order and the
21249 // compare below covers every frame the stream
21250 // carries (class gate-blind-to-hidden-frames).
21251 kf_arg, limit_arg, "--lag-in-frames=0",
21252 &depth_arg, &input_depth_arg,
21253 // Other lanes' named refusals this recipe must
21254 // not trip. The both-cut corner is FORCED down
21255 // to 8x8 leaves, which is exactly where the
21256 // 8x8-intra-leaf-in-an-inter-frame gaps live,
21257 // so the intra tool set and tx-size search are
21258 // pinned off: without them 30/30 inter
21259 // attempts refused (measured r1) on "a nonzero
21260 // angle delta on an 8x8 intra leaf in an inter
21261 // frame", "a non-DC chroma mode on an 8x8
21262 // inter-frame leaf" and "an 8x8 intra leaf in
21263 // an inter frame whose tx_depth splits it into
21264 // 4x4 transform units".
21265 "--enable-rect-partitions=0", "--enable-ab-partitions=0",
21266 "--enable-1to4-partitions=0",
21267 "--min-partition-size=8", "--max-partition-size=64",
21268 "--enable-palette=0", "--enable-intrabc=0",
21269 "--enable-warped-motion=0", "--enable-obmc=0",
21270 "--enable-masked-comp=0", "--enable-interintra-comp=0",
21271 "--enable-onesided-comp=0", "--enable-interintra-wedge=0",
21272 "--enable-smooth-interintra=0", "--enable-ref-frame-mvs=0",
21273 "--enable-angle-delta=0", "--enable-cfl-intra=0",
21274 "--enable-directional-intra=0", "--enable-smooth-intra=0",
21275 "--enable-paeth-intra=0", "--enable-filter-intra=0",
21276 "--enable-tx-size-search=0",
21277 "--obu", "-o", "-", "-",
21278 ])
21279 .stdin(Stdio::piped())
21280 .stdout(Stdio::piped())
21281 .stderr(Stdio::piped())
21282 .spawn()
21283 .expect("aomenc failed to start");
21284 child
21285 .stdin
21286 .take()
21287 .expect("aomenc stdin")
21288 .write_all(&y4m.stdout)
21289 .expect("write y4m");
21290 let out = child.wait_with_output().expect("aomenc failed to run");
21291 assert!(
21292 out.status.success(),
21293 "aomenc refused: {}",
21294 String::from_utf8_lossy(&out.stderr)
21295 );
21296 let stream = out.stdout;
21297
21298 // Reset, never a delta across attempts: a refused
21299 // attempt's hits must not count (class
21300 // counter-from-refused-stream).
21301 crate::decode::reset_edge_both_cut_hits();
21302 let decoded = match decode_stream(&stream) {
21303 Ok(f) => f,
21304 Err(e) => {
21305 let msg = e.to_string();
21306 assert!(
21307 msg.contains("unsupported"),
21308 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
21309 failed outright, not a named refusal: {msg}"
21310 );
21311 eprintln!(
21312 " {NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
21313 REFUSED {msg}"
21314 );
21315 refusals.push(msg);
21316 continue;
21317 }
21318 };
21319 let hits = crate::decode::edge_both_cut_hits();
21320 let reference = if bit_depth == 10 {
21321 ffmpeg_decode_sequence_10bit(&stream, width, height, frames)
21322 } else {
21323 ffmpeg_decode_sequence(&stream, width, height, frames)
21324 };
21325 assert_eq!(
21326 decoded.len(),
21327 frames,
21328 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} decoded {} \
21329 frames, expected {frames}",
21330 decoded.len()
21331 );
21332 assert_eq!(
21333 reference.len(),
21334 frames,
21335 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} reference \
21336 frame count"
21337 );
21338 for (i, (ours, theirs)) in decoded.iter().zip(&reference).enumerate() {
21339 let nd =
21340 |a: &[u16], b: &[u16]| a.iter().zip(b).filter(|(x, y)| x != y).count();
21341 // Where a mismatch lands is the whole diagnosis
21342 // here (corner block vs elsewhere), so print the
21343 // luma bounding box before the assert kills the run.
21344 if nd(&ours.y, &theirs.y) > 0 {
21345 let (mut r0, mut c0, mut r1, mut c1) =
21346 (usize::MAX, usize::MAX, 0usize, 0usize);
21347 for row in 0..height {
21348 for col in 0..width {
21349 if ours.y[row * width + col] != theirs.y[row * width + col] {
21350 r0 = r0.min(row);
21351 c0 = c0.min(col);
21352 r1 = r1.max(row);
21353 c1 = c1.max(col);
21354 }
21355 }
21356 }
21357 eprintln!(
21358 " {NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
21359 frame {i} luma diff bbox rows {r0}..={r1} cols {c0}..={c1}"
21360 );
21361 }
21362 assert_eq!(
21363 (
21364 nd(&ours.y, &theirs.y),
21365 nd(&ours.u, &theirs.u),
21366 nd(&ours.v, &theirs.v)
21367 ),
21368 (0, 0, 0),
21369 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} frame \
21370 {i} differs from ffmpeg"
21371 );
21372 }
21373 // Every compared attempt must carry the case, so no
21374 // compared attempt is out of scope and
21375 // out_of_scope_mismatch is 0 by construction.
21376 assert!(
21377 hits[0] > 0,
21378 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} decoded \
21379 pixel-exact but no 16-level both-axes-cut block fired \
21380 (hits={hits:?}) -- the recipe no longer reaches the lifted arm"
21381 );
21382 for l in 0..4 {
21383 totals[l] += hits[l];
21384 }
21385 compared += 1;
21386 size_compared += 1;
21387 }
21388 }
21389 }
21390 assert!(
21391 size_compared > 0,
21392 "{NAME}: every {width}x{height} attempt refused -- that size proved nothing"
21393 );
21394 }
21395 assert!(
21396 totals[1] > 0 && totals[2] > 0,
21397 "{NAME}: no 32-level ({}) or 64-level ({}) both-axes-cut node fired -- 200x72 puts \
21398 both in that state, so the sweep stopped reaching them",
21399 totals[1],
21400 totals[2]
21401 );
21402 eprintln!(
21403 "{NAME}: {compared} attempts pixel-exact over {} sizes ({arm} arm), \
21404 out_of_scope_mismatch=0, both_cut hits [16,32,64,128]={totals:?}, {} named refusals",
21405 sizes.len(),
21406 refusals.len()
21407 );
21408 }
21409
21410 /// lane-tiny r4 GATE (was r1's `#[ignore]`d probe): every tiny key-frame
21411 /// size real aomenc will encode, decoded pixel-exact against ffmpeg.
21412 /// Tiny frames are where every edge/partial-superblock corner case is
21413 /// forced, and this sweep is what found both r3's filter-intra tx_type
21414 /// CDF row and r4's chroma-transform-size deblock defect -- so it
21415 /// hard-asserts now: a decode error, a refusal, or one differing sample
21416 /// at any size/seed fails. Only a genuinely absent oracle skips, and
21417 /// `EC_AV1_REQUIRE_AOMENC=1` turns that into a failure too.
21418 #[test]
21419 fn a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact() {
21420 if !have_ffmpeg() || !have_aomenc() {
21421 eprintln!("SKIP: no ffmpeg/aomenc");
21422 return;
21423 }
21424 // lane-oddh r2: the second half of this list is the odd-height /
21425 // odd-width ladder -- frame sizes whose last superblock row or column
21426 // is a partial 64 (72 = one full SB plus 8 rows, 136 = two plus 8),
21427 // which is where the frame-edge half-strip path r1 added is the only
21428 // way to code the edge. 192x136 is the inter-sized member.
21429 let sizes: &[(usize, usize)] = &[
21430 (8, 8),
21431 (16, 16),
21432 (32, 32),
21433 (16, 32),
21434 (32, 16),
21435 (64, 64),
21436 (48, 48),
21437 (24, 24),
21438 (64, 72),
21439 (72, 64),
21440 (64, 136),
21441 (136, 64),
21442 (192, 136),
21443 ];
21444 let mut total_exact = 0u32;
21445 for &(width, height) in sizes {
21446 let mut ok = 0u32;
21447 let mut bad = 0u32;
21448 let mut refused = 0u32;
21449 let n = 10u32;
21450 for attempt in 0..n {
21451 let seed = 42 + attempt;
21452 let source = format!(
21453 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
21454 sx = -0.6 + 0.005 * (attempt as f64),
21455 sy = -0.4 + 0.005 * (attempt as f64)
21456 );
21457 let y4m = Command::new("ffmpeg")
21458 .args([
21459 "-v", "error", "-f", "lavfi", "-i", &source, "-t", "0.04", "-pix_fmt",
21460 "yuv420p", "-f", "yuv4mpegpipe", "-",
21461 ])
21462 .stdin(Stdio::null())
21463 .stdout(Stdio::piped())
21464 .stderr(Stdio::piped())
21465 .output()
21466 .expect("ffmpeg failed to run");
21467 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
21468 let max_part = width.max(height).min(64).next_power_of_two();
21469 let min_part = width.min(height).next_power_of_two().max(8).min(max_part);
21470 let max_part_arg = format!("--max-partition-size={max_part}");
21471 let min_part_arg = format!("--min-partition-size={min_part}");
21472 let args: Vec<&str> = vec![
21473 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32",
21474 "--cpu-used=4", "--kf-max-dist=0", "--limit=1", "--threads=1",
21475 "--row-mt=0", "--enable-rect-partitions=0", "--enable-ab-partitions=0",
21476 "--enable-1to4-partitions=0",
21477 &max_part_arg, &min_part_arg,
21478 "--obu", "-o", "-", "-",
21479 ];
21480 let mut child = Command::new(aomenc_path())
21481 .args(&args)
21482 .stdin(Stdio::piped())
21483 .stdout(Stdio::piped())
21484 .stderr(Stdio::piped())
21485 .spawn()
21486 .expect("aomenc failed to start");
21487 child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("write y4m");
21488 let out = child.wait_with_output().expect("aomenc failed to run");
21489 assert!(out.status.success(), "aomenc refused: {}", String::from_utf8_lossy(&out.stderr));
21490 let stream = out.stdout;
21491 let frames = match decode_stream(&stream) {
21492 Err(e) => {
21493 // A NAMED refusal is the only non-exact outcome this
21494 // gate tolerates (8x8 still needs a rectangular
21495 // transform); anything else is a hard failure, and
21496 // the floor assert below keeps that from going
21497 // vacuous.
21498 let msg = e.to_string();
21499 assert!(
21500 msg.contains("unsupported"),
21501 "{width}x{height} seed {seed}: failed outright, not a named \
21502 refusal: {msg}"
21503 );
21504 eprintln!(" {width}x{height} seed {seed}: REFUSED {msg}");
21505 refused += 1;
21506 continue;
21507 }
21508 Ok(f) => f,
21509 };
21510 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
21511 if frames.len() == 1
21512 && frames[0].y == ffmpeg_frames[0].y
21513 && frames[0].u == ffmpeg_frames[0].u
21514 && frames[0].v == ffmpeg_frames[0].v
21515 {
21516 ok += 1;
21517 } else {
21518 bad += 1;
21519 let nd = |a: &[u16], b: &[u16]| a.iter().zip(b).filter(|(x, y)| x != y).count();
21520 let (ndy, ndu, ndv) = (
21521 nd(&frames[0].y, &ffmpeg_frames[0].y),
21522 nd(&frames[0].u, &ffmpeg_frames[0].u),
21523 nd(&frames[0].v, &ffmpeg_frames[0].v),
21524 );
21525 let mut first = None;
21526 for row in 0..height {
21527 for col in 0..width {
21528 let i = row * width + col;
21529 if frames[0].y[i] != ffmpeg_frames[0].y[i] {
21530 first = Some((row, col, frames[0].y[i], ffmpeg_frames[0].y[i]));
21531 break;
21532 }
21533 }
21534 if first.is_some() {
21535 break;
21536 }
21537 }
21538 let ndiff = frames[0]
21539 .y
21540 .iter()
21541 .zip(&ffmpeg_frames[0].y)
21542 .filter(|(a, b)| a != b)
21543 .count();
21544 eprintln!(
21545 " {width}x{height} seed {seed}: MISMATCH first_diff={first:?} \
21546 ndiff_luma={ndiff}/{} ndiff y/u/v={ndy}/{ndu}/{ndv}",
21547 width * height
21548 );
21549 }
21550 }
21551 assert_eq!(
21552 bad, 0,
21553 "{width}x{height}: {bad} of {n} seeds decoded to WRONG PIXELS ({ok} exact, \
21554 {refused} named refusals)"
21555 );
21556 eprintln!("{width}x{height}: {ok}/{n} pixel-exact, {refused} named refusals");
21557 total_exact += ok;
21558 }
21559 // Hit counter: the sweep proved nothing unless every size x seed
21560 // attempt really ran end to end (aomenc -> us -> ffmpeg compare).
21561 // Floor (hit counter): 12 of the 13 sizes must decode all 10 seeds
21562 // pixel-exact -- only 8x8 is allowed to refuse outright today. If a
21563 // future change makes sizes refuse instead of decode, this fails
21564 // rather than passing on refusals alone.
21565 assert!(
21566 total_exact >= 120,
21567 "tiny sweep only reached {total_exact} pixel-exact attempts (floor 70) -- \
21568 refusals cannot substitute for decodes"
21569 );
21570 eprintln!("tiny frame sweep: {total_exact} pixel-exact attempts");
21571 }
21572
21573 /// lane-tiny r1: re-decodes the known-failing 32x32 seed 45 fixture with
21574 /// `EC_AV1_TRACE` on to inspect what mode/tx this single-block frame
21575 /// picked. Diagnostic only, `

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