forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5c8eff8Tahinli2 months ago2949 commits

stream.rs21531 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 crate::census::frame_start(header, tile_bufs.iter().map(|t| t.len()).sum(), decode_idx);
1386 if header.segmentation.enabled {
1387 for segment in 0..MAX_SEGMENTS {
1388 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
1389 if header.segmentation.feature_enabled[segment][feature] {
1390 return Err(Error::unsupported(
1391 "AV1 decode_stream",
1392 "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)",
1393 ));
1394 }
1395 }
1396 }
1397 }
1398 // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
1399 // primary reference frame's slot, and is all-zero without one.
1400 decode::set_segmentation(
1401 header.segmentation,
1402 header.mi_rows as usize,
1403 header.mi_cols as usize,
1404 snap.prev_seg_map.as_deref(), fctx,
1405 );
1406 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
1407 // symbol (spec 7.16's upscaling is a pixel-domain post-process
1408 // libaom's `decodeframe.c` runs between CDEF and loop restoration,
1409 // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile
1410 // reads stay bit-exact in sync and `crate::superres::upscale_picture`
1411 // (below, after decode) makes its `Picture` the spec-correct
1412 // `upscaled_width` instead of silently staying at `frame_width`.
1413 // lane-superres r10: an INTER frame under `use_superres` no longer
1414 // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3)
1415 // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/
1416 // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes
1417 // at the downscaled `frame_width` and upscales its own output the
1418 // same way the key-frame branch above does (see the inter branch
1419 // below). The combinations `predict_scaled` does not cover
1420 // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8
1421 // leaf) still refuse by name, deep in `decode.rs`, rather than
1422 // silently mispredicting -- see `refusal_inventory.rs`.
1423 // Loop restoration carries per-restoration-unit symbols in the tile
1424 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
1425 // superblock walk) -- lane-lr r2 ported the reader
1426 // (`crate::restoration`), r3 moved this refusal check to AFTER the
1427 // tile decode call below (was here, before it, in r2 -- meaning
1428 // `read_lr` was NEVER actually reached through `decode_stream`, the
1429 // gap the r3 gate caught live: 40/40 attempts hit this refusal with
1430 // zero `read_lr_unit` hits). Checking post-decode instead proves the
1431 // superblock walk actually survived `read_lr` (no desync) before
1432 // refusing on the true remaining gap: decoded Wiener/SGR filters are
1433 // stored per unit but never applied to pixels.
1434 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
1435 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
1436 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
1437 // zero vector only under `GmType == IDENTITY` -- any other warp
1438 // model needs the full affine/translation MV derivation this
1439 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
1440 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
1441 // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
1442 // to every one of the 7 single-reference slots `decode_inter_block`
1443 // can now select.
1444 //
1445 // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal
1446 // exposed a real pixel mismatch --
1447 // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact
1448 // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20
1449 // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring
1450 // is not yet provably correct end to end; keeping the refusal
1451 // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and
1452 // root-caused rather than shipping a wrong decode.
1453 //
1454 // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not
1455 // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac
1456 // RANGE at the first divergent block (mi=(8,0), frame 1) matches
1457 // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides),
1458 // and this decoder's own `gm_get_motion_vector` for that block
1459 // (ROTZOOM, seed 43's own header) computes the spec-correct
1460 // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`,
1461 // which found and fixed a real `- 1` omission in `warp.rs` --
1462 // harmless for THIS block's rounding but a genuine spec bug fixed
1463 // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a
1464 // `global_warp_allowed` branch (`warp_types.global_warp_allowed =
1465 // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts
1466 // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8)
1467 // with the FULL per-pixel affine global-motion warp, independent
1468 // of `motion_mode` -- this decoder only ever builds a warp
1469 // prediction for local `WARPED_CAUSAL` motion mode and falls back
1470 // to plain translational MC with the block-centre mv for every
1471 // other GLOBALMV block, which is only a centre-point approximation
1472 // of the true per-pixel warp. That is the entire remaining gap.
1473 // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into
1474 // `crate::warp::global_warp_params` for every single-ref
1475 // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s
1476 // `global_warp_allowed` branch -- ROTZOOM is pin-verified
1477 // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already
1478 // worked (`gm_get_motion_vector`'s translation-only mv, no warp
1479 // needed). AFFINE is untested this round (no aomenc fixture in the
1480 // wedge gate reached a 6-parameter model) -- keep refusing it by
1481 // name rather than shipping an unverified decode.
1482 // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom
1483 // can never write a 6-parameter model -- its encoder-side search is
1484 // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`,
1485 // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) --
1486 // which is why four rounds of `--enable-global-motion=1` recipes
1487 // never reached the case. `scripts/build-aom-affine-oracle.sh` widens
1488 // exactly that search range in a side build, and
1489 // `a_real_affine_global_motion_stream_decodes_pixel_exact` below
1490 // decodes its output pixel-exact against ffmpeg with
1491 // `affine_gm_hits() > 0`, i.e. real blocks predicted through the
1492 // 6-parameter warp. Nothing in the decoder needed changing: the
1493 // header reader already reads params 4/5 with their own subexp refs
1494 // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s
1495 // shear-validity check + `warp_affine` are model-agnostic.
1496 // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two
1497 // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and
1498 // refused the shape by name rather than guess-fix it. r5 localized
1499 // the mismatch to an ordinary NEWMV/GOLDEN block, not the new
1500 // global-warp branch at all -- proving "two active slots" was a
1501 // correlated symptom, not the cause. r6 range-laddered that block
1502 // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after
1503 // mode info -- symbol consumption bit-exact) and found the real
1504 // defect in `mvstack.rs`'s single-reference predictor fallback:
1505 // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real
1506 // neighbour scan left short with this block's OWN global motion
1507 // vector for its ref (`gm_get_motion_vector`), not zero -- invisible
1508 // whenever the live ref's global motion is itself
1509 // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE
1510 // and the querying block's own stack comes up short (frame 14's
1511 // mi=(0,0), the very first block decoded, has no neighbours at
1512 // all). Fixed at the predictor fallback; the refusal above (single
1513 // untested shape: AFFINE on a single-ref frame) stays, but the
1514 // *multi-slot* refusal this comment used to guard is lifted -- the
1515 // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames
1516 // byte-exact with it gone.
1517 // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
1518 // `comp_mode` per block whenever this frame's own `reference_select`
1519 // header bit is set (spec 5.11.25), and refuse by name the blocks
1520 // that pick `COMPOUND_REFERENCE` -- two-reference motion
1521 // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
1522 // is wired at the block level too (forced NEAREST_NEARESTMV compound
1523 // of `skip_mode_frame`, plain average blend), so the old blanket
1524 // `skip_mode_present` refusal is gone.
1525 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
1526 // which tile's end-of-tile adapted CDFs become the frame's own.
1527 // lane-tiles r8: this comment used to claim a `!= 0` refusal existed
1528 // "further down" -- it did not (`decode.rs` reads
1529 // `tile_info.context_update_tile_id` generically at both the
1530 // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites,
1531 // never hardcoded to tile 0); stale documentation, not a real gap.
1532 // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact`
1533 // hard-asserts a live aomenc stream naming tile 1/2/3 decodes
1534 // pixel-exact, so the capability is now proven as well as described
1535 // correctly.
1536 //
1537 // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped,
1538 // not blanket. `decode_key_frame_tile_with_cdfs` and (r6)
1539 // `decode_inter_frame_tile_with_cdfs` both genuinely loop every
1540 // tile, `mvstack.rs`'s `MiGrid` is bounded per tile
1541 // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1`
1542 // origin receives real values at every call site (r6's
1543 // `set_tile_origin` sweep). r7 proved the two remaining
1544 // tile-*column* gaps closed (inter frames, >2 columns with loop
1545 // filtering on). r8 proved tile *rows* the same way: the per-tile
1546 // loop's row math (`tile_num / tile_info.cols`,
1547 // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly
1548 // symmetric with the column path already proven, and
1549 // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact`
1550 // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact.
1551 // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_
1552 // stream` below re-proves it through this entry point. Tile columns
1553 // and tile rows (any count, loop filter on) are no longer capped.
1554 // `Tile::offset` is relative to the buffer `parse_obu` was handed
1555 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
1556 // to `obu_offset`, not to `data` as a whole.
1557 let enable_filter_intra = seq.enable_filter_intra;
1558 let enable_dual_filter = seq.enable_dual_filter;
1559 let enable_edge_filter = seq.enable_edge_filter;
1560 // Inter frames' intra blocks read this through a thread-local that only
1561 // the key-frame tile path used to set; without this call a stream whose
1562 // inter frames are decoded on a thread that previously decoded a
1563 // different sequence would inherit that sequence's bit.
1564 crate::decode::set_enable_edge_filter(enable_edge_filter, fctx);
1565 // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the
1566 // key-frame and the inter tile path read the 128 partition root and
1567 // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and
1568 // libaom's quadrant visit order into the inter loop too). A frame at
1569 // most 64x64 decodes identically either way (its 128 root reads no
1570 // symbol -- neither half is in frame, so SPLIT is inferred), so the
1571 // flag is only armed for frames bigger than one 64x64 superblock.
1572 let use_sb128 = seq.use_sb128;
1573 let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);
1574 crate::decode::set_sb128(sb128_active, fctx);
1575 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
1576 // which every dequant/inverse-transform clamp reads -- set per frame,
1577 // not once per process, for the same cross-sequence-on-one-thread
1578 // reason as `set_enable_edge_filter` above. Defaults to 8 when no
1579 // sequence header has been seen yet, matching every existing fixture.
1580 let bit_depth = seq.bit_depth;
1581 // lane-bd12: the sequence-header parser accepts `twelve_bit`, but every
1582 // rounding shift below is written for 8/10-bit only -- `warp.rs`'s
1583 // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses
1584 // `round_0 + max(bd + FILTER_BITS - round_0 - 14, 0)` (5 at bd 12), the
1585 // MC `round_0`/`round_1` change at 12-bit (libaom convolve.h:83), the
1586 // Wiener rounding bits change, and neither CDEF nor film grain has a
1587 // 12-bit path. Refuse by name rather than decode silently wrong pixels.
1588 if bit_depth == 12 {
1589 return Err(Error::unsupported(
1590 "AV1 decode_stream",
1591 "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)",
1592 ));
1593 }
1594 // lane-dpm1: a LOSSLESS frame (`qindex == 0` with zero deltas, spec 5.9.12)
1595 // is a different tile syntax, and this decoder has none of it: libaom
1596 // forces TX_4X4 with the WALSH-HADAMARD transform over every block (so no
1597 // `tx_depth` symbol is coded at all), and `is_cfl_allowed` narrows to
1598 // `plane_bsize == BLOCK_4X4` instead of the 32x32 rule, which changes the
1599 // `uv_mode` ALPHABET. Measured on his own screen-capture row at libaom
1600 // `-crf 5` (base_q_idx 0): the very first block, mi(0,0) BLOCK_32X32,
1601 // reads `uv_mode` off the CfL alphabet where libaom reads the plain one
1602 // (ours 12 = UV_CFL_PRED, aomdec 1 = V_PRED) and the tile desyncs at
1603 // symbol four of the frame. Refuse by name rather than return a picture
1604 // that is silently wrong from luma sample 0 (class `refusal-hides-a-defect`
1605 // read the other way: a silent wrong decode is worse than a named gap).
1606 // lane-lossless: `CodedLossless` (spec 5.9.12) -- every segment at
1607 // `qindex == 0` with zero plane deltas. The tile reader then forces TX_4X4
1608 // with the Walsh-Hadamard transform on every plane, codes no `tx_type`
1609 // symbol and narrows `is_cfl_allowed` to `plane_bsize == BLOCK_4X4`
1610 // (libaom `read_tx_size`/`read_tx_type`/`is_cfl_allowed`). A frame whose
1611 // segments DISAGREE is still refused by name: every one of those rules is
1612 // per segment there, and no gate covers a mixed frame.
1613 let coded_lossless = header.lossless.iter().all(|&l| l);
1614 if header.lossless.iter().any(|&l| l) && !coded_lossless {
1615 return Err(Error::unsupported(
1616 "AV1 decode_stream",
1617 "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)",
1618 ));
1619 }
1620 // lane-lossless2: an INTER frame's chroma plane is now walked as 4x4
1621 // transform units too (`decode::read_inter_chroma_lossless`), so the
1622 // named refusal that stood here is gone -- the gate that replaced it is
1623 // `a_lossless_libaom_inter_frame_decodes_sample_exact`.
1624 crate::decode::set_lossless(coded_lossless, fctx);
1625 crate::decode::set_bit_depth(bit_depth, fctx);
1626 // spec 7.16: this frame's superres state, for the filter chain --
1627 // `decode.rs` upscales between CDEF and loop restoration and sizes
1628 // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
1629 // unscaled frame so a later frame never inherits it.
1630 crate::decode::set_superres(
1631 if header.use_superres { header.upscaled_width } else { 0 },
1632 u32::from(header.superres_denom), fctx,
1633 );
1634 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
1635 let enable_masked_compound = seq.enable_masked_compound;
1636 let enable_jnt_comp = seq.enable_jnt_comp;
1637 // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's
1638 // read site doc.
1639 let enable_interintra_compound = seq.enable_interintra_compound;
1640 let interp_fixed = match header.interpolation_filter {
1641 ec_av1_syntax::InterpolationFilter::Switchable => None,
1642 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
1643 };
1644 // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
1645 // from that reference slot's saved CDF state instead of the spec 8.4
1646 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
1647 // builds.
1648 let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
1649 None
1650 } else {
1651 Some(snap.primary_cdfs.clone().ok_or_else(|| {
1652 Error::unsupported(
1653 "AV1 decode_stream",
1654 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
1655 )
1656 })?)
1657 };
1658 let started_from = initial_cdfs.clone();
1659 // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.
1660 decode::set_coeff_trace_frame(decode_idx);
1661 // lane-t900 r9: one line per DECODE-order frame naming the header
1662 // fields a desync cliff is usually keyed on (frame type, base q,
1663 // primary_ref, the 7 ref slots, refresh mask, order hints).
1664 if std::env::var_os("EC_PROBE_HDR").is_some() {
1665 eprintln!(
1666 "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={:?}",
1667 header.frame_type,
1668 header.show_frame,
1669 header.show_existing_frame,
1670 header.quantization.base_q_idx,
1671 header.primary_ref_frame,
1672 header.ref_frame_idx,
1673 header.refresh_frame_flags,
1674 header.order_hint,
1675 header.tile_info.cols,
1676 header.tile_info.rows,
1677 header.tx_mode,
1678 header.interpolation_filter,
1679 header.reduced_tx_set,
1680 header.allow_warped_motion,
1681 header.is_motion_mode_switchable,
1682 header.use_ref_frame_mvs,
1683 header.skip_mode_present,
1684 header.cdef.bits,
1685 header.loop_restoration.frame_restoration_type,
1686 );
1687 }
1688
1689 let order_hint_bits = seq.order_hint_bits;
1690 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
1691 // of the picture sitting in each of its 7 single references' DPB
1692 // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
1693 // (a later frame projects from it) whether or not this frame itself
1694 // reads temporal candidates.
1695 let ref_order_hints = snap.ref_order_hints;
1696
1697 crate::timeline::bind(
1698 decode_idx,
1699 if header.frame_type == FrameType::Key {
1700 'K'
1701 } else if header.show_frame {
1702 'P'
1703 } else {
1704 'A'
1705 },
1706 header.show_frame,
1707 );
1708 crate::timeline::hdr_done();
1709 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
1710 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
1711 &tile_bufs,
1712 &header.tile_info,
1713 header.mi_cols,
1714 header.mi_rows,
1715 header.quantization.base_q_idx,
1716 crate::quant::QuantDeltas {
1717 y_dc: i32::from(header.quantization.delta_q_y_dc),
1718 u_dc: i32::from(header.quantization.delta_q_u_dc),
1719 u_ac: i32::from(header.quantization.delta_q_u_ac),
1720 v_dc: i32::from(header.quantization.delta_q_v_dc),
1721 v_ac: i32::from(header.quantization.delta_q_v_ac),
1722 },
1723 header.frame_width,
1724 header.frame_height,
1725 enable_filter_intra,
1726 enable_edge_filter,
1727 &header.cdef,
1728 &header.loop_filter,
1729 &header.loop_restoration,
1730 initial_cdfs,
1731 header.tx_mode == TxMode::Select,
1732 header.reduced_tx_set,
1733 header.allow_screen_content_tools,
1734 header.allow_intrabc,
1735 header.delta, fctx,
1736 )?;
1737 // A key frame codes no inter blocks -- its own saved motion
1738 // field has no cells set, matching libaom's own "intra frame
1739 // contributes nothing to a later projection" behaviour, but
1740 // still carries `order_hint`/`ref_order_hints` for the distance
1741 // arithmetic a later frame's projection needs.
1742 let motion_field = crate::motion_field::MotionField::new(
1743 header.mi_cols as usize,
1744 header.mi_rows as usize,
1745 header.order_hint,
1746 ref_order_hints,
1747 // `frame_type` for the DPB slot: a key (or intra-only) frame is
1748 // never a projection source, and never spends a `ref_stamp`.
1749 true,
1750 );
1751 (picture, end_cdfs, Some(motion_field))
1752 } else {
1753 let last_slot = header.ref_frame_idx[0] as usize;
1754 let _ = last_slot;
1755 if snap.refpix.dims(1).is_none() {
1756 return Err(Error::unsupported(
1757 "AV1 decode_stream",
1758 "an inter frame with no key frame before it",
1759 ));
1760 }
1761 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
1762 // (spec 7.8/7.20). Any of them having no picture yet is not a
1763 // stream error on its own: `decode_inter_block` only needs a
1764 // given slot when a block actually selects that reference, and
1765 // refuses by name there if the slot is still empty -- widened
1766 // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
1767 // one of the 7 single-reference slots.
1768 // lane-fimv r1: record the header state the fimv gate asserts on
1769 // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
1770 if header.force_integer_mv {
1771 decode::note_force_integer_mv_frame();
1772 }
1773 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1774 // this frame's header actually asks for temporal candidates --
1775 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
1776 // behaviour bit for bit when this is `None` (see its own doc).
1777 // lane-twostage: the stage-1 sink is handed the table a consumer
1778 // would have read out of the slot, not the raw end-of-tile one.
1779 let started_from_stage1 = started_from.clone();
1780 let stage1_adapter = stage1.map(|sink| {
1781 move |end_cdfs: Cdfs,
1782 motion_field: crate::motion_field::MotionField,
1783 width: usize,
1784 height: usize| {
1785 sink(
1786 stored_cdfs_for(header, end_cdfs, started_from_stage1.clone()),
1787 motion_field,
1788 width,
1789 height,
1790 )
1791 }
1792 });
1793 let tpl_field = &snap.tpl_field;
1794 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
1795 &tile_bufs,
1796 &header.tile_info,
1797 header.mi_cols,
1798 header.mi_rows,
1799 header.quantization.base_q_idx,
1800 crate::quant::QuantDeltas {
1801 y_dc: i32::from(header.quantization.delta_q_y_dc),
1802 u_dc: i32::from(header.quantization.delta_q_u_dc),
1803 u_ac: i32::from(header.quantization.delta_q_u_ac),
1804 v_dc: i32::from(header.quantization.delta_q_v_dc),
1805 v_ac: i32::from(header.quantization.delta_q_v_ac),
1806 },
1807 header.frame_width,
1808 header.frame_height,
1809 snap.refpix,
1810 &header.cdef,
1811 &header.loop_filter,
1812 &header.loop_restoration,
1813 initial_cdfs,
1814 header.allow_high_precision_mv,
1815 header.force_integer_mv,
1816 header.ref_frame_sign_bias,
1817 header.global_motion,
1818 interp_fixed,
1819 enable_dual_filter,
1820 order_hint_bits,
1821 header.order_hint,
1822 ref_order_hints,
1823 tpl_field.as_ref(),
1824 header.reference_select,
1825 enable_masked_compound,
1826 enable_jnt_comp,
1827 enable_interintra_compound,
1828 header.skip_mode_present,
1829 header.skip_mode_frame,
1830 header.reduced_tx_set,
1831 header.tx_mode == TxMode::Select,
1832 header.is_motion_mode_switchable,
1833 header.allow_warped_motion,
1834 header.allow_screen_content_tools,
1835 header.delta,
1836 enable_filter_intra,
1837 stage1_adapter
1838 .as_ref()
1839 .map(|f| f as &dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)),
1840 fctx,
1841 )?;
1842 (picture, end_cdfs, motion_field)
1843 };
1844 // lane-lr r4: the Wiener/self-guided pixel filters are wired
1845 // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
1846 // `uses_lr` frames now decode all the way to pixels.
1847 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
1848 // *initial* table into the slots it refreshes, not the adapted
1849 // end-of-tile one.
1850 let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from);
1851 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
1852 use std::io::Write;
1853 if let Ok(mut f) = std::fs::OpenOptions::new()
1854 .create(true)
1855 .append(true)
1856 .open(&path)
1857 {
1858 let _ = writeln!(f, "=== frame idx={} ===", shown_idx);
1859 let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
1860 let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
1861 let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
1862 let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
1863 let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
1864 let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
1865 let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
1866 let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
1867 }
1868 }
1869 // lane-comppin r3: decode-order (not display-order) dump of every
1870 // frame's own post-deblock buffer -- the pre-existing pixel diff
1871 // (`scratch_isolate_pinned_mismatch`) only ever compares *shown*
1872 // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a
1873 // later shown frame is otherwise invisible; diff this byte-for-byte
1874 // against `EC_AV1_POSTFILT_DUMP.fN` from the instrumented aomdec
1875 // build to isolate whether the defect is in a hidden frame's own
1876 // reconstruction or downstream of it.
1877 if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") {
1878 use std::io::Write;
1879 let idx = decode_idx;
1880 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
1881 // lane-hbd r4: debug dump narrows to u8 -- this diagnostic
1882 // predates 10-bit support and is an 8-bit-oracle comparison
1883 // only (aomdec's own dump is 8-bit here too).
1884 let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
1885 let _ = f.write_all(&narrow(&picture.y));
1886 let _ = f.write_all(&narrow(&picture.u));
1887 let _ = f.write_all(&narrow(&picture.v));
1888 }
1889 }
1890 // lane-hidden r1: the frame exactly as it is about to be stored into
1891 // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
1892 // order, hidden (`show_frame == 0`) alt-ref frames included, and
1893 // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
1894 // u8-narrowing diagnostic dumps above. Matches the instrumented
1895 // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
1896 // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
1897 // hidden frame's pixels comparable at all.
1898 if let Some(prefix) = final_dump {
1899 use std::io::Write;
1900 if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{decode_idx}")) {
1901 let mut buf = Vec::new();
1902 for plane in [&picture.y, &picture.u, &picture.v] {
1903 if bit_depth == 8 {
1904 buf.extend(plane.iter().map(|&s| s as u8));
1905 } else {
1906 for &s in plane {
1907 buf.extend_from_slice(&s.to_le_bytes());
1908 }
1909 }
1910 }
1911 let _ = f.write_all(&buf);
1912 }
1913 }
1914 Ok(FrameOutput {
1915 picture,
1916 stored_cdfs,
1917 motion_field,
1918 seg_map: decode::take_segment_ids(fctx),
1919 })
1920}
1921
1922/// lane-intra14 r1: INTRA-coded 1:4 strips decoded on the INTER block path
1923/// (64x16, 16x64, 32x8, 8x32) -- the counters a recipe sweep needs from
1924/// outside the crate.
1925pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) {
1926 (
1927 crate::decode::intra_rect4_strip_in_inter_hits(0),
1928 crate::decode::intra_rect4_strip_in_inter_hits(1),
1929 crate::decode::intra_rect4_strip_in_inter_hits(2),
1930 crate::decode::intra_rect4_strip_in_inter_hits(3),
1931 )
1932}
1933
1934#[cfg(test)]
1935pub(crate) mod tests {
1936 use super::*;
1937 use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
1938
1939 fn test_card(width: usize, height: usize) -> Pic {
1940 let mut picture = Pic::grey(width, height);
1941 for row in 0..height {
1942 for col in 0..width {
1943 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
1944 }
1945 }
1946 for row in 0..height / 2 {
1947 for col in 0..width / 2 {
1948 let i = row * width / 2 + col;
1949 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
1950 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
1951 }
1952 }
1953 picture
1954 }
1955
1956 fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic {
1957 let mut picture = Pic::grey(width, height);
1958 for y in 0..height {
1959 for x in 0..width {
1960 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
1961 let gradient = sx * 200.0 / width as f64;
1962 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
1963 }
1964 }
1965 for y in 0..height / 2 {
1966 for x in 0..width / 2 {
1967 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
1968 let i = y * width / 2 + x;
1969 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
1970 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
1971 }
1972 }
1973 picture
1974 }
1975
1976 /// A stream whose sequence header says `twelve_bit` is refused by name
1977 /// rather than decoded with the 8/10-bit rounding shifts (`warp.rs`'s
1978 /// hard `REDUCE_BITS_HORIZ = 3`, MC/Wiener round bits, ungated CDEF and
1979 /// film grain). Reachability, not a pixel claim: the header is written at
1980 /// `seq_profile = 2` so `twelve_bit` is actually coded, and the frame's
1981 /// tile payload is never reached.
1982 #[test]
1983 fn a_twelve_bit_sequence_header_is_refused_by_name() {
1984 let fctx = &crate::decode::FrameCtx::new();
1985 let picture = test_card(64, 64);
1986 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1987 let mut color = ec_av1_syntax::ColorConfig {
1988 bit_depth: 12,
1989 ..Default::default()
1990 };
1991 color.num_planes = 3;
1992 // Only seq_profile 2 codes the `twelve_bit` bit (spec 5.5.2).
1993 let (mut seq, header) =
1994 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
1995 seq.seq_profile = 2;
1996 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
1997 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
1998
1999 let err = decode_stream(&stream).unwrap_err().to_string();
2000 assert!(
2001 err.contains(
2002 "a bit depth of 12 (this decoder is gated at 8 and 10 only: \
2003 warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)"
2004 ),
2005 "expected the 12-bit refusal, got: {err}"
2006 );
2007 }
2008
2009 /// lane-t900 r25: the refusal "a frame OBU with no tile group" names a
2010 /// shape the parser cannot hand [`decode_stream`].
2011 ///
2012 /// `tiles` reaches that check from exactly two places -- `ObuKind::Frame`'s
2013 /// own vector and the `ObuKind::TileGroup` accumulation -- and both are
2014 /// filled by `ec_av1_syntax`'s `parse_tile_group`, whose only success path
2015 /// pushes one `Tile` per `tile_num` of the INCLUSIVE range
2016 /// `tg_start..=tg_end`. That range is never empty: the single-tile-group
2017 /// case takes `(0, num_tiles - 1)` saturating at 0, and the multi-group
2018 /// case rejects `end < start` as corrupt. So an `OBU_FRAME` either fails to
2019 /// parse or carries at least one tile, however short its payload is --
2020 /// including the empty payload the charter for this round asked to build,
2021 /// which parses into ONE zero-byte tile rather than none.
2022 ///
2023 /// Sweeping a real frame OBU's tile payload from empty upwards asserts both
2024 /// halves: every `Frame` OBU that parses has a tile, and `decode_stream`
2025 /// never reports this refusal for any of them.
2026 #[test]
2027 fn a_frame_obu_that_parses_always_carries_at_least_one_tile() {
2028 let fctx = &crate::decode::FrameCtx::new();
2029 const REFUSAL: &str = "a frame OBU with no tile group";
2030 let picture = test_card(64, 64);
2031 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2032 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2033 let mut frame_obus_parsed = 0;
2034 for len in 0..=encoded.tile.len().min(24) {
2035 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2036 stream.extend_from_slice(
2037 &crate::frame::frame_obu(&seq, &header, &encoded.tile[..len]).unwrap(),
2038 );
2039 let mut parser = Av1Parser::new();
2040 let mut pos = 0usize;
2041 while pos < stream.len() {
2042 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
2043 break;
2044 };
2045 pos += obu.total_size;
2046 if let ObuKind::Frame(_, tiles) = &obu.kind {
2047 frame_obus_parsed += 1;
2048 assert!(
2049 !tiles.is_empty(),
2050 "a {len}-byte tile payload parsed into a frame OBU with no tile group -- \
2051 the refusal {REFUSAL:?} is reachable after all"
2052 );
2053 }
2054 }
2055 if let Err(e) = decode_stream(&stream) {
2056 let e = e.to_string();
2057 assert!(
2058 !e.contains(REFUSAL),
2059 "a {len}-byte tile payload reached {REFUSAL:?}: {e}"
2060 );
2061 }
2062 }
2063 assert!(
2064 frame_obus_parsed >= 2,
2065 "the sweep parsed {frame_obus_parsed} frame OBUs -- it proves nothing about the \
2066 refusal's reachability"
2067 );
2068 }
2069
2070 /// lane-t900 r27, negative gate: a frame whose segmentation enables one of
2071 /// the three MODE-OVERRIDING features -- `SEG_LVL_REF_FRAME` (forces a
2072 /// block's reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both
2073 /// suppress symbols `decode_inter_block` reads unconditionally) -- is
2074 /// refused BY NAME and outputs no picture, rather than desyncing on the
2075 /// first block that would have obeyed the override.
2076 ///
2077 /// Written, not hand-built: `write_segmentation_params` (spec 5.9.14)
2078 /// codes `feature_enabled`/`feature_data` for every segment, so a real
2079 /// key frame carrying the flag is a two-line change to the header the
2080 /// encoder already produced. Swept over all three features and over the
2081 /// first, a middle and the last segment id.
2082 #[test]
2083 fn a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name() {
2084 let fctx = &crate::decode::FrameCtx::new();
2085 const REFUSAL: &str =
2086 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
2087 let picture = test_card(64, 64);
2088 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2089 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2090 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
2091 for segment in [0usize, 3, 7] {
2092 let mut header = key.clone();
2093 header.segmentation.enabled = true;
2094 header.segmentation.update_map = true;
2095 header.segmentation.update_data = true;
2096 header.segmentation.feature_enabled[segment][feature] = true;
2097 header.segmentation.feature_data[segment][feature] = 1;
2098 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2099 stream.extend_from_slice(
2100 &crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap(),
2101 );
2102 let mut shown = 0;
2103 let err = decode_stream_with(&stream, |_, _, _| {
2104 shown += 1;
2105 Ok(())
2106 })
2107 .unwrap_err()
2108 .to_string();
2109 assert!(
2110 err.contains(REFUSAL),
2111 "feature {feature} segment {segment}: expected {REFUSAL:?}, got: {err}"
2112 );
2113 assert_eq!(
2114 shown, 0,
2115 "feature {feature} segment {segment}: a refused frame produced a picture"
2116 );
2117 }
2118 }
2119 }
2120
2121 /// One census attempt: encode `frames` frames of `source` with real
2122 /// aomenc plus `extra` args, decode with THIS decoder, and return the
2123 /// stream's byte length with either the picture count or the refusal (any
2124 /// decode error) it produced. A census is about what the encoder emits,
2125 /// so a refusal is data here, not a failure.
2126 fn census_attempt(
2127 source: &str,
2128 width: usize,
2129 height: usize,
2130 frames: usize,
2131 extra: &[&str],
2132 ) -> (usize, std::result::Result<usize, String>) {
2133 let duration = format!("{}", frames as f64 / 25.0);
2134 let src = format!("{source}=size={width}x{height}:rate=25");
2135 let y4m = Command::new("ffmpeg")
2136 .args([
2137 "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt", "yuv420p",
2138 "-strict", "-1", "-f", "yuv4mpegpipe", "-",
2139 ])
2140 .stdin(Stdio::null())
2141 .stdout(Stdio::piped())
2142 .stderr(Stdio::piped())
2143 .output()
2144 .expect("ffmpeg failed to run");
2145 assert!(y4m.status.success(), "ffmpeg refused the {width}x{height} fixture");
2146 let limit = format!("--limit={frames}");
2147 let mut args: Vec<String> = [
2148 "--codec=av1",
2149 "--passes=1",
2150 "--end-usage=q",
2151 "--threads=1",
2152 "--row-mt=0",
2153 "--kf-max-dist=9999",
2154 "--lag-in-frames=0",
2155 ]
2156 .iter()
2157 .map(|s| (*s).to_owned())
2158 .collect();
2159 args.push(limit);
2160 args.extend(extra.iter().map(|s| (*s).to_owned()));
2161 args.extend(["--obu".to_owned(), "-o".to_owned(), "-".to_owned(), "-".to_owned()]);
2162 let mut child = Command::new(aomenc_path())
2163 .args(&args)
2164 .stdin(Stdio::piped())
2165 .stdout(Stdio::piped())
2166 .stderr(Stdio::piped())
2167 .spawn()
2168 .expect("aomenc failed to start");
2169 child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("write y4m");
2170 let out = child.wait_with_output().expect("aomenc failed to run");
2171 assert!(out.status.success(), "aomenc refused {args:?}: {}", String::from_utf8_lossy(&out.stderr));
2172 let stream = out.stdout;
2173 let result = match decode_stream(&stream) {
2174 Ok(pictures) => Ok(pictures.len()),
2175 Err(e) => Err(e.to_string()),
2176 };
2177 (stream.len(), result)
2178 }
2179
2180 /// lane-t900 r27 CENSUS behind the negative gate above: does a real
2181 /// aomenc ever ENABLE one of the three mode-overriding segmentation
2182 /// features? Measured over the recipes that turn segmentation on --
2183 /// `--aq-mode=1/2/3` (variance, complexity and cyclic-refresh AQ) and
2184 /// `--deltaq-mode=1` -- with the refusal as the instrument: if one of
2185 /// those features appeared, the decode would stop by name.
2186 #[test]
2187 fn a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature() {
2188 if !have_aomenc() {
2189 eprintln!("SKIP a_segmentation_census_over_real_aq_streams: no aomenc");
2190 return;
2191 }
2192 const REFUSAL: &str =
2193 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
2194 let recipes: [(&str, Vec<&str>); 6] = [
2195 ("baseline", vec!["--cpu-used=4", "--cq-level=40"]),
2196 ("aq-mode=1", vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=40"]),
2197 ("aq-mode=2", vec!["--cpu-used=4", "--aq-mode=2", "--cq-level=40"]),
2198 ("aq-mode=3", vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=40"]),
2199 ("aq-mode=3 cq10", vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=10"]),
2200 ("deltaq-mode=1", vec!["--cpu-used=4", "--deltaq-mode=1", "--cq-level=40"]),
2201 ];
2202 // Arrival, not intent (class knob-never-reached-the-tool): a recipe
2203 // whose stream is byte-for-byte the baseline's changed nothing, and a
2204 // census over such arms would be vacuous. Measured r27: only
2205 // `--aq-mode=3` (cyclic refresh) does -- aq-mode 1/2 and deltaq-mode=1
2206 // all reproduce the baseline's 7147 B at this recipe.
2207 let mut baseline_bytes = 0usize;
2208 let mut segment_symbols = 0usize;
2209 let mut refused = 0usize;
2210 let mut decoded = 0usize;
2211 for (name, extra) in &recipes {
2212 let before = crate::decode::segment_id_hits();
2213 let (bytes, result) = census_attempt("mandelbrot", 192, 128, 8, extra);
2214 match result {
2215 Ok(pictures) => {
2216 decoded += 1;
2217 let symbols = crate::decode::segment_id_hits() - before;
2218 segment_symbols += symbols;
2219 if *name == "baseline" {
2220 baseline_bytes = bytes;
2221 }
2222 eprintln!(
2223 "SEGCENSUS {name}: {bytes} B{}, {pictures} pictures, segment_id symbols {symbols}",
2224 if bytes == baseline_bytes && *name != "baseline" {
2225 " (== baseline: the flag changed nothing)"
2226 } else {
2227 ""
2228 }
2229 );
2230 }
2231 Err(e) => {
2232 eprintln!("SEGCENSUS {name}: {bytes} B, refused: {e}");
2233 assert!(
2234 !e.contains(REFUSAL),
2235 "{name}: a real aomenc stream DOES enable a mode-overriding \
2236 segmentation feature -- the refusal is a capability gap, not a \
2237 claim about the encoder: {e}"
2238 );
2239 refused += 1;
2240 }
2241 }
2242 }
2243 eprintln!(
2244 "SEGCENSUS: {} recipes, {decoded} decoded, {refused} refused for other reasons",
2245 recipes.len()
2246 );
2247 assert_eq!(decoded, recipes.len(), "every recipe must decode; {refused} refused");
2248 assert!(
2249 segment_symbols > 0,
2250 "no recipe coded a single segment_id symbol -- segmentation never arrived, so \
2251 this census measures nothing about the three mode-overriding features"
2252 );
2253 }
2254
2255 /// lane-t900 r27, WITNESS half of the proof for "an OBMC neighbour whose
2256 /// switchable interp filter was never recorded" (the structural half is
2257 /// `decode::tests::every_inter_record_publishes_an_obmc_readable_filter`,
2258 /// which shows no INTER cell is ever stamped with the `[3, 3]`
2259 /// sentinel): real OBMC streams whose frames use a SWITCHABLE (and dual)
2260 /// interp filter decode with the refusal firing 0 times while OBMC blends
2261 /// really read the neighbour band -- a decode that never read one would
2262 /// pass just as well and prove nothing (class gate-blind-to-feature).
2263 #[test]
2264 fn a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour() {
2265 if !have_aomenc() {
2266 eprintln!("SKIP a_real_obmc_stream_reads_a_recorded_switchable_filter: no aomenc");
2267 return;
2268 }
2269 // `--cpu-used=0` is load-bearing: at speed 4 aomenc settles on a
2270 // FRAME-level fixed interp filter, every neighbour then legitimately
2271 // carries the sentinel, and the band is never read at all (measured
2272 // r27: 0 reads over two speed-4 streams).
2273 let base = vec![
2274 "--cpu-used=0",
2275 "--enable-obmc=1",
2276 "--enable-dual-filter=1",
2277 "--min-partition-size=8",
2278 "--max-partition-size=16",
2279 "--enable-palette=0",
2280 "--enable-intrabc=0",
2281 ];
2282 let recipes: [(&str, usize, usize, Vec<&str>); 2] = [
2283 ("obmc dual cq40", 192, 128, [vec!["--cq-level=40"], base.clone()].concat()),
2284 ("obmc dual cq20", 192, 128, [vec!["--cq-level=20"], base.clone()].concat()),
2285 ];
2286 let mut reads = 0usize;
2287 let mut decoded = 0usize;
2288 for (name, w, h, extra) in &recipes {
2289 let before = crate::decode::obmc_filter_band_reads();
2290 let obmc_before = crate::decode::obmc_hits();
2291 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 8, extra);
2292 match result {
2293 Ok(pictures) => {
2294 decoded += 1;
2295 let got = crate::decode::obmc_filter_band_reads() - before;
2296 reads += got;
2297 eprintln!(
2298 "OBMCFILT {name}: {bytes} B, {pictures} pictures, {got} band reads, \
2299 {} OBMC blocks",
2300 crate::decode::obmc_hits() - obmc_before
2301 );
2302 }
2303 Err(e) => {
2304 assert!(
2305 !e.contains("an OBMC neighbour whose switchable interp filter was never recorded"),
2306 "{name}: a real OBMC stream reached the unrecorded-filter refusal -- \
2307 a publication site is missing: {e}"
2308 );
2309 eprintln!("OBMCFILT {name}: {bytes} B, refused for another reason: {e}");
2310 }
2311 }
2312 }
2313 assert!(decoded > 0, "no OBMC recipe decoded -- the witness is vacuous");
2314 assert!(
2315 reads > 0,
2316 "every OBMC blend took the fixed-filter path: the band was never read, so this \
2317 proves nothing about the refusal"
2318 );
2319 }
2320
2321 /// lane-t900 r27 CENSUS for the three SUPERRES refusals -- "warp
2322 /// prediction with a scaled reference", "a sub-8x8 inter block under a
2323 /// scaled reference" and "an 8x8 partition leaf under a scaled reference".
2324 /// Six real `--superres-mode` encodes (fixed denominators and the auto
2325 /// mode, warped motion and OBMC on), decoded by this decoder: the table it
2326 /// prints is which of the three a real encoder actually reaches.
2327 ///
2328 /// Every one of them is a REAL capability gap (unlike the enumerated
2329 /// refusals elsewhere in the inventory), so this gate asserts the measured
2330 /// shape rather than "no refusal": at least one recipe must decode (else
2331 /// the census says nothing), and any refusal must be one of the three
2332 /// named superres ones -- a fourth string would be a new gap this round
2333 /// did not measure.
2334 #[test]
2335 fn a_superres_census_over_six_real_streams_records_which_scaled_refusals_fire() {
2336 if !have_aomenc() {
2337 eprintln!("SKIP a_superres_census_over_six_real_streams: no aomenc");
2338 return;
2339 }
2340 const WARP: &str = "warp prediction with a scaled reference";
2341 const SUB8: &str = "a sub-8x8 inter block under a scaled reference";
2342 const LEAF8: &str = "an 8x8 partition leaf under a scaled reference";
2343 let common = [
2344 "--enable-warped-motion=1",
2345 "--enable-obmc=1",
2346 "--enable-palette=0",
2347 "--enable-intrabc=0",
2348 ];
2349 let recipes: [(&str, usize, usize, Vec<&str>); 6] = [
2350 ("denom12 320x180 cq32", 320, 180, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=12", "--cq-level=32"]),
2351 ("denom12 320x180 cq50", 320, 180, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=12", "--cq-level=50"]),
2352 ("denom16 320x180 cq32", 320, 180, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=16", "--cq-level=32"]),
2353 ("denom10 192x128 cq32", 192, 128, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=10", "--cq-level=32"]),
2354 ("auto 320x180 cq50", 320, 180, vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"]),
2355 ("auto 192x128 cq50", 192, 128, vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"]),
2356 ];
2357 let (mut decoded, mut warp, mut sub8, mut leaf8) = (0, 0, 0, 0);
2358 // lane-t900 r36 (class [[gate-blind-to-feature]]): unknown refusal
2359 // strings used to `other += 1` and panic on the spot, so the census
2360 // summary below -- the whole point of the gate -- never printed when
2361 // one fired. They are collected instead, reported in the summary, and
2362 // asserted after it.
2363 let mut other: Vec<String> = Vec::new();
2364 for (name, w, h, extra) in &recipes {
2365 let mut args = extra.clone();
2366 args.extend_from_slice(&common);
2367 let before = crate::mc::predict_scaled_hits();
2368 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 10, &args);
2369 match result {
2370 Ok(pictures) => {
2371 decoded += 1;
2372 eprintln!(
2373 "SUPERRES {name}: {bytes} B, {pictures} pictures, scaled MC blocks {}",
2374 crate::mc::predict_scaled_hits() - before
2375 );
2376 }
2377 Err(e) => {
2378 eprintln!("SUPERRES {name}: {bytes} B, refused: {e}");
2379 if e.contains(WARP) {
2380 warp += 1;
2381 } else if e.contains(SUB8) {
2382 sub8 += 1;
2383 } else if e.contains(LEAF8) {
2384 leaf8 += 1;
2385 } else {
2386 other.push(format!("{name}: {e}"));
2387 }
2388 }
2389 }
2390 }
2391 eprintln!(
2392 "SUPERRES CENSUS: 6 streams, {decoded} decoded, warp {warp}x, sub8 {sub8}x, leaf8 {leaf8}x, other {}x",
2393 other.len()
2394 );
2395 assert!(
2396 other.is_empty(),
2397 "{} superres stream(s) stopped on a string this census does not know: {other:?}",
2398 other.len()
2399 );
2400 // Measured r27: the four FIXED-denominator recipes all stop at the
2401 // 8x8-leaf refusal, and the two `--superres-mode=3` (auto) streams
2402 // decode with ZERO scaled MC blocks -- auto picked denominator 8, so
2403 // those two arms carry no scaling at all and prove nothing. The warp
2404 // and sub-8x8 refusals never fire because the 8x8-leaf one sits in
2405 // front of them: whichever partition path a scaled frame takes, the
2406 // leaf guard is reached first. Lifting the leaf gap is what makes the
2407 // other two measurable, so this gate pins the ORDER, not just a count.
2408 assert!(decoded > 0, "no superres recipe decoded -- the census is vacuous");
2409 // lane-t900 r28: all three scaled refusals are LIFTED, so the census
2410 // now pins the opposite shape -- every fixed-denominator recipe must
2411 // DECODE, and none of the three strings may come back.
2412 assert_eq!(
2413 (warp, sub8, leaf8),
2414 (0, 0, 0),
2415 "a scaled-reference refusal came back (warp {warp}, sub8 {sub8}, leaf8 {leaf8})"
2416 );
2417 assert!(decoded > 0, "no superres recipe decoded -- the census is vacuous");
2418 }
2419
2420 /// lane-t900 r25, negative gate: a `show_existing_frame` header naming a
2421 /// slot no frame has refreshed is refused BY NAME, and outputs no picture.
2422 ///
2423 /// The OBU is hand-built because [`crate::frame::write_frame_header`]
2424 /// refuses to write one (it writes shown key and inter frames only): spec
2425 /// 5.9.2's whole header for this case is `show_existing_frame` (1) plus
2426 /// `frame_to_show_map_idx` (3), the sequence carrying neither a decoder
2427 /// model nor frame ids.
2428 ///
2429 /// Deviation from the round's charter, which asked for a key frame first
2430 /// with the named slot's `refresh_frame_flags` bit clear: a SHOWN key frame
2431 /// refreshes every slot (spec 5.9.2 forces `refresh_frame_flags` to
2432 /// `all_frames` and does not code it, which is also what
2433 /// `write_frame_header` does), so the only reachable empty-slot stream is
2434 /// one where no frame has refreshed that slot yet. The stream below is a
2435 /// valid sequence header followed by the header OBU, and every one of the
2436 /// eight slots is tried.
2437 #[test]
2438 fn a_show_existing_frame_header_naming_an_empty_slot_is_refused_by_name() {
2439 const REFUSAL: &str = "a show_existing_frame header naming an empty reference slot";
2440 let (seq, _) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2441 for slot in 0..NUM_REF_FRAMES as u32 {
2442 let mut w = ec_core::BitWriter::new();
2443 w.write_bit(true); // show_existing_frame
2444 w.write_bits(slot, 3); // frame_to_show_map_idx
2445 crate::bits::write_byte_alignment(&mut w);
2446 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2447 stream.extend_from_slice(&crate::obu::wrap_obu(
2448 &ec_av1_syntax::obu::ObuHeader {
2449 obu_type: ec_av1_syntax::obu::ObuType::FrameHeader,
2450 extension_flag: false,
2451 has_size_field: true,
2452 temporal_id: 0,
2453 spatial_id: 0,
2454 },
2455 &w.into_bytes(),
2456 ));
2457
2458 let mut shown = 0;
2459 let err = decode_stream_with(&stream, |_, _, _| {
2460 shown += 1;
2461 Ok(())
2462 })
2463 .unwrap_err()
2464 .to_string();
2465 assert!(
2466 err.contains(REFUSAL),
2467 "slot {slot}: expected {REFUSAL:?}, got: {err}"
2468 );
2469 assert_eq!(shown, 0, "slot {slot}: an empty slot was output as a picture");
2470 }
2471 }
2472
2473 /// lane-t900 r25, negative gate: an inter frame whose `ref_frame_idx[0]`
2474 /// slot holds no picture -- a stream that opens on an inter frame -- is
2475 /// refused BY NAME rather than predicting from nothing.
2476 ///
2477 /// Deviation from the round's charter, which asked for a real aomenc
2478 /// two-frame stream with the key frame's OBUs stripped: this crate's own
2479 /// `write_frame_header` writes a shown INTER frame (short reference
2480 /// signalling and non-identity global motion are the parts it refuses), so
2481 /// the fixture is built from the writers, needs neither ffmpeg nor aomenc,
2482 /// and is byte-identical on every run. The tile payload is a real key
2483 /// frame's; the refusal fires on the header's reference lookup, before any
2484 /// tile is decoded.
2485 #[test]
2486 fn an_inter_frame_opening_a_stream_is_refused_by_name() {
2487 let fctx = &crate::decode::FrameCtx::new();
2488 const REFUSAL: &str = "an inter frame with no key frame before it";
2489 let picture = test_card(64, 64);
2490 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2491 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2492 let inter = FrameHeader {
2493 frame_type: FrameType::Inter,
2494 frame_is_intra: false,
2495 // Keeps `primary_ref_frame`, `frame_size_with_refs` and
2496 // `use_ref_frame_mvs` out of the written header (spec 5.9.2).
2497 error_resilient_mode: true,
2498 primary_ref_frame: PRIMARY_REF_NONE,
2499 refresh_frame_flags: 0x02,
2500 order_hint: 1,
2501 ..key
2502 };
2503 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2504 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
2505
2506 let mut shown = 0;
2507 let err = decode_stream_with(&stream, |_, _, _| {
2508 shown += 1;
2509 Ok(())
2510 })
2511 .unwrap_err()
2512 .to_string();
2513 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
2514 assert_eq!(shown, 0, "an inter frame with no reference produced a picture");
2515 }
2516
2517 /// lane-t900 r26, negative gate: an inter frame whose own coded size is
2518 /// SHORTER than the reference it predicts from is refused BY NAME, and
2519 /// outputs no picture beyond the key frame that preceded it.
2520 ///
2521 /// The height mismatch is the one size difference this decoder cannot
2522 /// absorb: `mc::predict_scaled` scales horizontally (a `use_superres`
2523 /// reference), and nothing on this path scales vertically. The fixture is
2524 /// written, not hand-built: a shown key frame at 64x64 (which refreshes
2525 /// every slot), then a shown inter frame carrying
2526 /// `frame_size_override_flag` with `error_resilient_mode` set -- the one
2527 /// combination [`crate::frame::write_frame_header`] writes, since
2528 /// `frame_size_with_refs` (spec 5.9.7) is only read when error resilience
2529 /// is OFF. The inter frame's tile payload is the key frame's; the refusal
2530 /// fires on the reference's dimensions before a tile symbol is read.
2531 #[test]
2532 fn an_inter_frame_shorter_than_its_reference_is_refused_by_name() {
2533 let fctx = &crate::decode::FrameCtx::new();
2534 const REFUSAL: &str =
2535 "a reference picture whose height does not match this frame's own true size";
2536 let picture = test_card(64, 64);
2537 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2538 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2539 let inter = FrameHeader {
2540 frame_type: FrameType::Inter,
2541 frame_is_intra: false,
2542 error_resilient_mode: true,
2543 primary_ref_frame: PRIMARY_REF_NONE,
2544 refresh_frame_flags: 0x02,
2545 order_hint: 1,
2546 frame_size_override_flag: true,
2547 frame_height: 32,
2548 render_height: 32,
2549 ..key.clone()
2550 };
2551 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2552 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &key, &encoded.tile).unwrap());
2553 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
2554
2555 let mut shown = 0;
2556 let err = decode_stream_with(&stream, |_, _, _| {
2557 shown += 1;
2558 Ok(())
2559 })
2560 .unwrap_err()
2561 .to_string();
2562 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
2563 assert_eq!(shown, 1, "expected the key frame alone, got {shown} pictures");
2564 }
2565
2566 /// lane-t900 r26, negative gate: an inter frame naming a
2567 /// `primary_ref_frame` whose reference slot has never been refreshed is
2568 /// refused BY NAME rather than decoded from the spec 8.4 default tables.
2569 ///
2570 /// Enumeration first, because the refusal's premise is an invariant: the
2571 /// picture slots and the CDF slots are written by exactly two loops in
2572 /// [`decode_stream`] (the `show_existing_frame` arm's copy and the
2573 /// end-of-frame store), and both walk the SAME `refresh_frame_flags` mask
2574 /// writing `ref_slots[i]` and `cdf_slots[i]` together -- so no slot can
2575 /// hold a picture without CDFs, and the reachable case is a slot nothing
2576 /// has refreshed at all. That is what this builds: a stream that OPENS on
2577 /// a non-error-resilient inter frame (the only header shape that codes
2578 /// `primary_ref_frame` at all, spec 5.9.2), tried at all eight slots.
2579 ///
2580 /// This refusal, not "an inter frame with no key frame before it", is the
2581 /// one such a stream reaches: the CDF load happens in the header path,
2582 /// before the reference pictures are looked up.
2583 #[test]
2584 fn an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name() {
2585 let fctx = &crate::decode::FrameCtx::new();
2586 const REFUSAL: &str =
2587 "a frame naming primary_ref_frame at a reference slot with no saved CDF state";
2588 // The invariant above, read off the source: every line that stores a
2589 // picture into a slot sits in a block that stores that slot's CDFs too.
2590 let src = include_str!("stream.rs");
2591 let stores: Vec<usize> = src
2592 .lines()
2593 .enumerate()
2594 .filter(|(_, l)| l.trim().starts_with("ref_slots[i] = "))
2595 .map(|(i, _)| i)
2596 .collect();
2597 assert_eq!(
2598 stores.len(),
2599 2,
2600 "the picture slots gained a writer -- check it stores cdf_slots too"
2601 );
2602 let lines: Vec<&str> = src.lines().collect();
2603 for &i in &stores {
2604 let window = lines[i.saturating_sub(6)..(i + 6).min(lines.len())].join("\n");
2605 assert!(
2606 window.contains("cdf_slots[i] = "),
2607 "line {} stores a reference picture with no cdf_slots store beside it: a slot \
2608 can then hold a picture with no saved CDF state",
2609 i + 1
2610 );
2611 }
2612
2613 let picture = test_card(64, 64);
2614 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2615 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2616 for slot in 0..NUM_REF_FRAMES as u8 {
2617 let inter = FrameHeader {
2618 frame_type: FrameType::Inter,
2619 frame_is_intra: false,
2620 // `primary_ref_frame` is coded only when error resilience is
2621 // off (spec 5.9.2); `frame_size_override_flag` stays clear so
2622 // the header writes a plain `frame_size()`.
2623 error_resilient_mode: false,
2624 primary_ref_frame: 0,
2625 ref_frame_idx: [slot; ec_av1_syntax::REFS_PER_FRAME],
2626 refresh_frame_flags: 0x02,
2627 order_hint: 1,
2628 ..key.clone()
2629 };
2630 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2631 stream
2632 .extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
2633
2634 let mut shown = 0;
2635 let err = decode_stream_with(&stream, |_, _, _| {
2636 shown += 1;
2637 Ok(())
2638 })
2639 .unwrap_err()
2640 .to_string();
2641 assert!(err.contains(REFUSAL), "slot {slot}: expected {REFUSAL:?}, got: {err}");
2642 assert_eq!(shown, 0, "slot {slot}: a frame with no CDF state produced a picture");
2643 }
2644 }
2645
2646 /// lane-t900 r26, enumeration: no frame header a stream can carry derives
2647 /// an empty mode-info grid, so "a frame with no mode-info grid" names a
2648 /// case outside the coded domain.
2649 ///
2650 /// `compute_image_size` (spec 5.9.9) is `mi_cols = 2 * ((frame_width + 7)
2651 /// >> 3)`, which is 0 only for `frame_width == 0`, and a frame width is
2652 /// never 0 on any of the three paths that set one:
2653 ///
2654 /// * `frame_size()` (5.9.5) reads `frame_width_minus_1` and adds one, or
2655 /// takes the sequence's `max_frame_width` (itself `+ 1`-coded);
2656 /// * `superres_params()` (5.9.8) divides by a denominator of 9..=16 with
2657 /// rounding, whose minimum over the whole 16-bit upscaled-width domain
2658 /// is enumerated below and is 1, not 0;
2659 /// * `show_existing_frame` and `frame_size_with_refs()` copy a slot's own
2660 /// dimensions, which came from one of the above.
2661 ///
2662 /// The sweep drives the REAL header reader (write a header, parse it back)
2663 /// over every width and every height a 16-bit `frame_size()` can code,
2664 /// per axis -- the derivation is independent per axis -- rather than
2665 /// re-deriving the formula here.
2666 #[test]
2667 fn every_frame_size_a_header_can_code_has_a_mode_info_grid() {
2668 let mut sizes: Vec<u32> = (1..=1024).collect();
2669 sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]);
2670 // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can
2671 // only appear at the SMALL end -- which is why a size this crate's
2672 // tile-info writer cannot express (its tile log2 range runs out well
2673 // before 65536) is skipped rather than worked around, while every
2674 // size up to 1024 must be covered.
2675 let mut skipped: Vec<u32> = Vec::new();
2676 for n in sizes {
2677 for (w, h) in [(n, 16), (16, n)] {
2678 let Ok((seq, header)) =
2679 crate::encode::key_frame_headers(w as usize, h as usize, 100)
2680 else {
2681 skipped.push(n);
2682 continue;
2683 };
2684 let Ok(stream) = crate::frame::frame_obu(&seq, &header, &[]) else {
2685 skipped.push(n);
2686 continue;
2687 };
2688 let mut parser = Av1Parser::new();
2689 parser.parse_obu(&crate::sequence::sequence_header_obu(&seq).unwrap()).unwrap();
2690 let obu = parser.parse_obu(&stream).unwrap();
2691 let ObuKind::Frame(parsed, _) = &obu.kind else {
2692 panic!("{w}x{h}: the written frame OBU did not parse as one");
2693 };
2694 assert!(
2695 parsed.mi_cols >= 2 && parsed.mi_rows >= 2,
2696 "{w}x{h} parsed to a {}x{} mode-info grid",
2697 parsed.mi_cols,
2698 parsed.mi_rows
2699 );
2700 }
2701 }
2702 assert!(
2703 skipped.iter().all(|&n| n > 1024),
2704 "the writer could not express these small frame sizes, so the small end of the \
2705 sweep is incomplete: {skipped:?}"
2706 );
2707 // The superres arm, which no writer here can express: spec 5.9.8's
2708 // `(upscaled_width * 8 + denom / 2) / denom` over its whole domain.
2709 for denom in 9u32..=16 {
2710 for upscaled in [1u32, 2, 3, 7, 8, 9, 255, 4096, 65535, 65536] {
2711 let width = (upscaled * 8 + denom / 2) / denom;
2712 assert!(
2713 width >= 1,
2714 "superres denom {denom} maps an upscaled width of {upscaled} to {width}, \
2715 which would derive an empty mode-info grid"
2716 );
2717 }
2718 }
2719 }
2720
2721 /// lane-interedge r1: one attempt of the inter frame-edge half-strip gate --
2722 /// encode `width x height` with real aomenc (rect partitions ON, every other
2723 /// lane's open tool pinned off), decode it, and return
2724 /// `(inter_edge_strip hits, frames whose LUMA differs, frames whose CHROMA
2725 /// differs)` against ffmpeg. A refusal or a decode error is a hard failure:
2726 /// this recipe reached every size without one (measured r1).
2727 fn inter_edge_strip_attempt(
2728 name: &str,
2729 width: usize,
2730 height: usize,
2731 bit_depth: u32,
2732 cq: u32,
2733 frames: usize,
2734 ) -> ([usize; 6], usize, usize) {
2735 let duration = format!("{}", frames as f64 / 25.0);
2736 let source = format!("mandelbrot=size={width}x{height}:rate=25");
2737 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
2738 let y4m = Command::new("ffmpeg")
2739 .args([
2740 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration, "-pix_fmt",
2741 pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
2742 ])
2743 .stdin(Stdio::null())
2744 .stdout(Stdio::piped())
2745 .stderr(Stdio::piped())
2746 .output()
2747 .expect("ffmpeg failed to run");
2748 assert!(
2749 y4m.status.success(),
2750 "{name}: ffmpeg refused the {width}x{height} {bit_depth}-bit fixture: {}",
2751 String::from_utf8_lossy(&y4m.stderr)
2752 );
2753 let depth_arg = format!("--bit-depth={bit_depth}");
2754 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
2755 let cq_arg = format!("--cq-level={cq}");
2756 let limit_arg = format!("--limit={frames}");
2757 let mut child = Command::new(aomenc_path())
2758 .args([
2759 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg,
2760 // cpu-used >= 1 keeps libaom on 64x64 superblocks at these
2761 // sizes (`av1_select_sb_size`).
2762 "--cpu-used=4", "--threads=1", "--row-mt=0", "--kf-max-dist=9999",
2763 &limit_arg,
2764 // decode order == display order, so the compare below covers
2765 // every frame the stream carries (class gate-blind-to-hidden-frames).
2766 "--lag-in-frames=0", &depth_arg, &input_depth_arg,
2767 // Rect partitions stay ON: the frame-edge strip is a FORCED
2768 // (gathered) HORZ/VERT, but with rect coding off the encoder
2769 // answers that gathered symbol SPLIT every time and no edge
2770 // strip ever fires (lane-oddh r2's finding, re-measured r1).
2771 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
2772 "--enable-1to4-partitions=0", "--min-partition-size=8",
2773 "--max-partition-size=64",
2774 // Other lanes' open gaps this recipe must not trip.
2775 "--enable-palette=0", "--enable-intrabc=0", "--enable-warped-motion=0",
2776 "--enable-obmc=0", "--enable-masked-comp=0", "--enable-interintra-comp=0",
2777 "--enable-onesided-comp=0", "--enable-interintra-wedge=0",
2778 "--enable-smooth-interintra=0", "--enable-ref-frame-mvs=0",
2779 "--enable-angle-delta=0", "--enable-cfl-intra=0",
2780 "--enable-directional-intra=0", "--enable-smooth-intra=0",
2781 "--enable-paeth-intra=0", "--enable-filter-intra=0",
2782 "--enable-tx-size-search=0",
2783 "--obu", "-o", "-", "-",
2784 ])
2785 .stdin(Stdio::piped())
2786 .stdout(Stdio::piped())
2787 .stderr(Stdio::piped())
2788 .spawn()
2789 .expect("aomenc failed to start");
2790 child
2791 .stdin
2792 .take()
2793 .expect("aomenc stdin")
2794 .write_all(&y4m.stdout)
2795 .expect("write y4m");
2796 let out = child.wait_with_output().expect("aomenc failed to run");
2797 assert!(
2798 out.status.success(),
2799 "aomenc refused: {}",
2800 String::from_utf8_lossy(&out.stderr)
2801 );
2802 let stream = out.stdout;
2803
2804 // Reset, never a delta: a refused attempt's hits must not leak into the
2805 // next one (class counter-from-refused-stream).
2806 crate::decode::reset_inter_edge_strip_hits();
2807 let decoded = decode_stream(&stream).unwrap_or_else(|e| {
2808 panic!("{name}: {width}x{height} {bit_depth}-bit cq {cq} did not decode: {e}")
2809 });
2810 let hits = crate::decode::inter_edge_strip_hits();
2811 let reference = if bit_depth == 10 {
2812 ffmpeg_decode_sequence_10bit(&stream, width, height, frames)
2813 } else {
2814 ffmpeg_decode_sequence(&stream, width, height, frames)
2815 };
2816 assert_eq!(
2817 decoded.len(),
2818 reference.len(),
2819 "{name}: {width}x{height} {bit_depth}-bit cq {cq} frame count"
2820 );
2821 assert!(
2822 decoded.len() >= frames,
2823 "{name}: {width}x{height} {bit_depth}-bit cq {cq} decoded only {} frames",
2824 decoded.len()
2825 );
2826 let (mut luma_bad, mut chroma_bad) = (0usize, 0usize);
2827 for (ours, theirs) in decoded.iter().zip(&reference) {
2828 if ours.y != theirs.y {
2829 luma_bad += 1;
2830 }
2831 if ours.u != theirs.u || ours.v != theirs.v {
2832 chroma_bad += 1;
2833 }
2834 }
2835 (hits, luma_bad, chroma_bad)
2836 }
2837
2838 /// lane-interedge r1 GATE (was lane-oddh r2's `#[ignore]`d twin): the INTER
2839 /// frame-edge half strips -- a `PARTITION_HORZ`/`PARTITION_VERT` forced by
2840 /// the gathered edge symbol at the 64, 32 or 16 level whose second half lies
2841 /// outside the true frame. Both of the user's films are height mod 16 == 8
2842 /// (1920x792, 3840x1608), so every inter frame crosses these nodes.
2843 ///
2844 /// r1 root cause: the inter tile's 32-level `PARTITION_HORZ`/`PARTITION_VERT`
2845 /// decoded the SECOND strip unconditionally, while libaom `decode_partition`
2846 /// (decodeframe.c, PARTITION_HORZ) guards it with `has_rows`/`has_cols` --
2847 /// so at the edge we read symbols the encoder never wrote. With that guard
2848 /// removed this gate's 72x192 cq 32 arm refuses outright and its 104x192 arm
2849 /// decodes luma rows 127..191 of frame 5 wrong (measured r1).
2850 ///
2851 /// The compare is LUMA-exact per frame plus a CONTROL size with no edge node
2852 /// at all: chroma is excluded because a chroma-only inter residue that has
2853 /// nothing to do with the frame edge is open on main (lanes/tiny-r3,
2854 /// lanes/gmaffine-r4, lanes/palette2-r8) and the control below reproduces it
2855 /// with `inter_edge_strip_hits` all zero.
2856 #[test]
2857 fn a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact() {
2858 const NAME: &str = "a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact";
2859 let _gate_lock = lock_gate_counters();
2860 if !have_ffmpeg() || !have_aomenc() {
2861 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
2862 return;
2863 }
2864 let frames = 6usize;
2865 // h mod 16 == 8 (bottom edge) and w mod 16 == 8 (right edge).
2866 let sizes: &[(usize, usize)] = &[(192, 72), (192, 88), (72, 192), (88, 192), (104, 192)];
2867 let mut totals = [0usize; 6];
2868 let mut compared = 0u32;
2869 let mut chroma_frames = 0usize;
2870 for &(width, height) in sizes {
2871 for bit_depth in [8u32, 10] {
2872 for cq in [20u32, 32, 45] {
2873 let (hits, luma_bad, chroma_bad) =
2874 inter_edge_strip_attempt(NAME, width, height, bit_depth, cq, frames);
2875 assert_eq!(
2876 luma_bad, 0,
2877 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {luma_bad} of {frames} \
2878 frames differ from ffmpeg in LUMA (edge hits {hits:?})"
2879 );
2880 // merge J, after lane-rectchroma2: the chroma residue this
2881 // gate used to tolerate WAS this decoder's -- the per-axis
2882 // narrow-block MC kernel decision read side x side instead
2883 // of the block's true dims. Full-plane now.
2884 assert_eq!(
2885 chroma_bad, 0,
2886 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {chroma_bad} of \
2887 {frames} frames differ from ffmpeg in CHROMA (edge hits {hits:?})"
2888 );
2889 for (t, h) in totals.iter_mut().zip(hits) {
2890 *t += h;
2891 }
2892 chroma_frames += chroma_bad;
2893 compared += 1;
2894 }
2895 }
2896 }
2897 // Every level x axis this recipe reaches must have fired on a COMPARED
2898 // attempt. h32 (a bottom-edge HORZ at the 32 level) is not asserted: no
2899 // recipe found in r1 makes libaom answer that gathered symbol HORZ
2900 // (sweep ~/.cache/interedge-tmp/h32.sh, 3 sizes x 6 cq, all SPLIT); it
2901 // is the transposed twin of v32, which this gate does fire.
2902 assert!(
2903 totals[0] > 0 && totals[1] > 0 && totals[3] > 0 && totals[4] > 0 && totals[5] > 0,
2904 "{NAME}: {compared} attempts luma-exact but the edge strips did not all fire \
2905 (h64,v64,h32,v32,h16,v16 = {totals:?}) -- the recipe no longer reaches the arms \
2906 this gate exists for"
2907 );
2908 // CONTROL: a size with no frame-edge node anywhere (192x128, both axes
2909 // 0 mod 64). It must be luma-exact with ZERO edge hits -- that is what
2910 // makes the chroma exclusion above a statement about a foreign defect
2911 // rather than about this lane's code.
2912 let (chits, cluma, cchroma) = inter_edge_strip_attempt(NAME, 192, 128, 8, 32, frames);
2913 assert_eq!(
2914 (chits, cluma, cchroma),
2915 ([0usize; 6], 0usize, 0usize),
2916 "{NAME}: control 192x128 (no frame-edge node) must be pixel-exact with no edge hits"
2917 );
2918 eprintln!(
2919 "{NAME}: {compared} attempts luma-exact over {} sizes, edge hits \
2920 (h64,v64,h32,v32,h16,v16)={totals:?}, 0 refusals; chroma-only frames {chroma_frames} \
2921 (control 192x128: hits {chits:?}, chroma-only frames {cchroma} -- foreign defect)",
2922 sizes.len()
2923 );
2924 }
2925
2926 /// lane-sb128 r4 GATE (was lane-oddh r2's refusal gate): the SAME real
2927 /// aomenc 64x72 `--cpu-used=0 --sb-size=128` stream that once desynced at
2928 /// the very first symbol now decodes PIXEL-EXACT against aomdec. mi_rows
2929 /// = 18 > 16, so the BLOCK_128X128 root reads a real gathered partition
2930 /// symbol (2 symbols: has_cols false, has_rows true) -- exactly the case
2931 /// r1 mis-read as a 10-symbol BLOCK_64X64 partition.
2932 ///
2933 /// The `use_128x128_superblock` assert is the "knob reached the tool"
2934 /// half: without it an aomenc that ignored `--sb-size=128` would leave
2935 /// the gate proving nothing about 128 superblocks.
2936 #[test]
2937 fn a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact() {
2938 if !have_ffmpeg() || !have_aomenc() {
2939 eprintln!("SKIP: no ffmpeg/aomenc");
2940 return;
2941 }
2942 let (width, height) = (64usize, 72usize);
2943 let y4m = Command::new("ffmpeg")
2944 .args([
2945 "-v", "error", "-f", "lavfi", "-i",
2946 "mandelbrot=size=64x72:rate=25:start_x=-0.6:start_y=-0.4", "-t", "0.04",
2947 "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-",
2948 ])
2949 .stdin(Stdio::null())
2950 .stdout(Stdio::piped())
2951 .stderr(Stdio::piped())
2952 .output()
2953 .expect("ffmpeg failed to run");
2954 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
2955 let mut child = Command::new(aomenc_path())
2956 .args([
2957 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32",
2958 "--cpu-used=0", "--sb-size=128", "--min-partition-size=16",
2959 "--kf-max-dist=0", "--limit=1",
2960 "--threads=1", "--row-mt=0", "--obu", "-o", "-", "-",
2961 ])
2962 .stdin(Stdio::piped())
2963 .stdout(Stdio::piped())
2964 .stderr(Stdio::piped())
2965 .spawn()
2966 .expect("aomenc failed to start");
2967 child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("write y4m");
2968 let out = child.wait_with_output().expect("aomenc failed to run");
2969 assert!(out.status.success(), "aomenc refused: {}", String::from_utf8_lossy(&out.stderr));
2970 let stream = out.stdout;
2971
2972 // The knob actually arrived: this stream's sequence header codes
2973 // `use_128x128_superblock = 1`.
2974 let mut parser = Av1Parser::new();
2975 let mut pos = 0usize;
2976 let mut sb128 = false;
2977 while pos < stream.len() {
2978 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
2979 break;
2980 };
2981 pos += obu.total_size.max(1);
2982 if let Some(seq) = parser.sequence_header() {
2983 sb128 = seq.use_128x128_superblock;
2984 break;
2985 }
2986 }
2987 assert!(sb128, "aomenc ignored --sb-size=128: this stream is 64x64-superblock");
2988
2989 let _guard = lock_gate_counters();
2990 let before = crate::decode::part128_symbols()
2991 + crate::decode::part128_gathered_symbols();
2992 let (frames, hidden) =
2993 decode_all_frames_vs_oracle(&stream, "sb128-oddh-64x72");
2994 assert!(frames > 0, "no frames decoded for {width}x{height}");
2995 // The 128 root actually READ a partition symbol here: at mi_rows=18
2996 // `has_rows` is true, so BLOCK_128X128 is not a forced split.
2997 let part128 = crate::decode::part128_symbols()
2998 + crate::decode::part128_gathered_symbols()
2999 - before;
3000 assert!(
3001 part128 > 0,
3002 "{width}x{height} decoded without reading a single BLOCK_128X128 \
3003 partition symbol -- the gate proves nothing about the 128 root"
3004 );
3005 eprintln!(
3006 "a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact: \
3007 {frames} frames pixel-exact ({hidden} hidden) at {width}x{height}, \
3008 part128_symbols={part128}"
3009 );
3010 }
3011
3012 /// `decode_stream` on a lone key frame's stream matches both the tile
3013 /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and
3014 /// the encoder's own reconstruction, at an even and an odd size.
3015 #[test]
3016 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
3017 // lane-b128m: the ENCODER writes at this process's superblock size, so
3018 // its own trial decode -- and the raw tile decode below -- must be given
3019 // that size too (class: stale header in the test harness).
3020 let fctx = &crate::decode::FrameCtx::for_encoder();
3021 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
3022 let picture = test_card(width, height);
3023 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3024 let via_tile = decode_key_frame_tile_lr(
3025 &encoded.tile,
3026 encoded.mi_cols,
3027 encoded.mi_rows,
3028 encoded.base_q_idx,
3029 width as u32,
3030 height as u32,
3031 // lane-fintra: the sequence bit the encoder wrote this tile under
3032 // (stale-header class -- a hard-coded `false` here reads one symbol
3033 // short at the first DC_PRED block once the search offers filter intra).
3034 crate::encode::filter_intra_on(),
3035 &encoded.cdef,
3036 &encoded.loop_filter,
3037 encoded.tx_select,
3038 // lane-intertx: the frame's own `reduced_tx_set` -- a screen
3039 // key frame at preset 0 codes the wider intra alphabets, so
3040 // the old hardcoded `true` (ours "always" wrote true) is a
3041 // stale-header bug waiting for the first screen fixture.
3042 encoded.reduced_tx_set,
3043 // `allow_screen_content_tools` off the frame the encoder
3044 // actually wrote: a screen-content picture codes two palette
3045 // symbols per intra block, and a raw tile decode that guessed
3046 // `false` desyncs at the first one (class: test asserts
3047 // against a stale header).
3048 encoded.screen,
3049 // ... and its own `allow_intrabc` (stale-header class).
3050 encoded.allow_intrabc,
3051 &encoded.loop_restoration, fctx,
3052 )
3053 .unwrap();
3054 let via_stream = decode_stream(&encoded.stream).unwrap();
3055 assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture");
3056 assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma");
3057 assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U");
3058 assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V");
3059 assert_eq!(
3060 via_stream[0].y, encoded.reconstruction.y,
3061 "{width}x{height}: luma vs encoder reconstruction"
3062 );
3063 }
3064 }
3065
3066 /// A GOP (key frame plus panned inter frames, so blocks actually take
3067 /// motion) decodes bit-exact through `decode_stream` alone, threading its
3068 /// own DPB rather than a test-supplied reference.
3069 fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) {
3070 let pictures: Vec<_> = (0..4)
3071 .map(|i| panned_test_card(width, height, i * 3))
3072 .collect();
3073 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
3074 let decoded = decode_stream(&encoded.stream).unwrap();
3075 assert_eq!(decoded.len(), encoded.frames.len());
3076 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
3077 assert_eq!(
3078 got.y, frame.reconstruction.y,
3079 "{width}x{height} frame {i} luma"
3080 );
3081 assert_eq!(
3082 got.u, frame.reconstruction.u,
3083 "{width}x{height} frame {i} U"
3084 );
3085 assert_eq!(
3086 got.v, frame.reconstruction.v,
3087 "{width}x{height} frame {i} V"
3088 );
3089 }
3090 }
3091
3092 #[test]
3093 fn decode_stream_round_trips_a_gop() {
3094 let fctx = &crate::decode::FrameCtx::for_encoder();
3095 gop_round_trips(128, 64, fctx);
3096 }
3097
3098 /// Same claim at a size that is not a whole number of 32x32 blocks, so
3099 /// the inter frame's 16x16-leaf split path is exercised too.
3100 #[test]
3101 fn decode_stream_round_trips_an_odd_size_gop() {
3102 let fctx = &crate::decode::FrameCtx::for_encoder();
3103 gop_round_trips(216, 96, fctx);
3104 }
3105
3106 /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures
3107 /// `decode_stream` collects, in the same order -- the streaming path is
3108 /// the decoder now (`decode_stream` is a collecting wrapper), so an
3109 /// equivalence check here is what keeps every gate's Vec-shaped assert
3110 /// meaningful. Also pins the sink contract: one call per shown picture,
3111 /// decode indices non-decreasing, and an `Err` from the sink aborting.
3112 #[test]
3113 fn streaming_decode_matches_the_collecting_one() {
3114 let fctx = &crate::decode::FrameCtx::for_encoder();
3115 let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect();
3116 let stream = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap().stream;
3117 let collected = decode_stream(&stream).unwrap();
3118
3119 let mut shown = Vec::new();
3120 let mut idxs = Vec::new();
3121 let mut live = 0usize;
3122 decode_stream_with(&stream, |p, idx, is_shown| {
3123 live += 1;
3124 if is_shown {
3125 idxs.push(idx);
3126 shown.push(p.clone());
3127 }
3128 Ok(())
3129 })
3130 .unwrap();
3131 assert_eq!(shown.len(), collected.len(), "callback count vs shown frames");
3132 assert!(live >= shown.len(), "every shown picture is also a callback");
3133 assert!(
3134 idxs.windows(2).all(|w| w[0] <= w[1]),
3135 "decode indices out of order: {idxs:?}"
3136 );
3137 for (i, (got, want)) in shown.iter().zip(&collected).enumerate() {
3138 assert_eq!(got.y, want.y, "frame {i} luma");
3139 assert_eq!(got.u, want.u, "frame {i} U");
3140 assert_eq!(got.v, want.v, "frame {i} V");
3141 }
3142
3143 // A sink error stops the decode and comes back unchanged.
3144 let mut seen = 0usize;
3145 let err = decode_stream_with(&stream, |_, _, _| {
3146 seen += 1;
3147 Err(Error::corrupt("sink says stop"))
3148 })
3149 .unwrap_err();
3150 assert_eq!(seen, 1, "decode continued past a failing sink");
3151 assert!(format!("{err}").contains("sink says stop"), "{err}");
3152 }
3153
3154 use std::io::Write;
3155 use std::process::{Command, Stdio};
3156
3157 /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
3158 /// `skip_mode`/compound) all read a process-global atomic counter delta
3159 /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
3160 /// prove a real block picked the feature under test, not just that a
3161 /// header bit was set. Under `cargo test`'s default parallel run, a
3162 /// SIBLING test's own decode bumps the same global counter mid-gate --
3163 /// a false "fired" reading pixel-compares an attempt the gate would
3164 /// otherwise `continue` past, on top of genuine defects that path may
3165 /// still have. Serialising every counter-delta gate behind this one
3166 /// mutex makes firing detection honest again (matches the existing
3167 /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
3168 static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
3169 /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]):
3170 /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH
3171 /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named
3172 /// refusal -- and the three sum to the attempts made.
3173 fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) {
3174 eprintln!(
3175 "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \
3176 named-refusals={named_refusals} (attempts {})",
3177 counted_exact as usize + uncounted_exact as usize + named_refusals
3178 );
3179 }
3180
3181 pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
3182 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
3183 }
3184
3185 /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic --
3186 /// this is a load-bearing-identity fingerprint for flake triage, not a
3187 /// security digest, so no `sha2` dep is pulled in) fixture fingerprint
3188 /// for the cdf-forwarding gate's instrumentation below.
3189 fn fnv1a64(bytes: &[u8]) -> u64 {
3190 let mut hash = 0xcbf29ce484222325u64;
3191 for &b in bytes {
3192 hash ^= b as u64;
3193 hash = hash.wrapping_mul(0x100000001b3);
3194 }
3195 hash
3196 }
3197
3198 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
3199 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
3200 /// aomenc gate decodes its stream through ffmpeg and is meaningless
3201 /// without it -- turns it into a hard failure. Without this the require
3202 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
3203 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
3204 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
3205 fn have_ffmpeg() -> bool {
3206 let present = Command::new("ffmpeg")
3207 .arg("-version")
3208 .stdout(Stdio::null())
3209 .stderr(Stdio::null())
3210 .status()
3211 .is_ok_and(|s| s.success());
3212 assert!(
3213 present
3214 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
3215 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
3216 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
3217 );
3218 present
3219 }
3220
3221 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
3222 fn ffmpeg_decode_sequence(
3223 stream: &[u8],
3224 width: usize,
3225 height: usize,
3226 frames: usize,
3227 ) -> Vec<Pic> {
3228 let mut child = Command::new("ffmpeg")
3229 .args([
3230 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3231 ])
3232 .stdin(Stdio::piped())
3233 .stdout(Stdio::piped())
3234 .stderr(Stdio::piped())
3235 .spawn()
3236 .expect("ffmpeg failed to start");
3237 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
3238 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
3239 // fills before the last input byte is written -- which is exactly what
3240 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
3241 // (measured: 45 min, both processes at 0% CPU). A write error here is
3242 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
3243 // below, are the real diagnosis.
3244 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
3245 let payload = stream.to_vec();
3246 let writer = std::thread::Builder::new()
3247 .name("ec-av1-ffmpeg-in".into())
3248 .spawn(move || {
3249 let _ = stdin.write_all(&payload);
3250 })
3251 .expect("spawning the ffmpeg stdin writer");
3252 let out = child.wait_with_output().expect("ffmpeg failed to run");
3253 writer.join().expect("ffmpeg stdin writer thread");
3254 assert!(
3255 out.status.success(),
3256 "ffmpeg refused the stream: {}",
3257 String::from_utf8_lossy(&out.stderr)
3258 );
3259 let (luma, chroma) = (width * height, width * height / 4);
3260 let frame_bytes = luma + 2 * chroma;
3261 assert_eq!(
3262 out.stdout.len(),
3263 frame_bytes * frames,
3264 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
3265 String::from_utf8_lossy(&out.stderr)
3266 );
3267 (0..frames)
3268 .map(|i| {
3269 let base = i * frame_bytes;
3270 Pic {
3271 width,
3272 height,
3273 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
3274 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
3275 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
3276 }
3277 })
3278 .collect()
3279 }
3280
3281 /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
3282 /// are 2-byte little-endian, one full 16-bit range regardless of the
3283 /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
3284 /// bit depth). The 8-bit helper above stays untouched -- every existing
3285 /// gate depends on it.
3286 fn ffmpeg_decode_sequence_10bit(
3287 stream: &[u8],
3288 width: usize,
3289 height: usize,
3290 frames: usize,
3291 ) -> Vec<Pic> {
3292 let mut child = Command::new("ffmpeg")
3293 .args([
3294 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt",
3295 "yuv420p10le", "-",
3296 ])
3297 .stdin(Stdio::piped())
3298 .stdout(Stdio::piped())
3299 .stderr(Stdio::piped())
3300 .spawn()
3301 .expect("ffmpeg failed to start");
3302 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
3303 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
3304 // fills before the last input byte is written -- which is exactly what
3305 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
3306 // (measured: 45 min, both processes at 0% CPU). A write error here is
3307 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
3308 // below, are the real diagnosis.
3309 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
3310 let payload = stream.to_vec();
3311 let writer = std::thread::Builder::new()
3312 .name("ec-av1-ffmpeg-in".into())
3313 .spawn(move || {
3314 let _ = stdin.write_all(&payload);
3315 })
3316 .expect("spawning the ffmpeg stdin writer");
3317 let out = child.wait_with_output().expect("ffmpeg failed to run");
3318 writer.join().expect("ffmpeg stdin writer thread");
3319 assert!(
3320 out.status.success(),
3321 "ffmpeg refused the stream: {}",
3322 String::from_utf8_lossy(&out.stderr)
3323 );
3324 let (luma, chroma) = (width * height, width * height / 4);
3325 let frame_samples = luma + 2 * chroma;
3326 let frame_bytes = frame_samples * 2;
3327 assert_eq!(
3328 out.stdout.len(),
3329 frame_bytes * frames,
3330 "expected {frames} 4:2:0 10-bit frames, ffmpeg said: {}",
3331 String::from_utf8_lossy(&out.stderr)
3332 );
3333 fn le16(bytes: &[u8]) -> Vec<u16> {
3334 bytes
3335 .chunks_exact(2)
3336 .map(|c| u16::from_le_bytes([c[0], c[1]]))
3337 .collect()
3338 }
3339 (0..frames)
3340 .map(|i| {
3341 let base = i * frame_bytes;
3342 Pic {
3343 width,
3344 height,
3345 y: le16(&out.stdout[base..base + luma * 2]),
3346 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
3347 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
3348 }
3349 })
3350 .collect()
3351 }
3352
3353 /// lane-svtinter: an SVT-AV1 screen stream whose frame height is not a
3354 /// multiple of the superblock size codes PALETTE blocks in the bottom
3355 /// (and right) superblock row that hang off the mi grid. Spec 5.11.50
3356 /// `palette_tokens` reads the colour-index map only over the block's
3357 /// `onscreenWidth x onscreenHeight` corner and replicates it outward;
3358 /// this decoder read the full block grid, so it consumed colour-index
3359 /// symbols libaom never wrote and desynced the rest of the tile -- either
3360 /// a wrong bottom superblock row (1599 luma samples in this stream's
3361 /// frame 0, ~80k per inter frame after) or, further along the same tile,
3362 /// a bogus "a Golomb tail longer than this decoder reads" refusal.
3363 ///
3364 /// Unlike its lane-svt1 sibling above this one BUILDS its stream: the
3365 /// recipe is synthetic (`smptebars,drawgrid` through `libsvtav1 -preset 8
3366 /// -svtav1-params screen-content-mode=1`), and 384x152 puts a 32x32
3367 /// palette block at mi row 32 of a 38-mi-tall frame, 24 of its 32 rows
3368 /// on screen. `palette_onscreen_cut_hits` is asserted non-zero so the row
3369 /// cannot pass on a stream that never cuts a palette map (class
3370 /// gate-blind-to-feature).
3371 #[test]
3372 fn an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly() {
3373 const NAME: &str = "an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly";
3374 if !have_ffmpeg() {
3375 eprintln!("SKIP {NAME}: no ffmpeg");
3376 return;
3377 }
3378 let (width, height) = (384usize, 152usize);
3379 let out = Command::new("ffmpeg")
3380 .args([
3381 "-v", "error", "-f", "lavfi", "-i",
3382 "smptebars=s=384x152:r=12,drawgrid=w=8:h=8:t=1:c=black",
3383 "-frames:v", "4", "-c:v", "libsvtav1", "-preset", "8", "-crf", "30",
3384 "-svtav1-params", "lp=1:screen-content-mode=1", "-g", "12", "-f", "obu", "-",
3385 ])
3386 .stdin(Stdio::null())
3387 .stdout(Stdio::piped())
3388 .stderr(Stdio::piped())
3389 .output()
3390 .expect("ffmpeg failed to run");
3391 if !out.status.success() || out.stdout.is_empty() {
3392 eprintln!(
3393 "SKIP {NAME}: no libsvtav1 in this ffmpeg: {}",
3394 String::from_utf8_lossy(&out.stderr)
3395 );
3396 return;
3397 }
3398 let stream = out.stdout;
3399 crate::decode::reset_palette_onscreen_cut_hits();
3400 let decoded = decode_stream(&stream).expect("the SVT-AV1 screen stream decodes");
3401 assert_eq!(decoded.len(), 4, "{NAME}: frame count");
3402 assert!(
3403 crate::decode::palette_onscreen_cut_hits() > 0,
3404 "{NAME}: no palette map is cut by the frame edge here -- the gate would pass blind"
3405 );
3406 let want = ffmpeg_decode_sequence(&stream, width, height, decoded.len());
3407 assert_eq!(want.len(), decoded.len(), "{NAME}: ffmpeg frame count");
3408 for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
3409 assert_eq!(got.y, want.y, "{NAME}: frame {i} luma vs ffmpeg");
3410 assert_eq!(got.u, want.u, "{NAME}: frame {i} U vs ffmpeg");
3411 assert_eq!(got.v, want.v, "{NAME}: frame {i} V vs ffmpeg");
3412 }
3413 }
3414
3415 /// lane-svt1: an SVT-AV1 (v3.1.2, `-preset 8 -crf 35`) screen key frame
3416 /// codes 16x16 PALETTE blocks with `skip == 1` whose `tx_depth` split the
3417 /// luma transform. [`crate::decode::decode_block`] armed the palette
3418 /// prediction only when the transform covered the whole block, so that one
3419 /// block predicted DC off its own edges instead: the right symbols (the
3420 /// whole mode ladder diffs clean against an instrumented aomdec) and the
3421 /// wrong pixels -- 812 luma samples in frame 0, carried by the V_PRED
3422 /// blocks under it to 10122 samples over the 12-frame stream.
3423 ///
3424 /// No lavfi recipe witnesses it in a stream this decoder otherwise decodes:
3425 /// 6 sources x 5 sizes x 6 crf values through `libsvtav1 -preset 8
3426 /// -svtav1-params screen-content-mode=1` produced 8 streams that reach the
3427 /// path, and every one of them either refuses on an unrelated Golomb tail
3428 /// or misses by ~200k samples on unrelated inter-frame defects (both
3429 /// recorded in `lanes/svt1.report.md`). So the gate rides the kept stream
3430 /// named by `EC_AV1_SVT1_STREAM` and SKIPs when it is unset -- the screen
3431 /// crop itself is never committed to `fixtures/`.
3432 ///
3433 /// `skip_split_tx_override_hits` is asserted non-zero so the row cannot
3434 /// pass on a stream that never reaches the fixed arm (class
3435 /// gate-blind-to-feature).
3436 #[test]
3437 fn an_svt_screen_palette_block_with_a_split_transform_decodes_exactly() {
3438 const NAME: &str = "an_svt_screen_palette_block_with_a_split_transform_decodes_exactly";
3439 let Ok(path) = std::env::var("EC_AV1_SVT1_STREAM") else {
3440 eprintln!("SKIP {NAME}: EC_AV1_SVT1_STREAM names no stream");
3441 return;
3442 };
3443 if !have_ffmpeg() {
3444 eprintln!("SKIP {NAME}: no ffmpeg");
3445 return;
3446 }
3447 let data = match std::fs::read(&path) {
3448 Ok(data) => data,
3449 Err(e) => {
3450 eprintln!("SKIP {NAME}: {path}: {e}");
3451 return;
3452 }
3453 };
3454 crate::decode::reset_skip_split_tx_override_hits();
3455 let decoded = decode_stream(&data).expect("the kept SVT-AV1 screen stream decodes");
3456 assert!(
3457 crate::decode::skip_split_tx_override_hits() > 0,
3458 "{NAME}: no skipped split-transform palette block in {path} -- the gate would pass blind"
3459 );
3460 let (width, height) = (decoded[0].width, decoded[0].height);
3461 let want = ffmpeg_decode_sequence(&data, width, height, decoded.len());
3462 for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
3463 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
3464 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
3465 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
3466 }
3467 }
3468
3469 /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an
3470 /// independent decoder, not just this crate checking its own tile path.
3471 #[test]
3472 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
3473 let fctx = &crate::decode::FrameCtx::for_encoder();
3474 if !have_ffmpeg() {
3475 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
3476 return;
3477 }
3478 // lane-av1straddle: 216x96 joins 128x64 because only a size whose
3479 // 32x32 blocks straddle the right-hand frame edge can see the writer
3480 // coding a transform unit that starts outside the frame -- libdav1d
3481 // AND libaom both refused the whole key frame while it did, and this
3482 // crate's own (lenient) decoder only differed in the last block's V.
3483 for &(width, height) in &[(128usize, 64usize), (216usize, 96usize)] {
3484 let pictures: Vec<_> = (0..3)
3485 .map(|i| panned_test_card(width, height, i * 3))
3486 .collect();
3487 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
3488 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
3489 let decoded = decode_stream(&encoded.stream).unwrap();
3490 assert_eq!(decoded.len(), 3);
3491 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
3492 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
3493 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
3494 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
3495 }
3496 // ... and the encoder's own reconstruction is what ffmpeg sees,
3497 // so the check fails on a writer-side desync too, not only on a
3498 // decoder-side one.
3499 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
3500 let rec = &frame.reconstruction;
3501 assert_eq!(rec.y, want.y, "{width}x{height} frame {i} luma: reconstruction vs ffmpeg");
3502 assert_eq!(rec.u, want.u, "{width}x{height} frame {i} U: reconstruction vs ffmpeg");
3503 assert_eq!(rec.v, want.v, "{width}x{height} frame {i} V: reconstruction vs ffmpeg");
3504 }
3505 }
3506 }
3507
3508 /// lane-av1rect: the encoder used to REFUSE every size where a 32x32
3509 /// block straddles BOTH true frame edges at once ("straddles the true
3510 /// frame edge in a way that needs a rectangular (HORZ/VERT) transform
3511 /// this encoder does not code yet"). That refusal was a misreading of
3512 /// spec 5.11.4: a block whose `hasRows` and `hasCols` are BOTH false
3513 /// reads no partition symbol at all and is `PARTITION_SPLIT` by
3514 /// inference, down to the 8x8 leaves whose own mi origin is inside the
3515 /// frame -- exactly the leaves this writer already codes for the
3516 /// one-axis case, and no rectangular transform anywhere. The sweep walks
3517 /// the corners around the 32-multiples (each width has a 16x16 column
3518 /// whose right half is outside, each height a row whose bottom half is,
3519 /// so the bottom-right 16x16 of every size here is cut on both axes) and
3520 /// three-way compares: our decoder, the encoder's own reconstruction and
3521 /// ffmpeg, over a 4-frame GOP so the inter writer's copy of the same
3522 /// signaling is covered too. `edge_both_cut_hits` proves the decoder
3523 /// really took the inferred-split path rather than the gate passing on
3524 /// geometry that never fires it.
3525 #[test]
3526 fn a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg() {
3527 let fctx = &crate::decode::FrameCtx::for_encoder();
3528 if !have_ffmpeg() {
3529 eprintln!("SKIP a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg: no ffmpeg");
3530 return;
3531 }
3532 const FRAMES: usize = 4;
3533 let mut both_cut = 0usize;
3534 for &width in &[200usize, 216, 232, 248] {
3535 for &height in &[104usize, 120, 136, 152] {
3536 let pictures: Vec<_> = (0..FRAMES as i64)
3537 .map(|i| panned_test_card(width, height, i * 3))
3538 .collect();
3539 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
3540 .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
3541 // Reset per attempt, never a delta across sizes (class
3542 // counter-from-refused-stream).
3543 crate::decode::reset_edge_both_cut_hits();
3544 let decoded = decode_stream(&encoded.stream)
3545 .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
3546 both_cut += crate::decode::edge_both_cut_hits().iter().sum::<usize>();
3547 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
3548 assert_eq!(
3549 ffmpeg_frames.len(),
3550 FRAMES,
3551 "{width}x{height}: ffmpeg decoded {} of {FRAMES} frames",
3552 ffmpeg_frames.len()
3553 );
3554 assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
3555 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
3556 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
3557 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
3558 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
3559 }
3560 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
3561 let rec = &frame.reconstruction;
3562 assert_eq!(rec.y, want.y, "{width}x{height} frame {i} luma: recon vs ffmpeg");
3563 assert_eq!(rec.u, want.u, "{width}x{height} frame {i} U: recon vs ffmpeg");
3564 assert_eq!(rec.v, want.v, "{width}x{height} frame {i} V: recon vs ffmpeg");
3565 }
3566 }
3567 }
3568 assert!(
3569 both_cut > 0,
3570 "no partition node in the whole sweep was coded as the both-axes-cut \
3571 inferred split -- the gate is blind to the feature it pins"
3572 );
3573 }
3574
3575 /// lane-corner: sizes whose LAST superblock is cut by the true frame
3576 /// edge on BOTH axes with more than half of each still inside -- so
3577 /// `has_cols` and `has_rows` are both true and the spec lets that
3578 /// superblock stay a whole 64x64 `PARTITION_NONE` block, which this
3579 /// encoder's roots take (`EC_AV1_B64EDGE` on the inter side, the key
3580 /// frame's own `Superblock::Whole`). The sibling luma-only test
3581 /// (`encoder.rs`'s `a_non_superblock_aligned_clip_...`) is blind to
3582 /// chroma (class `metric-blind-to-a-plane`), so this one compares all
3583 /// three planes three ways: our decoder, the encoder's own
3584 /// reconstruction, and ffmpeg.
3585 #[test]
3586 fn a_doubly_cut_superblock_root_round_trips_in_every_plane() {
3587 let fctx = &crate::decode::FrameCtx::for_encoder();
3588 if !have_ffmpeg() {
3589 eprintln!("SKIP a_doubly_cut_superblock_root_round_trips_in_every_plane: no ffmpeg");
3590 return;
3591 }
3592 const FRAMES: usize = 4;
3593 // Each size leaves MORE than half of its last superblock row (and,
3594 // but for 200x120's 8-px column, of its last column) inside, which is
3595 // what makes the root legal there at all; 248x168/232x168/248x184 are
3596 // cut on BOTH axes at once. 1920x1080 -- the user's own export shape
3597 // -- is the same case: 1080 = 16*64 + 56, a 56-px bottom straddle.
3598 for &(width, height) in &[(248usize, 168usize), (232, 168), (200, 120), (248, 184)] {
3599 let pictures: Vec<_> = (0..FRAMES as i64)
3600 .map(|i| panned_test_card(width, height, i * 3))
3601 .collect();
3602 let _ = crate::encode::take_b64_edge_hits();
3603 let _ = crate::encode::take_i64_root_hits();
3604 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
3605 .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
3606 let edges = crate::encode::take_b64_edge_hits();
3607 let [i64_whole, i64_offered, i64_edge] = crate::encode::take_i64_root_hits();
3608 eprintln!(
3609 "{width}x{height}: edge inter 64 roots {edges}, key 64 roots {i64_whole} of \
3610 {i64_offered} offered, {i64_edge} of them cut by the frame edge"
3611 );
3612 // gate-blind-to-feature: without this the three-way compare below
3613 // passes on a stream that never coded a whole root at the cut
3614 // superblock at all.
3615 assert!(
3616 i64_edge > 0,
3617 "{width}x{height}: no 64x64 root sat on a superblock the frame edge cuts"
3618 );
3619 let decoded = decode_stream(&encoded.stream)
3620 .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
3621 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
3622 assert_eq!(ffmpeg_frames.len(), FRAMES, "{width}x{height}: ffmpeg frame count");
3623 assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
3624 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
3625 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma: ours vs ffmpeg");
3626 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U: ours vs ffmpeg");
3627 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V: ours vs ffmpeg");
3628 }
3629 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
3630 let rec = &frame.reconstruction;
3631 assert_eq!(rec.y, want.y, "{width}x{height} frame {i} luma: recon vs ffmpeg");
3632 assert_eq!(rec.u, want.u, "{width}x{height} frame {i} U: recon vs ffmpeg");
3633 assert_eq!(rec.v, want.v, "{width}x{height} frame {i} V: recon vs ffmpeg");
3634 }
3635 }
3636 }
3637
3638 /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME`
3639 /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s
3640 /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc
3641 /// attempts never could: frame 0 is a real key frame (this crate's own
3642 /// encoder, real texture), refreshing all 8 DPB slots as spec requires --
3643 /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded
3644 /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`),
3645 /// refreshing only slot 0 with a flat 128 block -- distinguishable from
3646 /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3
3647 /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs.
3648 /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3`
3649 /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose
3650 /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME`
3651 /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy
3652 /// of GOLDEN's picture, so its output must equal frame 0's own
3653 /// reconstruction exactly, and must differ from frame 1's -- proof the
3654 /// decoder actually read the golden plane, not silently substituted
3655 /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a
3656 /// deblock/MC residue that turned out to be film-grain synthesis
3657 /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN);
3658 /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing
3659 /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so
3660 /// this fixture flips back to its round-4 pixel-exact form. ffmpeg
3661 /// decodes the identical wire bytes as the foreign oracle
3662 /// (shared-oracle-blindness class): this crate's own decoder agreeing
3663 /// with itself would prove nothing.
3664 #[test]
3665 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
3666 let fctx = &crate::decode::FrameCtx::new();
3667 if !have_ffmpeg() {
3668 eprintln!(
3669 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
3670 );
3671 return;
3672 }
3673 use crate::cdf_state::Cdfs;
3674 use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of};
3675 use crate::encode::{inter_frame_headers, key_frame_headers};
3676 use crate::frame::frame_obu;
3677 use crate::msac::SymbolEncoder;
3678 use crate::mvstack::{
3679 GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx,
3680 single_ref_p5_ctx,
3681 };
3682 use crate::obu::temporal_delimiter;
3683
3684 let (width, height) = (32usize, 32usize);
3685 let base_q_idx = 100u8;
3686 // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/
3687 // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" --
3688 // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB`
3689 // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false
3690 // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/
3691 // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1`
3692 // (decode.rs `Neighbours::new`) -- computed here without
3693 // constructing the (module-private) `Neighbours` itself.
3694 const PARTITION_NONE: usize = 0;
3695 let ii_ctx = intra_inter_ctx(false, false, false, false);
3696 let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None);
3697 let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None);
3698 let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None);
3699
3700 for run in 0..4 {
3701 let picture = test_card(width, height);
3702 let key = encode_key_frame_with_ctx(&picture, base_q_idx, 0.5, fctx).unwrap();
3703 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
3704
3705 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
3706 // 128 block (no neighbours to predict `DC_PRED` from).
3707 let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
3708 // These two tiles are hand-coded from a FRESH `Cdfs`, so the
3709 // frames must not carry CDF state the way the encoder's own inter
3710 // frames now do (spec 7.20): with the bit set, what each frame
3711 // stores is what it started from -- the defaults -- which is
3712 // exactly what the next hand-coded tile assumes.
3713 header1.disable_frame_end_update_cdf = true;
3714 let tile1 = {
3715 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3716 let mut enc = SymbolEncoder::new();
3717 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
3718 enc.symbol(1, &mut cdfs.skip[0]); // skip
3719 enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false
3720 enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32)
3721 enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED
3722 enc.finish()
3723 };
3724 let mut stream = key.stream.clone();
3725 stream.extend(temporal_delimiter());
3726 stream.extend(frame_obu(&seq, &header1, &tile1).unwrap());
3727
3728 // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
3729 // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
3730 let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
3731 header2.disable_frame_end_update_cdf = true;
3732 header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
3733 let tile2 = {
3734 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3735 let mut enc = SymbolEncoder::new();
3736 let grid = MiGrid::new(8, 8);
3737 let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8);
3738 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
3739 enc.symbol(1, &mut cdfs.skip[0]); // skip
3740 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true
3741 enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group
3742 enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group
3743 enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME
3744 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV
3745 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV
3746 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0)
3747 enc.finish()
3748 };
3749 stream.extend(temporal_delimiter());
3750 stream.extend(frame_obu(&seq, &header2, &tile2).unwrap());
3751
3752 let before = non_last_ref_hits();
3753 let decoded = decode_stream(&stream).unwrap();
3754 assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures");
3755 assert!(
3756 non_last_ref_hits() > before,
3757 "run {run}: GOLDEN_FRAME never fired"
3758 );
3759
3760 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3);
3761 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
3762 assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg");
3763 assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg");
3764 assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg");
3765 }
3766 assert_eq!(
3767 decoded[0].y, key.reconstruction.y,
3768 "run {run}: frame 0 vs the encoder's own reconstruction"
3769 );
3770 assert_eq!(
3771 decoded[2].y, key.reconstruction.y,
3772 "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names"
3773 );
3774 assert_ne!(
3775 decoded[2].y, decoded[1].y,
3776 "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \
3777 distinguishable -- the gate proves nothing"
3778 );
3779 }
3780 }
3781
3782 /// Builds a `gradients` lavfi source string with colours derived from
3783 /// `seed`, not left to the filter's own default.
3784 ///
3785 /// Measured (lane-fixdet r1): ffmpeg's `gradients` source IGNORES its
3786 /// `seed=` parameter for colour selection -- five encodes of an
3787 /// identical command line (same `seed=`, same everything) produced five
3788 /// different fixtures, because the unset `c0..c9` stops are randomized
3789 /// from something other than that seed. Every one of this file's ~20
3790 /// gate fixtures built a `gradients` source this way, so none of them
3791 /// had a reproducible input: a pin captured from one run could not be
3792 /// regenerated, and "attempt N failed" was as likely to be a different
3793 /// fixture as a different decode outcome.
3794 ///
3795 /// Freezing the colours outright (as the earliest four gates below do,
3796 /// hand-picking `c0=red:c1=blue:c2=green`) fixes reproducibility but
3797 /// throws away the per-attempt content variety the sweep gates need to
3798 /// make features (OBMC, warp, wedge, ...) fire at all -- this repo's own
3799 /// `sampler-decorrelated-gate` class. So: derive `c0..c3` deterministically
3800 /// FROM the seed with a plain integer hash, and keep passing `seed=`
3801 /// itself too, so a future ffmpeg that actually honours it only adds
3802 /// more variety, never removes the determinism this buys.
3803 fn gradients_source(seed: u32, width: usize, height: usize, tail: &str) -> String {
3804 fn hash_color(seed: u32, salt: u32) -> String {
3805 let h = seed
3806 .wrapping_mul(2_654_435_761)
3807 .wrapping_add(salt.wrapping_mul(0x9E37_79B9))
3808 ^ (seed.rotate_left(13));
3809 format!("0x{:06x}", h & 0x00ff_ffff)
3810 }
3811 let (c0, c1, c2, c3) = (
3812 hash_color(seed, 0),
3813 hash_color(seed, 1),
3814 hash_color(seed, 2),
3815 hash_color(seed, 3),
3816 );
3817 format!("gradients=size={width}x{height}:c0={c0}:c1={c1}:c2={c2}:c3={c3}:seed={seed}:{tail}")
3818 }
3819
3820 /// The determinism guard: same seed twice must byte-match ffmpeg's own
3821 /// output; different seeds must not. Regresses this fix if it ever
3822 /// breaks.
3823 #[test]
3824 fn gradients_source_is_reproducible_per_seed() {
3825 if !have_ffmpeg() {
3826 eprintln!("SKIP gradients_source_is_reproducible_per_seed: no ffmpeg");
3827 return;
3828 }
3829 fn render_hash(lavfi: &str) -> Vec<u8> {
3830 let out = Command::new("ffmpeg")
3831 .args([
3832 "-v", "error", "-f", "lavfi", "-i", lavfi, "-frames:v", "1", "-f", "rawvideo",
3833 "-",
3834 ])
3835 .stdin(Stdio::null())
3836 .stdout(Stdio::piped())
3837 .stderr(Stdio::piped())
3838 .output()
3839 .expect("ffmpeg failed to run");
3840 assert!(out.status.success(), "ffmpeg refused {lavfi}");
3841 out.stdout
3842 }
3843 let a1 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
3844 let a2 = render_hash(&gradients_source(43, 64, 64, "duration=0.04:rate=25"));
3845 let a3 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
3846 assert_eq!(a1, a3, "same seed must reproduce byte-identical output");
3847 assert_ne!(a1, a2, "different seeds must not collide");
3848 }
3849
3850 /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this
3851 /// crate's) with the same reduced-partition flags lane-av1adst's r6
3852 /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on
3853 /// gradient content (TX_SET_INTRA_2), and decodes it with
3854 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
3855 /// gets past an encoder this crate never wrote a byte of.
3856 fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
3857 libaom_encode_with(lavfi, width, height, crf, &[])
3858 }
3859
3860 /// As [`libaom_encode`], with extra encoder args appended -- used to pin
3861 /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
3862 /// RD search is not otherwise stable run-to-run on this box, and lavfi
3863 /// `gradients` needs its own `seed=` for the same reason) and to gate
3864 /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
3865 fn libaom_encode_with(
3866 lavfi: &str,
3867 width: usize,
3868 height: usize,
3869 crf: u32,
3870 extra: &[&str],
3871 ) -> Option<Vec<u8>> {
3872 let mut args = vec![
3873 "-v",
3874 "error",
3875 "-f",
3876 "lavfi",
3877 "-i",
3878 lavfi,
3879 "-frames:v",
3880 "1",
3881 "-pix_fmt",
3882 "yuv420p",
3883 "-c:v",
3884 "libaom-av1",
3885 ];
3886 let crf_str = crf.to_string();
3887 args.extend(["-crf", &crf_str]);
3888 args.extend([
3889 "-cpu-used",
3890 "8",
3891 "-enable-rect-partitions",
3892 "0",
3893 "-enable-ab-partitions",
3894 "0",
3895 "-enable-1to4-partitions",
3896 "0",
3897 "-enable-angle-delta",
3898 "0",
3899 "-enable-cfl-intra",
3900 "0",
3901 ]);
3902 args.extend(extra.iter().copied());
3903 args.extend(["-f", "obu", "-"]);
3904 let out = Command::new("ffmpeg")
3905 .args(&args)
3906 .stdin(Stdio::null())
3907 .stdout(Stdio::piped())
3908 .stderr(Stdio::piped())
3909 .output()
3910 .expect("ffmpeg failed to run");
3911 if !out.status.success() {
3912 eprintln!(
3913 "ffmpeg refused to encode {lavfi} at {width}x{height}: {}",
3914 String::from_utf8_lossy(&out.stderr)
3915 );
3916 return None;
3917 }
3918 Some(out.stdout)
3919 }
3920
3921 /// The end-to-end gate: two real libaom-av1 configs, decoded with
3922 /// [`decode_stream`] and checked against ffmpeg's own decode of the same
3923 /// bytes. Not every config this encoder writes decodes yet (partitions
3924 /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the
3925 /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the
3926 /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this
3927 /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx
3928 /// types on gradient content.
3929 #[test]
3930 fn a_real_libaom_stream_with_adst_decodes_end_to_end() {
3931 if !have_ffmpeg() {
3932 eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg");
3933 return;
3934 }
3935 let configs: [(String, usize, usize, u32); 2] = [
3936 ("testsrc2=size=64x64:rate=1".to_string(), 64, 64, 15),
3937 (gradients_source(42, 64, 64, "rate=1"), 64, 64, 15),
3938 ];
3939 let mut verdicts = Vec::new();
3940 for (lavfi, width, height, crf) in configs {
3941 let lavfi = lavfi.as_str();
3942 let Some(stream) = libaom_encode(lavfi, width, height, crf) else {
3943 verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode"));
3944 continue;
3945 };
3946 match decode_stream(&stream) {
3947 Ok(frames) => {
3948 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3949 let matches = frames[0].y == ffmpeg_frames[0].y
3950 && frames[0].u == ffmpeg_frames[0].u
3951 && frames[0].v == ffmpeg_frames[0].v;
3952 verdicts.push(format!(
3953 "{lavfi}: decoded, {} ffmpeg's own decode",
3954 if matches { "MATCHES" } else { "MISMATCHES" }
3955 ));
3956 // Not a hard `assert!`: libaom's own mode decisions at
3957 // `cpu-used 8` are not observed stable run-to-run on this
3958 // box (multi-threaded RD search), so a run that happens
3959 // to land on a still-unsupported syntax element (e.g. a
3960 // partition below 16x16, a separate round-2 gap) can
3961 // decode without erroring yet disagree -- that failure
3962 // mode belongs to those other gaps, not to this round's
3963 // ADST wiring, and the eprintln below reports it either
3964 // way rather than hiding it.
3965 }
3966 Err(e) => {
3967 verdicts.push(format!("{lavfi}: still refuses ({e})"));
3968 }
3969 }
3970 }
3971 eprintln!("libaom ADST end-to-end verdicts:");
3972 for v in &verdicts {
3973 eprintln!(" {v}");
3974 }
3975 }
3976
3977 /// lane-dgolomb: the `force_integer_mv` gate. libaom turns screen-content
3978 /// tools on for DARK, SMOOTH content -- its `av1_set_screen_content_options`
3979 /// counts 16x16 blocks with 2..=4 distinct luma values -- and then sets
3980 /// `force_integer_mv` on any inter frame whose source is pixel-identical to
3981 /// the previously coded source (`av1_is_integer_mv`: `cs_rate >= 0.8` and
3982 /// `C == T`, every collocated 8x8 block matching, is the only path that
3983 /// returns 1). Both hold on his real AV1 films, and this decoder used to
3984 /// drop `lower_mv_precision`'s `is_integer` half as unreachable, so every
3985 /// temporal MV candidate on such a frame came out at eighth-pel: the frame
3986 /// decoded without any error into a whole-frame prediction mismatch, and
3987 /// the desync surfaced blocks later as "a Golomb tail longer than this
3988 /// decoder reads".
3989 ///
3990 /// The source is SYNTHETIC (no film sample lives in `fixtures`): the
3991 /// near-flat dark pattern libaom's own screen-content detector counts as
3992 /// screen content, at the film-B crop size 1920x1024, SCROLLING globally
3993 /// 5 px per frame and frozen on frame 8 -- an exact duplicate of frame 7
3994 /// (the `C == T` trigger) whose twin is not among its own references, so
3995 /// its blocks still code real motion under `force_integer_mv`.
3996 ///
3997 /// lane-dpm1 made this gate SENSITIVE: with the `force_integer_mv` branch
3998 /// of [`crate::motion_field::lower_mv_precision`] stubbed out (`if false
3999 /// &&`) the stream decodes WRONG -- frame 8, luma sample 25695, 20 against
4000 /// ffmpeg's 19 -- where the previous patch-in-a-static-background recipe
4001 /// (and two others tried) still decoded byte-exact: there the used mv-stack
4002 /// slots came from agreeing spatial neighbours and the rounded temporal
4003 /// entries never won one. The gate asserts both halves: at least one INTER
4004 /// frame really carries `force_integer_mv` (class `gate-blind-to-feature`),
4005 /// and every shown frame decodes sample-exact against ffmpeg's own decode.
4006 #[test]
4007 fn a_libaom_force_integer_mv_stream_decodes_exact() {
4008 const NAME: &str = "a_libaom_force_integer_mv_stream_decodes_exact";
4009 if !have_ffmpeg() {
4010 eprintln!("SKIP {NAME}: no ffmpeg");
4011 return;
4012 }
4013 let (w, h, frames) = (1920usize, 1024usize, 16usize);
4014 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
4015 let mut off = 0usize;
4016 for f in 0..frames {
4017 // lane-dpm1: the WHOLE picture scrolls 5 px per frame and freezes
4018 // on frame 8, so (a) every block of the frozen frame -- including
4019 // mi(0,0), which has no spatial neighbour at all -- still codes
4020 // real motion against the references that are not its twin, and
4021 // (b) 40 eighth-pels projected over the pyramid's distances lands
4022 // on non-multiples of 8 (40/2 = 20 -> 16). A patch moving inside a
4023 // static background was NOT sensitive: there the used stack slots
4024 // came from spatial neighbours that agreed, and the rounded
4025 // temporal entries never won one.
4026 if f > 0 && f != 8 {
4027 off = (off + 5) % h;
4028 }
4029 let mut y = vec![0u8; w * h];
4030 for row in 0..h {
4031 let src = (row + off) % h;
4032 for col in 0..w {
4033 // 2..=4 distinct values per 16x16 block, all dark: the
4034 // screen-content detector's own counting rule.
4035 y[row * w + col] =
4036 16 + ((col / 32 + src / 32) % 5) as u8 + ((col / 4 + src / 4) % 3) as u8;
4037 }
4038 }
4039 raw.extend_from_slice(&y);
4040 raw.extend(std::iter::repeat_n(128u8, w * h / 2));
4041 }
4042 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
4043 let src = std::env::temp_dir().join(format!("ec-av1-intmv-{}.yuv", std::process::id()));
4044 std::fs::write(&src, &raw).expect("raw source");
4045 let out = Command::new("ffmpeg")
4046 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
4047 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
4048 .arg(&src)
4049 .args(["-an", "-threads", "1", "-g", "16", "-c:v", "libaom-av1"])
4050 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "35", "-f", "obu", "-"])
4051 .stdin(Stdio::null())
4052 .stdout(Stdio::piped())
4053 .stderr(Stdio::piped())
4054 .output()
4055 .expect("ffmpeg failed to run");
4056 let _ = std::fs::remove_file(&src);
4057 if !out.status.success() {
4058 eprintln!(
4059 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
4060 String::from_utf8_lossy(&out.stderr)
4061 );
4062 return;
4063 }
4064 let stream = out.stdout;
4065
4066 // Half of the gate: the stream must actually carry the feature.
4067 let mut parser = Av1Parser::new();
4068 let (mut pos, mut int_mv_inter) = (0usize, 0usize);
4069 while pos < stream.len() {
4070 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
4071 pos += obu.total_size.max(1);
4072 let header = match &obu.kind {
4073 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
4074 _ => continue,
4075 };
4076 if header.force_integer_mv && !header.frame_is_intra && header.use_ref_frame_mvs {
4077 int_mv_inter += 1;
4078 }
4079 }
4080 assert!(
4081 int_mv_inter > 0,
4082 "{NAME} went blind: libaom coded no inter frame with force_integer_mv"
4083 );
4084
4085 let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
4086 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
4087 assert_eq!(ours.len(), frames, "shown frame count");
4088 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
4089 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
4090 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
4091 assert!(
4092 first.is_none(),
4093 "frame {i} plane {plane} differs from ffmpeg at sample {} \
4094 ({int_mv_inter} force_integer_mv inter frames in this stream)",
4095 first.unwrap()
4096 );
4097 }
4098 }
4099 }
4100
4101 /// lane-dpm1: the 128x128-INTRA-inside-an-INTER-frame chroma context gate.
4102 /// A 128x128 block codes its chroma as four TX_32X32 units, one per 64x64
4103 /// mu chunk, and libaom stamps the coefficient context PER UNIT. The two
4104 /// INTER mu-chunk sites set `mu_chroma` so the block tail re-stamps the
4105 /// four units in mu order; the INTRA-in-inter site did not, so the
4106 /// whole-block record left every unit carrying the TOP-LEFT unit's level.
4107 /// The next block then read its `txb_skip` off ctx 11 where libaom reads
4108 /// ctx 10 (class `override-slot-on-one-arm`) -- one symbol on the wrong
4109 /// CDF row, tile desynced, and because the loop-restoration coefficients
4110 /// live in the same tile data the damage showed up as a +-1 luma sample at
4111 /// the TOP of the frame (measured: frame 1, luma sample 66, ours 146 /
4112 /// ffmpeg 145, with 1.7M samples wrong behind it).
4113 ///
4114 /// Source: the repository's own 2160p colour-bar fixture at the native
4115 /// gate's crop (1920x1024 out of the middle), 12 frames, libaom
4116 /// `-cpu-used 6 -crf 45 -g 12` -- the first reference point of
4117 /// `bd_rate_screen_native`'s "bars 2160p" row, which is where the assertion
4118 /// caught it. The gate asserts the tool fired (class
4119 /// `gate-blind-to-feature`) and that every shown frame decodes sample-exact
4120 /// against ffmpeg's own decode.
4121 #[test]
4122 fn a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact() {
4123 const NAME: &str = "a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact";
4124 if !have_ffmpeg() {
4125 eprintln!("SKIP {NAME}: no ffmpeg");
4126 return;
4127 }
4128 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
4129 .join("../../fixtures/video/h264-2160p-23.976-8bit.mp4");
4130 if !clip.exists() {
4131 eprintln!("SKIP {NAME}: the 2160p bars fixture is missing");
4132 return;
4133 }
4134 let (w, h, frames) = (1920usize, 1024usize, 12usize);
4135 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
4136 let src = std::env::temp_dir().join(format!("ec-av1-i128-{}.yuv", std::process::id()));
4137 let load = Command::new("ffmpeg")
4138 .args(["-v", "error", "-y", "-i"])
4139 .arg(&clip)
4140 .args(["-frames:v", &frames.to_string(), "-vf", "crop=1920:1024:960:568"])
4141 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
4142 .arg(&src)
4143 .output()
4144 .expect("ffmpeg failed to run");
4145 assert!(load.status.success(), "{NAME}: {}", String::from_utf8_lossy(&load.stderr));
4146 let out = Command::new("ffmpeg")
4147 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
4148 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
4149 .arg(&src)
4150 .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
4151 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "45", "-f", "obu", "-"])
4152 .stdin(Stdio::null())
4153 .stdout(Stdio::piped())
4154 .stderr(Stdio::piped())
4155 .output()
4156 .expect("ffmpeg failed to run");
4157 let _ = std::fs::remove_file(&src);
4158 if !out.status.success() {
4159 eprintln!(
4160 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
4161 String::from_utf8_lossy(&out.stderr)
4162 );
4163 return;
4164 }
4165 let stream = out.stdout;
4166 let before = crate::decode::intra_128_in_inter_hits();
4167 let ours = decode_stream(&stream).expect("libaom bars stream decodes");
4168 assert!(
4169 crate::decode::intra_128_in_inter_hits() > before,
4170 "{NAME} went blind: no 128-rooted intra block inside an inter frame"
4171 );
4172 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
4173 assert_eq!(ours.len(), frames, "shown frame count");
4174 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
4175 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
4176 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
4177 assert!(
4178 first.is_none(),
4179 "frame {i} plane {plane} differs from ffmpeg at sample {}",
4180 first.unwrap()
4181 );
4182 }
4183 }
4184 }
4185
4186 /// lane-lossless: the refusal became an implementation, so its gate became
4187 /// a DECODE-EXACT one (class `refusal-lifted-without-a-gate`). libaom at
4188 /// `-crf 0` codes `base_q_idx == 0` -- the same lossless frame his
4189 /// screen-capture row gets at `-crf 5` -- where every plane is TX_4X4 with
4190 /// the Walsh-Hadamard transform, no `tx_type` symbol is coded
4191 /// (`read_tx_type`, `decodetxb.c`: "No need to read transform type for
4192 /// lossless mode(qindex==0)") and `is_cfl_allowed` (`blockd.h`) narrows to
4193 /// a BLOCK_4X4 chroma plane block. The gate asserts the stream really is
4194 /// lossless (class `gate-blind-to-feature`), that every KEY frame decodes
4195 /// sample-exact against ffmpeg, and that the still-unimplemented lossless
4196 /// INTER frame is refused BY NAME rather than decoded wrong.
4197 #[test]
4198 fn a_lossless_libaom_key_frame_decodes_sample_exact() {
4199 const NAME: &str = "a_lossless_libaom_key_frame_decodes_sample_exact";
4200 if !have_ffmpeg() {
4201 eprintln!("SKIP {NAME}: no ffmpeg");
4202 return;
4203 }
4204 let (w, h, frames) = (256usize, 128usize, 2usize);
4205 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
4206 for f in 0..frames {
4207 for row in 0..h {
4208 for col in 0..w {
4209 raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8);
4210 }
4211 }
4212 // lane-lossless2: TEXTURED chroma. A flat chroma plane codes one
4213 // `txb_skip` symbol per 4x4 unit with every context at 0, which
4214 // is blind to both the unit ORDER and the per-unit contexts
4215 // (class `gate-blind-to-feature`).
4216 for row in 0..h / 2 {
4217 for col in 0..w / 2 {
4218 raw.push((((col + f) * 11 + row * 5) % 251) as u8);
4219 }
4220 }
4221 for row in 0..h / 2 {
4222 for col in 0..w / 2 {
4223 raw.push(((col * 3 + (row + f) * 17) % 251) as u8);
4224 }
4225 }
4226 }
4227 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
4228 let src = std::env::temp_dir().join(format!("ec-av1-lossless-{}.yuv", std::process::id()));
4229 std::fs::write(&src, &raw).expect("raw source");
4230 let encode = |gop: &str| {
4231 let out = Command::new("ffmpeg")
4232 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
4233 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
4234 .arg(&src)
4235 .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
4236 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"])
4237 .stdin(Stdio::null())
4238 .stdout(Stdio::piped())
4239 .stderr(Stdio::piped())
4240 .output()
4241 .expect("ffmpeg failed to run");
4242 out
4243 };
4244 let out = encode("1");
4245 let _ = std::fs::remove_file(&src);
4246 if !out.status.success() {
4247 eprintln!(
4248 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
4249 String::from_utf8_lossy(&out.stderr)
4250 );
4251 return;
4252 }
4253 let stream = out.stdout;
4254 // Half of the gate: the stream must really carry a lossless frame
4255 // (class `gate-blind-to-feature`).
4256 let mut parser = Av1Parser::new();
4257 let (mut pos, mut lossless) = (0usize, 0usize);
4258 while pos < stream.len() {
4259 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
4260 pos += obu.total_size.max(1);
4261 let header = match &obu.kind {
4262 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
4263 _ => continue,
4264 };
4265 if header.lossless.iter().all(|&l| l) {
4266 lossless += 1;
4267 }
4268 }
4269 assert_eq!(lossless, frames, "{NAME} went blind: libaom coded no lossless key frame at -crf 0");
4270 let ours = decode_stream(&stream).expect("a lossless key-frame stream decodes");
4271 let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
4272 assert_eq!(ours.len(), frames, "{NAME}: frame count");
4273 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
4274 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
4275 .iter()
4276 .enumerate()
4277 {
4278 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
4279 assert_eq!(bad, 0, "{NAME}: frame {i} plane {plane}: {bad} samples differ");
4280 }
4281 }
4282 }
4283
4284 /// lane-lossless2: the refusal `a_lossless_inter_frame_is_refused_by_name`
4285 /// pinned became an implementation, so its gate became a DECODE-EXACT one
4286 /// (class `refusal-lifted-without-a-gate`). A lossless INTER frame codes
4287 /// its chroma plane as 4x4 transform units, plane-major inside each 64x64
4288 /// mu chunk (libaom `read_tx_size` returns TX_4X4 for every plane under
4289 /// `xd->lossless[..]`, and `decode_token_recon_block` walks
4290 /// `for (plane..) for (blk_row..) for (blk_col..)`), which is what
4291 /// `decode::read_inter_chroma_lossless` reads. The source carries TEXTURED
4292 /// CHROMA and real motion on purpose: a flat-chroma source codes one
4293 /// `txb_skip` symbol per unit and is blind to both the unit order and the
4294 /// per-unit contexts (class `gate-blind-to-feature`).
4295 #[test]
4296 fn a_lossless_libaom_inter_frame_decodes_sample_exact() {
4297 const NAME: &str = "a_lossless_libaom_inter_frame_decodes_sample_exact";
4298 if !have_ffmpeg() {
4299 eprintln!("SKIP {NAME}: no ffmpeg");
4300 return;
4301 }
4302 // (w, h, frames, gop, bit depth, 128-superblock, screen content)
4303 // lane-lossless2: the SCREEN rows carry palette blocks, which is what
4304 // caught the whole-block palette prediction being handed to a 4x4
4305 // chroma unit.
4306 // lane-lossless3: the last row is a screen source with INTER frames --
4307 // the row that caught both of this lane's defects (a skip 8x8 leaf
4308 // restoring the previous block's luma level band over the zeros
4309 // `av1_reset_entropy_context` writes, and a rect sub-8x8 INTRA leaf
4310 // reading one TX_4X8 unit where a lossless frame codes two TX_4X4).
4311 let cases: [(usize, usize, usize, &str, u32, bool, bool); 7] = [
4312 (256, 128, 8, "4", 8, false, false),
4313 (192, 96, 6, "3", 10, false, false),
4314 (320, 192, 6, "3", 8, false, false),
4315 (256, 256, 4, "2", 8, true, false),
4316 (320, 192, 2, "1", 8, false, true),
4317 (640, 384, 2, "1", 8, false, true),
4318 (640, 384, 6, "3", 8, false, true),
4319 ];
4320 for &(w, h, frames, gop, depth, sb128, screen) in &cases {
4321 let tag = format!(
4322 "{w}x{h} {depth}-bit gop {gop}{}{}",
4323 if sb128 { " sb128" } else { "" },
4324 if screen { " screen" } else { "" }
4325 );
4326 let mut raw: Vec<u8> = Vec::new();
4327 let put = |v: u32, raw: &mut Vec<u8>| {
4328 if depth == 10 {
4329 raw.extend_from_slice(&((v * 4) as u16).to_le_bytes());
4330 } else {
4331 raw.push(v as u8);
4332 }
4333 };
4334 // A screen source is a few flat colours in 16x16 tiles plus
4335 // 1-px text-like rows -- what makes libaom code palette blocks.
4336 const PAL: [u32; 8] = [16, 60, 110, 145, 180, 210, 235, 128];
4337 for f in 0..frames {
4338 for row in 0..h {
4339 for col in 0..w {
4340 let v = if screen {
4341 if row % 7 == 0 && col % 3 == 0 {
4342 if (col / 3 + row + f) % 2 == 1 { 16 } else { 235 }
4343 } else {
4344 PAL[((col + 4 * f) / 16 + row / 16) % PAL.len()]
4345 }
4346 } else {
4347 (((col + 2 * f) * 7 + row * 13) % 251) as u32
4348 };
4349 put(v, &mut raw);
4350 }
4351 }
4352 for plane in 0..2usize {
4353 for row in 0..h / 2 {
4354 for col in 0..w / 2 {
4355 let v = if screen {
4356 PAL[((col + 2 * f) / 8 + row / 8 + plane) % PAL.len()]
4357 } else if plane == 0 {
4358 (((col + f) * 11 + row * 5) % 251) as u32
4359 } else {
4360 ((col * 3 + (row + f) * 17) % 251) as u32
4361 };
4362 put(v, &mut raw);
4363 }
4364 }
4365 }
4366 }
4367 let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
4368 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
4369 let src = std::env::temp_dir()
4370 .join(format!("ec-av1-lossless2-{}-{w}x{h}-{depth}.yuv", std::process::id()));
4371 std::fs::write(&src, &raw).expect("raw source");
4372 let mut cmd = Command::new("ffmpeg");
4373 cmd.args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", pix])
4374 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
4375 .arg(&src)
4376 .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
4377 .args(["-pix_fmt", pix, "-cpu-used", "6", "-b:v", "0", "-crf", "0"]);
4378 if sb128 {
4379 cmd.args(["-aom-params", "sb-size=128"]);
4380 }
4381 if screen {
4382 cmd.args(["-aom-params", "tune-content=screen"]);
4383 }
4384 let out = cmd
4385 .args(["-f", "obu", "-"])
4386 .stdin(Stdio::null())
4387 .stdout(Stdio::piped())
4388 .stderr(Stdio::piped())
4389 .output()
4390 .expect("ffmpeg failed to run");
4391 let _ = std::fs::remove_file(&src);
4392 if !out.status.success() {
4393 eprintln!(
4394 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
4395 String::from_utf8_lossy(&out.stderr)
4396 );
4397 return;
4398 }
4399 let stream = out.stdout;
4400 // The stream must really be lossless AND really carry inter frames
4401 // (class `gate-blind-to-feature`).
4402 let mut parser = Av1Parser::new();
4403 let (mut pos, mut lossless, mut inters) = (0usize, 0usize, 0usize);
4404 while pos < stream.len() {
4405 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
4406 pos += obu.total_size.max(1);
4407 let header = match &obu.kind {
4408 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
4409 _ => continue,
4410 };
4411 if header.lossless.iter().all(|&l| l) {
4412 lossless += 1;
4413 }
4414 if header.frame_type == FrameType::Inter {
4415 inters += 1;
4416 }
4417 }
4418 assert!(lossless >= frames, "{NAME} [{tag}] went blind: {lossless} lossless frames");
4419 assert!(
4420 screen || inters > 0,
4421 "{NAME} [{tag}] went blind: no inter frame at gop {gop}"
4422 );
4423 let ours = decode_stream(&stream)
4424 .unwrap_or_else(|e| panic!("{NAME} [{tag}]: a lossless inter stream decodes: {e}"));
4425 let refs = if depth == 10 {
4426 ffmpeg_decode_sequence_10bit(&stream, w, h, frames)
4427 } else {
4428 ffmpeg_decode_sequence(&stream, w, h, frames)
4429 };
4430 assert_eq!(ours.len(), frames, "{NAME} [{tag}]: frame count");
4431 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
4432 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
4433 .iter()
4434 .enumerate()
4435 {
4436 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
4437 assert_eq!(bad, 0, "{NAME} [{tag}]: frame {i} plane {plane}: {bad} samples differ");
4438 }
4439 }
4440 }
4441 }
4442
4443 /// lane-dkey: the palette-neighbour-band gate. A palette-Y block's size and
4444 /// colours used to stay standing in the mi-granular above/left bands after a
4445 /// sub-8x8 group was decoded next to it -- the sub-8x8 readers published
4446 /// skip/lf/mode state but no palette state, while libaom's mi grid carries
4447 /// `palette_size == 0` in exactly those cells (`av1_allow_palette` needs
4448 /// BLOCK_8X8 and up). The next intra block then read `palette_y_mode` off
4449 /// CDF row 1 where libaom reads row 0 (class `cdf-row-held-constant`),
4450 /// decoded a palette libaom never coded, and skipped the `use_filter_intra`
4451 /// symbol a palette block has none of: one symbol short, tile desynced.
4452 ///
4453 /// Measured on the instrumented aomdec at KEY-frame block mi(76,88) of this
4454 /// very stream (`EC_PALSYN_AOM ... ctx=0 y=0` against our `mode_ctx=1`).
4455 /// Without the fix every one of the 12 frames differs from ffmpeg's decode
4456 /// from luma sample 491904 on.
4457 ///
4458 /// The source is SYNTHETIC (no film sample lives in `fixtures`): the dark,
4459 /// near-flat background libaom's own screen-content detector counts as
4460 /// screen content (2..=4 distinct luma values per 16x16 block), which is
4461 /// what turns palette on, plus one textured patch at a HALF-PEL position on
4462 /// half the frames so the encoder splits that region down to 4x4 groups
4463 /// beside its palette blocks.
4464 #[test]
4465 fn a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact() {
4466 const NAME: &str =
4467 "a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact";
4468 if !have_ffmpeg() {
4469 eprintln!("SKIP {NAME}: no ffmpeg");
4470 return;
4471 }
4472 let (w, h, frames) = (1920usize, 1024usize, 12usize);
4473 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
4474 for f in 0..frames {
4475 let mut y = vec![0u8; w * h];
4476 for row in 0..h {
4477 for col in 0..w {
4478 y[row * w + col] =
4479 16 + ((col / 32 + row / 32) % 5) as u8 + ((col / 4 + row / 4) % 3) as u8;
4480 }
4481 }
4482 // 2.5 px per pair of frames: integer on one pair, half a pixel off
4483 // on the next (linear interpolation), so the patch's edges land
4484 // mid-sample and the encoder splits there.
4485 let x0 = 200.0 + 2.5 * (f / 2) as f64;
4486 let (fx, ix) = (x0.fract(), x0.floor() as usize);
4487 for row in 300..428 {
4488 for col in 0..192 {
4489 let tex = |u: f64| -> f64 {
4490 let v = (row - 300) as f64;
4491 30.0 + 100.0 * (0.5 + 0.5 * ((u * 0.35).sin() * (v * 0.21).cos()))
4492 };
4493 let s = tex(col as f64) * (1.0 - fx) + tex(col as f64 - 1.0) * fx;
4494 y[row * w + ix + col] = s.round().clamp(0.0, 255.0) as u8;
4495 }
4496 }
4497 raw.extend_from_slice(&y);
4498 raw.extend(std::iter::repeat_n(128u8, w * h / 2));
4499 }
4500 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
4501 let src = std::env::temp_dir().join(format!("ec-av1-palsub8-{}.yuv", std::process::id()));
4502 std::fs::write(&src, &raw).expect("raw source");
4503 let out = Command::new("ffmpeg")
4504 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
4505 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
4506 .arg(&src)
4507 .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
4508 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "35", "-f", "obu", "-"])
4509 .stdin(Stdio::null())
4510 .stdout(Stdio::piped())
4511 .stderr(Stdio::piped())
4512 .output()
4513 .expect("ffmpeg failed to run");
4514 let _ = std::fs::remove_file(&src);
4515 if !out.status.success() {
4516 eprintln!(
4517 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
4518 String::from_utf8_lossy(&out.stderr)
4519 );
4520 return;
4521 }
4522 let stream = out.stdout;
4523 let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
4524 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
4525 assert_eq!(ours.len(), frames, "{NAME}: shown frame count");
4526 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
4527 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
4528 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
4529 assert!(
4530 first.is_none(),
4531 "{NAME}: frame {i} plane {plane} differs from ffmpeg at sample {}",
4532 first.unwrap()
4533 );
4534 }
4535 }
4536 }
4537
4538 /// Hardened past the report-only test above: a real libaom-av1 gradients
4539 /// stream, pinned deterministic (`gradients`' own `seed=`, plus
4540 /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search
4541 /// cannot pick a different mode set run to run) and with CDEF turned off
4542 /// (this decoder's tile path never applies that in-loop filter -- see
4543 /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on
4544 /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's
4545 /// `-enable-cdef 0` keeps this fixture out of that gap rather than this
4546 /// test working around it). Asserts pixel-exact against ffmpeg's own
4547 /// decode of the identical bytes, not just "decoded without error".
4548 #[test]
4549 fn a_real_libaom_gradients_stream_decodes_pixel_exact() {
4550 if !have_ffmpeg() {
4551 eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg");
4552 return;
4553 }
4554 let (width, height) = (64, 64);
4555 let stream = libaom_encode_with(
4556 &gradients_source(42, width, height, "rate=1"),
4557 width,
4558 height,
4559 15,
4560 &[
4561 "-threads",
4562 "1",
4563 "-row-mt",
4564 "0",
4565 "-tile-columns",
4566 "0",
4567 "-tile-rows",
4568 "0",
4569 "-enable-cdef",
4570 "0",
4571 ],
4572 )
4573 .expect("ffmpeg encode");
4574 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
4575 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4576 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
4577 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
4578 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
4579 }
4580
4581 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at
4582 /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single*
4583 /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB
4584 /// is never CFL-eligible itself, only its <=32x32 partitions, and
4585 /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search
4586 /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed
4587 /// lane-av1real r2), so no fixture at that size exercises CfL at all.
4588 /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and
4589 /// lane-av1real r2 found `gradients` there reliably selects
4590 /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there
4591 /// stays DC. Proves the CfL port this round added, not just DC-chroma
4592 /// decode: pixel-exact against ffmpeg's own decode, not just "decoded".
4593 ///
4594 #[test]
4595 fn a_real_libaom_cfl_stream_decodes_pixel_exact() {
4596 if !have_ffmpeg() {
4597 eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg");
4598 return;
4599 }
4600 let (width, height) = (32, 32);
4601 let stream = libaom_encode_with(
4602 &gradients_source(42, width, height, "rate=1"),
4603 width,
4604 height,
4605 15,
4606 &[
4607 "-threads",
4608 "1",
4609 "-row-mt",
4610 "0",
4611 "-tile-columns",
4612 "0",
4613 "-tile-rows",
4614 "0",
4615 "-enable-cdef",
4616 "0",
4617 ],
4618 )
4619 .expect("ffmpeg encode");
4620 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
4621 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4622 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
4623 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
4624 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
4625 }
4626
4627 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
4628 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
4629 /// proves `apply_cdef` itself, not just that this decoder still works
4630 /// when the filter never fires. Gradient content at a low crf reliably
4631 /// gives libaom something to dering. If a run happens to land on
4632 /// `cdef_bits > 0` (per-64x64 `cdef_idx`, still unimplemented -- see the
4633 /// refusal in `decode_stream`) the stream is skipped rather than failed:
4634 /// that gap is named by the refusal's own error text, not silently
4635 /// swallowed here.
4636 #[test]
4637 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
4638 if !have_ffmpeg() {
4639 eprintln!(
4640 "SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: no ffmpeg"
4641 );
4642 return;
4643 }
4644 let (width, height) = (64, 64);
4645 let stream = libaom_encode_with(
4646 &gradients_source(42, width, height, "rate=1"),
4647 width,
4648 height,
4649 30,
4650 &[
4651 "-threads",
4652 "1",
4653 "-row-mt",
4654 "0",
4655 "-tile-columns",
4656 "0",
4657 "-tile-rows",
4658 "0",
4659 ],
4660 )
4661 .expect("ffmpeg encode");
4662 match decode_stream(&stream) {
4663 Ok(frames) => {
4664 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4665 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (CDEF on)");
4666 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (CDEF on)");
4667 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (CDEF on)");
4668 }
4669 Err(e) => {
4670 eprintln!("SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: {e}");
4671 }
4672 }
4673 }
4674
4675 /// Path to a real `aomenc` build carrying the reference options this
4676 /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`,
4677 /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old
4678 /// to expose `enable-tx-size-search`/`loopfilter-control` through its
4679 /// own `-aom-params` passthrough (probed live: "Cannot find aom
4680 /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]
4681 /// shells out to the standalone binary instead of ffmpeg's libaom-av1
4682 /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the
4683 /// default dev-build path; the test skips (not fails) when neither this
4684 /// nor `ffmpeg` is present.
4685 fn aomenc_path() -> std::path::PathBuf {
4686 if let Some(p) = std::env::var_os("EC_AV1_AOMENC") {
4687 return std::path::PathBuf::from(p);
4688 }
4689 // The oracle used to live only under `/tmp`, which this box's tmpfs
4690 // guard reclaims -- when it did, all 20 aomenc gates below went
4691 // silently vacuous (SKIP, suite still green). The durable location
4692 // is provisioned by `scripts/build-aom-oracle.sh`; the `/tmp` path
4693 // stays last as a legacy fallback.
4694 let mut candidates = Vec::new();
4695 if let Some(home) = std::env::var_os("HOME") {
4696 candidates.push(std::path::PathBuf::from(&home).join(".cache/aom-oracle/build/aomenc"));
4697 }
4698 candidates.push("/tmp/libaom-src/build/encoder/aomenc".into());
4699 candidates
4700 .iter()
4701 .find(|p| p.is_file())
4702 .cloned()
4703 .unwrap_or_else(|| candidates.remove(0))
4704 }
4705
4706 /// Whether the aomenc oracle is present. Absence normally SKIPs (a
4707 /// checkout without the oracle should still run the rest of the suite),
4708 /// but `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure so a batch
4709 /// run cannot report green off 20 skipped gates.
4710 /// Where a pinned stream lives. `fixtures/` is a symlink to a durable
4711 /// directory outside the repo, so a pin captured in one session is still
4712 /// there in the next; a session scratchpad is not (tmpfs reaps it, and
4713 /// four pins were silently dead because of that).
4714 fn pin_dir() -> std::path::PathBuf {
4715 if let Some(p) = std::env::var_os("EC_AV1_PIN_DIR") {
4716 return std::path::PathBuf::from(p);
4717 }
4718 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
4719 .join("../../fixtures")
4720 .canonicalize()
4721 .unwrap_or_else(|_| std::path::PathBuf::from("fixtures"))
4722 }
4723
4724 fn have_aomenc() -> bool {
4725 let present = aomenc_path().is_file();
4726 assert!(
4727 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
4728 "EC_AV1_REQUIRE_AOMENC is set but no aomenc at {} -- run scripts/build-aom-oracle.sh",
4729 aomenc_path().display()
4730 );
4731 present
4732 }
4733
4734 /// The instrumented `aomdec` beside the `aomenc` oracle
4735 /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`).
4736 fn aomdec_path() -> std::path::PathBuf {
4737 if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") {
4738 return std::path::PathBuf::from(p);
4739 }
4740 aomenc_path().with_file_name("aomdec")
4741 }
4742
4743 /// Decodes `stream` with both this decoder and the instrumented oracle
4744 /// `aomdec`, and compares EVERY decoded frame in DECODE order --
4745 /// including the hidden (`show_frame == 0`) alt-ref frames no other gate
4746 /// in this repo can see, because `decode_stream` only pushes shown
4747 /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames
4748 /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces
4749 /// only as drift on some later shown frame, if at all).
4750 ///
4751 /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it
4752 /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in
4753 /// `decode_stream`, the oracle's in rung 12 of
4754 /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as
4755 /// u16 LE. Returns `(frames_decoded, hidden_frames)`.
4756 fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) {
4757 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
4758 let _ = std::fs::remove_dir_all(&dir);
4759 std::fs::create_dir_all(&dir).expect("scratch dir");
4760 let obu = dir.join("in.obu");
4761 std::fs::write(&obu, stream).expect("writing the stream");
4762 let aom_prefix = dir.join("aom");
4763 let out = Command::new(aomdec_path())
4764 .args(["--codec=av1", "-o"])
4765 .arg(dir.join("out.y4m"))
4766 .arg(&obu)
4767 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
4768 .stdin(Stdio::null())
4769 .stdout(Stdio::piped())
4770 .stderr(Stdio::piped())
4771 .output()
4772 .expect("aomdec failed to run");
4773 assert!(
4774 out.status.success(),
4775 "{name}: the oracle aomdec refused the stream: {}",
4776 String::from_utf8_lossy(&out.stderr)
4777 );
4778 let count_dumps = |prefix: &std::path::Path| -> usize {
4779 let mut n = 0usize;
4780 while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
4781 n += 1;
4782 }
4783 n
4784 };
4785 let oracle_frames = count_dumps(&aom_prefix);
4786 assert!(
4787 oracle_frames > 0,
4788 "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
4789 scripts/instrument-aom-oracle.sh is missing from {}",
4790 aomdec_path().display()
4791 );
4792 let ours_prefix = dir.join("ours");
4793 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
4794 let decoded = decode_stream(stream);
4795 set_final_dump_prefix(None);
4796 let shown = decoded
4797 .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"))
4798 .len();
4799 let our_frames = count_dumps(&ours_prefix);
4800 assert_eq!(
4801 our_frames, oracle_frames,
4802 "{name}: decoded {our_frames} frames in decode order, the oracle decoded \
4803 {oracle_frames}"
4804 );
4805 for i in 0..oracle_frames {
4806 let want =
4807 std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
4808 let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
4809 assert_eq!(
4810 got.len(),
4811 want.len(),
4812 "{name}: decode-order frame {i} is {} bytes, the oracle's is {}",
4813 got.len(),
4814 want.len()
4815 );
4816 if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) {
4817 let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
4818 panic!(
4819 "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \
4820 hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \
4821 bytes differ -- stream pinned at {}",
4822 oracle_frames - shown,
4823 got[at],
4824 want[at],
4825 obu.display()
4826 );
4827 }
4828 }
4829 let hidden = oracle_frames - shown;
4830 let _ = std::fs::remove_dir_all(&dir);
4831 (oracle_frames, hidden)
4832 }
4833
4834 /// lane-hidden r2: the `--arnr-maxframes=0` SECOND ARM of an existing
4835 /// gate -- the gate's own recipe is never changed, this re-encodes the
4836 /// same fixture with libaom's temporal alt-ref filter switched off and
4837 /// runs [`decode_all_frames_vs_oracle`] on the result. Measured: with
4838 /// the filter at its default EVERY alt-ref recipe in this file emits
4839 /// ZERO hidden frames (the candidates are filtered away), so the
4840 /// hidden-frame compare on the gate's own stream is vacuous; this arm
4841 /// is what actually puts `show_frame == 0` frames on the wire.
4842 ///
4843 /// Runs at most once per gate name per process (the loop gates sweep
4844 /// dozens of attempts and each arm costs a full encode + two decodes).
4845 /// A stream this decoder refuses BY NAME skips the arm -- the arm is
4846 /// about hidden frames, not about that capability gap -- while a pixel
4847 /// mismatch is a hard failure raised inside the compare.
4848 fn hidden_arnr_arm(name: &str, y4m: &[u8], args: &[&str]) -> Option<(usize, usize)> {
4849 static ARMED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
4850 std::sync::OnceLock::new();
4851 if !ARMED
4852 .get_or_init(Default::default)
4853 .lock()
4854 .unwrap()
4855 .insert(name.to_string())
4856 {
4857 return None;
4858 }
4859 let mut arm: Vec<&str> = vec!["--arnr-maxframes=0"];
4860 arm.extend_from_slice(args);
4861 let mut child = Command::new(aomenc_path())
4862 .args(&arm)
4863 .stdin(Stdio::piped())
4864 .stdout(Stdio::piped())
4865 .stderr(Stdio::piped())
4866 .spawn()
4867 .expect("aomenc failed to start");
4868 child
4869 .stdin
4870 .take()
4871 .expect("aomenc stdin")
4872 .write_all(y4m)
4873 .expect("writing y4m to aomenc");
4874 let out = child.wait_with_output().expect("aomenc failed to run");
4875 assert!(
4876 out.status.success(),
4877 "{name} HIDDEN-ARM: aomenc refused its own recipe plus --arnr-maxframes=0: {}",
4878 String::from_utf8_lossy(&out.stderr)
4879 );
4880 let stream = out.stdout;
4881 match decode_stream(&stream) {
4882 Err(e) => {
4883 let msg = e.to_string();
4884 assert!(
4885 msg.contains("unsupported"),
4886 "{name} HIDDEN-ARM failed outright: {msg}"
4887 );
4888 eprintln!("{name} HIDDEN-ARM: skipped on a named refusal: {msg}");
4889 None
4890 }
4891 Ok(_) => Some(decode_all_frames_vs_oracle(&stream, &format!("{name}-arnr0"))),
4892 }
4893 }
4894
4895
4896 /// The repo's first hidden-frame pixel gate. Every other aomenc gate
4897 /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and
4898 /// both sides emit SHOWN frames only -- so an alt-ref frame that is
4899 /// decoded, stored into a reference slot and never displayed was, until
4900 /// this gate, never compared to anything (class
4901 /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the
4902 /// default `--lag-in-frames`, so they are full of exactly these frames.
4903 ///
4904 /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc
4905 /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's
4906 /// temporal filter on, this fixture's alt-ref candidates get filtered
4907 /// away and the encoder emits ZERO hidden frames (measured: 0 hidden
4908 /// with the filter on, 3 with it off), which would have made the gate
4909 /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so
4910 /// a recipe that stops producing hidden frames fails rather than skips.
4911 #[test]
4912 fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() {
4913 const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact";
4914 let _gate_lock = lock_gate_counters();
4915 if !have_ffmpeg() {
4916 eprintln!("SKIP {NAME}: no ffmpeg");
4917 return;
4918 }
4919 if !have_aomenc() {
4920 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4921 return;
4922 }
4923 for bit_depth in [8u32, 10u32] {
4924 let (width, height, frames) = (64usize, 64usize, 40usize);
4925 let duration = frames as f64 / 25.0;
4926 let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25");
4927 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
4928 let y4m = Command::new("ffmpeg")
4929 .args([
4930 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
4931 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
4932 ])
4933 .stdin(Stdio::null())
4934 .stdout(Stdio::piped())
4935 .stderr(Stdio::piped())
4936 .output()
4937 .expect("ffmpeg failed to run");
4938 assert!(
4939 y4m.status.success(),
4940 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
4941 String::from_utf8_lossy(&y4m.stderr)
4942 );
4943 let depth_arg = format!("--bit-depth={bit_depth}");
4944 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
4945 let mut child = Command::new(aomenc_path())
4946 .args([
4947 // lane-defon r1: the repo's only gate that decodes hidden
4948 // frames is also the only place a FORWARD KEYFRAME can be
4949 // proven -- a KEY frame with `show_frame == 0`, which is
4950 // exactly the shape this gate already compares in decode
4951 // order. On-values go before the base list (aomenc keeps
4952 // the FIRST occurrence of a repeated flag).
4953 "--enable-fwd-kf=1",
4954 "--fwd-kf-dist=8",
4955 "--codec=av1",
4956 "--passes=1",
4957 "--end-usage=q",
4958 "--cq-level=45",
4959 "--cpu-used=0",
4960 "--threads=1",
4961 "--row-mt=0",
4962 "--kf-max-dist=1000",
4963 "--enable-order-hint=1",
4964 "--auto-alt-ref=1",
4965 "--lag-in-frames=25",
4966 "--arnr-maxframes=0",
4967 &depth_arg,
4968 &input_depth_arg,
4969 // The same tool set every sibling inter gate pins -- the
4970 // open capability gaps (rect/AB partitions, warped/OBMC,
4971 // masked compound, palette, ...) are other lanes' work;
4972 // this gate is about hidden frames, not about them.
4973 "--enable-warped-motion=0",
4974 // OBMC stays off HERE (this gate is about hidden frames);
4975 // the tool's own coverage is the `obmc*` gates and, on a
4976 // 16x8/8x16 leaf, the `--enable-obmc=1` arm of
4977 // `..._with_a_16_level_rect_leaf_...` (lane-inter4 r4).
4978 "--enable-obmc=0",
4979 "--enable-masked-comp=0",
4980 "--enable-interintra-comp=0",
4981 "--enable-onesided-comp=0",
4982 "--enable-interintra-wedge=0",
4983 "--enable-smooth-interintra=0",
4984 "--enable-rect-partitions=0",
4985 "--enable-ab-partitions=0",
4986 "--enable-1to4-partitions=0",
4987 "--enable-filter-intra=0",
4988 "--enable-smooth-intra=0",
4989 "--enable-paeth-intra=0",
4990 "--enable-directional-intra=0",
4991 "--enable-angle-delta=0",
4992 "--enable-tx-size-search=0",
4993 "--enable-cdef=0",
4994 "--enable-restoration=0",
4995 "--max-partition-size=32",
4996 "--min-partition-size=32",
4997 "--enable-palette=0",
4998 "--enable-intrabc=0",
4999 "--enable-cfl-intra=0",
5000 "--enable-ref-frame-mvs=0",
5001 "--obu",
5002 "-o",
5003 "-",
5004 "-",
5005 ])
5006 .stdin(Stdio::piped())
5007 .stdout(Stdio::piped())
5008 .stderr(Stdio::piped())
5009 .spawn()
5010 .expect("aomenc failed to start");
5011 child
5012 .stdin
5013 .take()
5014 .expect("aomenc stdin")
5015 .write_all(&y4m.stdout)
5016 .expect("writing y4m to aomenc");
5017 let out = child.wait_with_output().expect("aomenc failed to run");
5018 assert!(
5019 out.status.success(),
5020 "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}",
5021 String::from_utf8_lossy(&out.stderr)
5022 );
5023 let stream = out.stdout;
5024 let fwd_kf_before = crate::decode::fwd_kf_hits();
5025 let (total, hidden) =
5026 decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit"));
5027 let fwd_kf = crate::decode::fwd_kf_hits() - fwd_kf_before;
5028 assert!(
5029 hidden >= 2,
5030 "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \
5031 {total} decoded -- the gate would be vacuous (class \
5032 gate-blind-to-hidden-frames)"
5033 );
5034 // lane-defon r1: `--enable-fwd-kf=1` is spelled on this recipe, so
5035 // a KEY frame with `show_frame == 0` must actually have been
5036 // decoded -- otherwise the on-value proves nothing.
5037 assert!(
5038 fwd_kf > 0,
5039 "{NAME}: the {bit_depth}-bit recipe decoded {total} frames ({hidden} hidden) but \
5040 zero forward keyframes -- --enable-fwd-kf=1 --fwd-kf-dist=8 never reached the \
5041 bitstream"
5042 );
5043 eprintln!(
5044 "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, {fwd_kf} \
5045 forward keyframes, all pixel-exact vs the oracle in decode order"
5046 );
5047 }
5048 }
5049
5050 /// A real `aomenc` filter-intra fixture: every other intra mode disabled
5051 /// (smooth/paeth/directional/angle-delta) and
5052 /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
5053 /// <=32x32 bound means `use_filter_intra` never reads at all, spec
5054 /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter
5055 /// intra on top -- `--loopfilter-control=0` is required too: this
5056 /// decoder has no in-loop deblocking filter at all, and libaom's default
5057 /// (on) smooths every block-boundary column, which first looked like a
5058 /// filter-intra math bug (mismatches straddling the 32-pixel block
5059 /// seam) until the recipe without it round-tripped byte-exact. Checks
5060 /// [`decode::filter_intra_hits`] actually moved (a process-global
5061 /// counter, so before/after rather than an absolute value) to prove the
5062 /// symbol fired, then pixel-exactness against ffmpeg's own decode of the
5063 /// identical bytes on every plane.
5064 #[test]
5065 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
5066 if !have_ffmpeg() {
5067 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no ffmpeg");
5068 return;
5069 }
5070 if !have_aomenc() {
5071 eprintln!(
5072 "SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no aomenc at {}",
5073 aomenc_path().display()
5074 );
5075 return;
5076 }
5077 let (width, height) = (64usize, 64usize);
5078 // Recipe-search hooks: with the encoder pinned to one thread the
5079 // stream is a deterministic function of (seed, cq), so a firing recipe
5080 // can be searched for without a rebuild.
5081 let fi_seed: u32 = std::env::var("EC_FI_SEED")
5082 .ok()
5083 .and_then(|v| v.parse().ok())
5084 .unwrap_or(42);
5085 let fi_source = gradients_source(fi_seed, 64, 64, "duration=0.04:rate=25");
5086 let fi_cq = std::env::var("EC_FI_CQ").unwrap_or_else(|_| "40".to_string());
5087 let fi_cq_arg = format!("--cq-level={fi_cq}");
5088 let y4m = Command::new("ffmpeg")
5089 .args([
5090 "-v",
5091 "error",
5092 "-f",
5093 "lavfi",
5094 "-i",
5095 &fi_source,
5096 "-pix_fmt",
5097 "yuv420p",
5098 "-f",
5099 "yuv4mpegpipe",
5100 "-",
5101 ])
5102 .stdin(Stdio::null())
5103 .stdout(Stdio::piped())
5104 .stderr(Stdio::piped())
5105 .output()
5106 .expect("ffmpeg failed to run");
5107 assert!(
5108 y4m.status.success(),
5109 "ffmpeg refused to generate the y4m fixture: {}",
5110 String::from_utf8_lossy(&y4m.stderr)
5111 );
5112 let mut child = Command::new(aomenc_path())
5113 .args([
5114 "--codec=av1",
5115 "--passes=1",
5116 "--end-usage=q",
5117 &fi_cq_arg,
5118 "--cpu-used=0",
5119 // Every sibling gate pins these; this one did not, and a
5120 // multi-threaded aomenc is not deterministic, so each run
5121 // encoded a slightly different stream and the gate flaked
5122 // against whichever features that run happened to pick.
5123 // Pinning them makes seed 42 mean one stream (class
5124 // `parallel-flake-is-attempt-selection`).
5125 "--threads=1",
5126 "--row-mt=0",
5127 "--enable-filter-intra=1",
5128 "--enable-smooth-intra=0",
5129 "--enable-paeth-intra=0",
5130 "--enable-directional-intra=0",
5131 "--enable-angle-delta=0",
5132 "--enable-tx-size-search=0",
5133 "--enable-cdef=0",
5134 "--max-partition-size=32",
5135 "--loopfilter-control=0",
5136 "--enable-palette=0",
5137 "--enable-intrabc=0",
5138 "--obu",
5139 "-o",
5140 "-",
5141 "-",
5142 ])
5143 .stdin(Stdio::piped())
5144 .stdout(Stdio::piped())
5145 .stderr(Stdio::piped())
5146 .spawn()
5147 .expect("aomenc failed to start");
5148 child
5149 .stdin
5150 .take()
5151 .expect("aomenc stdin")
5152 .write_all(&y4m.stdout)
5153 .expect("writing the y4m fixture to aomenc");
5154 let out = child.wait_with_output().expect("aomenc failed to run");
5155 assert!(
5156 out.status.success(),
5157 "aomenc refused the fixture: {}",
5158 String::from_utf8_lossy(&out.stderr)
5159 );
5160 let stream = out.stdout;
5161 let before = decode::filter_intra_hits();
5162 // `screen_content_tools_determination` (libaom encoder_utils.c) is a
5163 // real internal trial-encode/PSNR comparison, not a flag this CLI
5164 // exposes a knob for -- on this flat gradient fixture it lands on
5165 // `allow_screen_content_tools=0` most runs but occasionally trips
5166 // over its 0.9 dB threshold the other way even with palette/intrabc
5167 // both disabled. That is a genuine separate gap (`decode_stream`
5168 // never reads `intrabc`/`palette_mode_info`), not a filter-intra
5169 // regression, so it is skipped here exactly as
5170 // `a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact`
5171 // above skips its own still-unsupported-gap runs.
5172 let frames = match decode_stream(&stream) {
5173 Ok(frames) => frames,
5174 Err(e) => {
5175 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: {e}");
5176 return;
5177 }
5178 };
5179 assert!(
5180 decode::filter_intra_hits() > before,
5181 "use_filter_intra never fired decoding this stream"
5182 );
5183 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
5184 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
5185 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
5186 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
5187 }
5188
5189 /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
5190 /// (SMPTE colour bars -- a handful of large flat luma regions, exactly
5191 /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s
5192 /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant
5193 /// value, so `DC_PRED` already nails every chroma block with zero
5194 /// residual and the encoder's own RD never has a reason to spend bits on
5195 /// a *UV* palette too (a real symbol this decoder still refuses --
5196 /// lane-palette r3's own scope is Y only). `smptebars` has no seed to
5197 /// vary, so the fixture is deterministic by construction; hashed twice
5198 /// below to prove it rather than assert it. `--enable-rect-partitions=0`
5199 /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the
5200 /// rect-strip screen-content refusal at `read_intra_mode_rect`
5201 /// (decode.rs ~2226) -- that refusal is this lane's own next milestone,
5202 /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the
5203 /// sibling-lane facts this charter paid for: a single 64x64 frame is one
5204 /// superblock either way, but pinning them keeps the recipe identical to
5205 /// every other gate in this file. HARD-asserts
5206 /// [`decode::palette_hits`] moved -- a stream that never reads a real
5207 /// palette block would refuse (or not) by construction without proving
5208 /// this milestone at all.
5209 ///
5210 /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed
5211 /// pixels did not match ffmpeg's decode of the same bytes even though
5212 /// every symbol read by `decode_color_index_map` checked line-for-line
5213 /// against the oracle and matched. r6's range trace (`compare-range-not-tell`)
5214 /// pinned the real cause: `decode_color_index_map` was called from the
5215 /// wrong syntax position -- inline right after the Y colours, instead of
5216 /// after the whole mode-info read (UV palette mode_info + `filter_intra`,
5217 /// `av1_visit_palette`'s real call order). r7 ported the UV palette
5218 /// mode_info read and moved the colour-index-map decode after
5219 /// `filter_intra`; this gate now asserts a real pixel match instead of
5220 /// the old named refusal.
5221 #[test]
5222 fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() {
5223 const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact";
5224 if !have_ffmpeg() {
5225 eprintln!("SKIP {NAME}: no ffmpeg");
5226 return;
5227 }
5228 if !have_aomenc() {
5229 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5230 return;
5231 }
5232 let source = "smptebars=size=64x64:rate=25";
5233 fn render(source: &str) -> Vec<u8> {
5234 Command::new("ffmpeg")
5235 .args([
5236 "-v",
5237 "error",
5238 "-f",
5239 "lavfi",
5240 "-i",
5241 source,
5242 "-vf",
5243 "hue=s=0",
5244 "-pix_fmt",
5245 "yuv420p",
5246 "-t",
5247 "0.04",
5248 "-f",
5249 "yuv4mpegpipe",
5250 "-",
5251 ])
5252 .stdin(Stdio::null())
5253 .stdout(Stdio::piped())
5254 .stderr(Stdio::piped())
5255 .output()
5256 .expect("ffmpeg failed to run")
5257 .stdout
5258 }
5259 let y4m_a = render(source);
5260 let y4m_b = render(source);
5261 assert_eq!(
5262 y4m_a, y4m_b,
5263 "smptebars must render byte-identical across two runs"
5264 );
5265 let y4m = y4m_a;
5266 let mut child = Command::new(aomenc_path())
5267 .args([
5268 "--codec=av1",
5269 "--passes=1",
5270 "--end-usage=q",
5271 "--cq-level=30",
5272 "--cpu-used=0",
5273 "--threads=1",
5274 "--row-mt=0",
5275 "--sb-size=64",
5276 "--tune-content=screen",
5277 "--enable-palette=1",
5278 "--enable-intrabc=0",
5279 "--enable-rect-partitions=0",
5280 "--enable-ab-partitions=0",
5281 "--enable-1to4-partitions=0",
5282 "--min-partition-size=32",
5283 "--max-partition-size=32",
5284 "--enable-filter-intra=0",
5285 "--enable-smooth-intra=0",
5286 "--enable-paeth-intra=0",
5287 "--enable-directional-intra=0",
5288 "--enable-angle-delta=0",
5289 "--enable-cfl-intra=0",
5290 "--enable-cdef=0",
5291 "--enable-restoration=0",
5292 "--enable-tx-size-search=0",
5293 "--loopfilter-control=0",
5294 "--obu",
5295 "-o",
5296 "-",
5297 "-",
5298 ])
5299 .stdin(Stdio::piped())
5300 .stdout(Stdio::piped())
5301 .stderr(Stdio::piped())
5302 .spawn()
5303 .expect("aomenc failed to start");
5304 child
5305 .stdin
5306 .take()
5307 .expect("aomenc stdin")
5308 .write_all(&y4m)
5309 .expect("writing y4m to aomenc");
5310 let out = child.wait_with_output().expect("aomenc failed to run");
5311 assert!(
5312 out.status.success(),
5313 "aomenc refused the fixture: {}",
5314 String::from_utf8_lossy(&out.stderr)
5315 );
5316 let stream = out.stdout;
5317 let before = decode::palette_hits();
5318 let frames = match decode_stream(&stream) {
5319 Ok(frames) => frames,
5320 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
5321 };
5322 assert!(
5323 decode::palette_hits() > before,
5324 "palette_y_mode never fired decoding this stream -- gate is vacuous"
5325 );
5326 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
5327 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
5328 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
5329 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
5330 }
5331
5332 /// lane-kf900 r3: the palette colour reader at BOTH bit depths.
5333 ///
5334 /// `read_palette_colors_y`/`_uv` (decode.rs, mirroring `decodemv.c:478`
5335 /// and `:509`) size every raw literal they read by the sequence's
5336 /// `bit_depth`: the first colour is `bit_depth` bits, `min_bits` is
5337 /// `bit_depth - 3` (Y/U) or `bit_depth - 4` (V), `range` starts at
5338 /// `1 << bit_depth`, and the clamp/wrap bound is `(1 << bit_depth) - 1`.
5339 /// Ours hardcoded 8, so every 10-bit palette block read TWO BITS TOO FEW
5340 /// per transmitted colour and silently decoded the rest of the tile from
5341 /// the wrong bit position.
5342 ///
5343 /// It was silent because raw literals are EQUIPROBABLE: at the ranges
5344 /// this content reaches an equiprobable read maps the msac range onto
5345 /// itself (62728 -> 31364 -> renormalised 62728), so a cross-decoder
5346 /// RANGE ladder stays bit-identical straight through the miscount and
5347 /// only the decoded VALUE moves. Pinned on a 256x192 10-bit
5348 /// `--cq-level=59` stream whose first block is a 32x16 palette: aomdec's
5349 /// `EC_PAL` ladder and ours agreed on every range and disagreed on the
5350 /// very first colour index (0 vs 1); after the fix all 1024 `EC_PAL`
5351 /// lines of that block match aomdec line for line.
5352 ///
5353 /// The recipe is the 8-bit `..._with_palette_y_...` gate's, with the
5354 /// depth as the only variable, so a failure here is the depth and
5355 /// nothing else. HARD-asserts [`decode::palette_hits`] moved on each arm
5356 /// (a stream with no real palette block would prove nothing) and
5357 /// compares all three planes against ffmpeg's decode of the same bytes.
5358 #[test]
5359 fn a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit() {
5360 const NAME: &str = "a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit";
5361 if !have_ffmpeg() {
5362 eprintln!("SKIP {NAME}: no ffmpeg");
5363 return;
5364 }
5365 if !have_aomenc() {
5366 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5367 return;
5368 }
5369 let (width, height) = (64usize, 64usize);
5370 for depth in [8usize, 10] {
5371 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
5372 let render = || {
5373 Command::new("ffmpeg")
5374 .args([
5375 "-v", "error",
5376 "-f", "lavfi",
5377 "-i", "smptebars=size=64x64:rate=25",
5378 "-vf", "hue=s=0",
5379 "-pix_fmt", pix_fmt,
5380 "-strict", "-1",
5381 "-t", "0.04",
5382 "-f", "yuv4mpegpipe",
5383 "-",
5384 ])
5385 .stdin(Stdio::null())
5386 .stdout(Stdio::piped())
5387 .stderr(Stdio::piped())
5388 .output()
5389 .expect("ffmpeg failed to run")
5390 .stdout
5391 };
5392 let y4m_a = render();
5393 let y4m_b = render();
5394 assert_eq!(
5395 y4m_a, y4m_b,
5396 "{NAME}: smptebars must render byte-identical across two runs at {depth}-bit"
5397 );
5398 let y4m = y4m_a;
5399 let depth_arg = format!("--bit-depth={depth}");
5400 let input_depth_arg = format!("--input-bit-depth={depth}");
5401 let mut child = Command::new(aomenc_path())
5402 .args([
5403 "--codec=av1",
5404 "--passes=1",
5405 "--end-usage=q",
5406 "--cq-level=30",
5407 "--cpu-used=0",
5408 "--threads=1",
5409 "--row-mt=0",
5410 "--sb-size=64",
5411 "--tune-content=screen",
5412 "--enable-palette=1",
5413 "--enable-intrabc=0",
5414 "--enable-rect-partitions=0",
5415 "--enable-ab-partitions=0",
5416 "--enable-1to4-partitions=0",
5417 "--min-partition-size=32",
5418 "--max-partition-size=32",
5419 "--enable-filter-intra=0",
5420 "--enable-smooth-intra=0",
5421 "--enable-paeth-intra=0",
5422 "--enable-directional-intra=0",
5423 "--enable-angle-delta=0",
5424 "--enable-cfl-intra=0",
5425 "--enable-cdef=0",
5426 "--enable-restoration=0",
5427 "--enable-tx-size-search=0",
5428 "--loopfilter-control=0",
5429 "--limit=1",
5430 ])
5431 // Per-arm overrides go AFTER the base recipe: aomenc keeps the
5432 // LAST occurrence of a repeated flag.
5433 .args([&depth_arg, &input_depth_arg])
5434 .args(["--obu", "-o", "-", "-"])
5435 .stdin(Stdio::piped())
5436 .stdout(Stdio::piped())
5437 .stderr(Stdio::piped())
5438 .spawn()
5439 .expect("aomenc failed to start");
5440 child
5441 .stdin
5442 .take()
5443 .expect("aomenc stdin")
5444 .write_all(&y4m)
5445 .expect("writing y4m to aomenc");
5446 let out = child.wait_with_output().expect("aomenc failed to run");
5447 assert!(
5448 out.status.success(),
5449 "{NAME}: aomenc refused the {depth}-bit fixture: {}",
5450 String::from_utf8_lossy(&out.stderr)
5451 );
5452 let stream = out.stdout;
5453 let before = decode::palette_hits();
5454 let frames = match decode_stream(&stream) {
5455 Ok(frames) => frames,
5456 Err(e) => panic!("{NAME}: decode_stream refused the {depth}-bit stream: {e}"),
5457 };
5458 assert!(
5459 decode::palette_hits() > before,
5460 "{NAME}: no real palette block at {depth}-bit -- gate is vacuous"
5461 );
5462 let ffmpeg_frames = if depth == 10 {
5463 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
5464 } else {
5465 ffmpeg_decode_sequence(&stream, width, height, 1)
5466 };
5467 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma at {depth}-bit");
5468 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U at {depth}-bit");
5469 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V at {depth}-bit");
5470 }
5471 }
5472
5473 /// lane-pal8 r1, the gate for a palette on a SQUARE 8x8 LEAF.
5474 ///
5475 /// `read_palette_mode_info` (decodemv.c:567) reads `palette_y_mode` for
5476 /// every `DC_PRED` block whose `av1_get_palette_bsize_ctx`
5477 /// (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`, 0 at 8x8) exists, and
5478 /// `av1_decode_palette_tokens` (decodeframe.c:1135, `av1_visit_palette`)
5479 /// reads the colour-index map after the WHOLE mode-info read. Ours passed
5480 /// `None`/`&[]` from [`decode::decode_leaf8`], reading the mode symbol off
5481 /// CDF row 0 and refusing "a block that actually uses a palette (Y) --
5482 /// reconstruction is out of scope" the moment it fired -- and at 8 bit
5483 /// aomenc palettes SQUARE blocks, so with `--min-partition-size=8` every
5484 /// 8-bit screen-content stream stopped there (lane-kf900 r4's measurement).
5485 ///
5486 /// Sweeps both bit depths x cq 30/40/55 x `--enable-tx-size-search` 0/1 x
5487 /// two lavfi sources (+ a `--tile-columns=1` arm, per the neighbour-map
5488 /// rule: the palette bands are per-mi and tile-guarded). Key frame only
5489 /// (`--limit=1`): the inter frames of these recipes stop on OTHER lanes'
5490 /// open refusals (8x8 inter leaf chroma mode, inter 1:4 partitions).
5491 /// HARD-asserts the 8x8-leaf palette counter moved on the compared arms
5492 /// and that no arm mismatched, in or out of scope.
5493 #[test]
5494 fn a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact() {
5495 const NAME: &str = "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact";
5496 if !have_ffmpeg() {
5497 eprintln!("SKIP {NAME}: no ffmpeg");
5498 return;
5499 }
5500 if !have_aomenc() {
5501 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5502 return;
5503 }
5504 let (width, height) = (128usize, 128usize);
5505 let (mut leaf8_total, mut fired_arms, mut compared, mut frames_compared) =
5506 (0usize, 0u32, 0u32, 0usize);
5507 let (mut out_of_scope, mut out_of_scope_mismatch, mut refusals) = (0u32, 0u32, 0u32);
5508 let (mut sb_strip_total, mut sb_strip_arms) = (0usize, 0u32);
5509 // lane-t900 r34 LIFTED this shape; the counter stays so the gate
5510 // fails loudly if the refusal ever comes back.
5511 let mut sb_strip_refusals = 0u32;
5512 for src in ["testsrc2", "smptebars"] {
5513 for depth in [8usize, 10usize] {
5514 for cq in [30usize, 40, 55] {
5515 for txs in [0usize, 1] {
5516 for tiles in [0usize, 1] {
5517 let arm = format!("{src}-{depth}bit-cq{cq}-txs{txs}-tc{tiles}");
5518 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
5519 let size = format!("{src}=size={width}x{height}:rate=25");
5520 let render = || {
5521 let out = Command::new("ffmpeg")
5522 .args([
5523 "-v", "error", "-f", "lavfi", "-i", &size, "-t", "0.04",
5524 "-pix_fmt", pix_fmt, "-strict", "-1", "-f",
5525 "yuv4mpegpipe", "-",
5526 ])
5527 .stdin(Stdio::null())
5528 .stdout(Stdio::piped())
5529 .stderr(Stdio::piped())
5530 .output()
5531 .expect("ffmpeg failed to run");
5532 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
5533 out.stdout
5534 };
5535 let y4m_a = render();
5536 let y4m_b = render();
5537 assert_eq!(
5538 y4m_a, y4m_b,
5539 "{NAME}: {arm} must render byte-identical across two runs"
5540 );
5541 let y4m = y4m_a;
5542 let depth_arg = format!("--bit-depth={depth}");
5543 let input_depth_arg = format!("--input-bit-depth={depth}");
5544 let cq_arg = format!("--cq-level={cq}");
5545 let txs_arg = format!("--enable-tx-size-search={txs}");
5546 let tiles_arg = format!("--tile-columns={tiles}");
5547 let mut child = Command::new(aomenc_path())
5548 .args([
5549 "--codec=av1",
5550 "--passes=1",
5551 "--end-usage=q",
5552 "--cpu-used=0",
5553 "--threads=1",
5554 "--row-mt=0",
5555 "--lag-in-frames=0",
5556 "--limit=1",
5557 "--sb-size=64",
5558 "--tune-content=screen",
5559 "--enable-palette=1",
5560 "--enable-intrabc=0",
5561 "--min-partition-size=8",
5562 "--enable-cdef=0",
5563 "--enable-restoration=0",
5564 "--loopfilter-control=0",
5565 ])
5566 // aomenc keeps the LAST occurrence of a repeated flag,
5567 // so per-arm overrides go after the base recipe.
5568 .args([&depth_arg, &input_depth_arg, &cq_arg, &txs_arg, &tiles_arg])
5569 .args(["--obu", "-o", "-", "-"])
5570 .stdin(Stdio::piped())
5571 .stdout(Stdio::piped())
5572 .stderr(Stdio::piped())
5573 .spawn()
5574 .expect("aomenc failed to start");
5575 child
5576 .stdin
5577 .take()
5578 .expect("aomenc stdin")
5579 .write_all(&y4m)
5580 .or_else(|e| match e.kind() {
5581 std::io::ErrorKind::BrokenPipe => Ok(()),
5582 _ => Err(e),
5583 })
5584 .expect("writing y4m to aomenc");
5585 let out = child.wait_with_output().expect("aomenc failed to run");
5586 assert!(
5587 out.status.success(),
5588 "{NAME}: aomenc refused {arm}: {}",
5589 String::from_utf8_lossy(&out.stderr)
5590 );
5591 let stream = out.stdout;
5592 decode::reset_palette_leaf8_hits();
5593 decode::reset_palette_sb_strip_hits();
5594 let decoded = decode_stream(&stream);
5595 let leaf8 = decode::palette_leaf8_hits();
5596 let sb_strip = decode::palette_sb_strip_hits();
5597 leaf8_total += leaf8;
5598 sb_strip_total += sb_strip;
5599 match decoded {
5600 Ok(frames) => {
5601 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
5602 let theirs = if depth == 10 {
5603 ffmpeg_decode_sequence_10bit(
5604 &stream,
5605 width,
5606 height,
5607 frames.len(),
5608 )
5609 } else {
5610 ffmpeg_decode_sequence(&stream, width, height, frames.len())
5611 };
5612 assert_eq!(
5613 frames.len(),
5614 theirs.len(),
5615 "{NAME}: {arm} frame count"
5616 );
5617 let mut same = true;
5618 for (i, (ours, ref_f)) in
5619 frames.iter().zip(theirs.iter()).enumerate()
5620 {
5621 let ok = ours.y == ref_f.y
5622 && ours.u == ref_f.u
5623 && ours.v == ref_f.v;
5624 if !ok {
5625 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
5626 }
5627 same &= ok;
5628 frames_compared += 1;
5629 }
5630 compared += 1;
5631 if sb_strip > 0 {
5632 sb_strip_arms += 1;
5633 assert!(
5634 same,
5635 "{NAME}: {arm} decoded {sb_strip} non-skip palette \
5636 block(s) on a superblock-level strip and did not \
5637 match ffmpeg"
5638 );
5639 }
5640 if leaf8 > 0 || sb_strip > 0 {
5641 fired_arms += 1;
5642 assert!(
5643 same,
5644 "{NAME}: {arm} decoded {leaf8} 8x8-leaf palette \
5645 block(s) and did not match ffmpeg"
5646 );
5647 } else {
5648 out_of_scope += 1;
5649 if !same {
5650 out_of_scope_mismatch += 1;
5651 }
5652 }
5653 eprintln!(
5654 "{NAME}: {arm} {} frame(s), {leaf8} 8x8-leaf palette \
5655 block(s), {sb_strip} superblock-strip palette \
5656 block(s), exact={same}",
5657 frames.len()
5658 );
5659 }
5660 Err(e) => {
5661 let msg = e.to_string();
5662 assert!(
5663 msg.contains("unsupported"),
5664 "{NAME}: {arm} decode failed: {e}"
5665 );
5666 // Named, counted, never turned into a skip.
5667 if msg.contains("superblock-level HORZ/VERT strip") {
5668 sb_strip_refusals += 1;
5669 }
5670 eprintln!("{NAME}: {arm} REFUSED: {e}");
5671 refusals += 1;
5672 }
5673 }
5674 }
5675 }
5676 }
5677 }
5678 }
5679 eprintln!(
5680 "{NAME}: {leaf8_total} 8x8-leaf palette block(s) across {fired_arms} arm(s), \
5681 {compared} arms compared ({frames_compared} frames), {sb_strip_total} \
5682 superblock-strip palette block(s) across {sb_strip_arms} arm(s), \
5683 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
5684 {refusals} refused ({sb_strip_refusals} superblock-strip palette)"
5685 );
5686 assert!(
5687 leaf8_total > 0 && fired_arms > 0,
5688 "{NAME}: gate is vacuous -- no compared arm decoded an 8x8-leaf palette block"
5689 );
5690 assert_eq!(
5691 sb_strip_refusals, 0,
5692 "{NAME}: the superblock-strip palette refusal is back (lane-t900 r34 lifted it)"
5693 );
5694 assert!(
5695 sb_strip_arms > 0 && sb_strip_total > 0,
5696 "{NAME}: no arm decoded a non-skip palette block on a superblock-level strip -- \
5697 the shape r34 lifted is no longer exercised"
5698 );
5699 assert_eq!(
5700 out_of_scope_mismatch, 0,
5701 "{NAME}: an out-of-scope arm mismatched ffmpeg -- a defect, never a skip"
5702 );
5703 assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact");
5704 }
5705
5706 /// lane-kf900 r5, the gate for the rect-strip `use_intrabc` read.
5707 ///
5708 /// `av1_allow_intrabc` is a FRAME-level test (`decodemv.c:892`,
5709 /// `read_intra_frame_mode_info`): on an intra frame whose header set
5710 /// `allow_intrabc`, EVERY intra block reads a `use_intrabc` symbol right
5711 /// after `skip`/`cdef`/`delta_q` and before `mbmi->mode`. There is no
5712 /// block-shape term, so rect strips read it exactly like square leaves --
5713 /// `read_intra_mode_rect` never did, and the arithmetic decoder desynced
5714 /// at the FIRST symbol of the first rect block of every
5715 /// `--tune-content=screen` key frame (measured: `testsrc2` 256x192 cq59
5716 /// 8-bit decoded "OK" with all 49152 luma samples wrong).
5717 ///
5718 /// Arm 0 is that recipe at cq50 without palette: its rect strips really do
5719 /// use intrabc, which this decoder cannot reconstruct, so it must stop on
5720 /// the NAMED refusal instead of emitting a wrong frame -- and it must have
5721 /// read the symbol to get there.
5722 /// Arm 1 is the same recipe without palette and without tx-size search --
5723 /// it decodes the whole frame, reading the symbol dozens of times.
5724 /// Arm 2 is a screen-tools key frame whose header does NOT set
5725 /// `allow_intrabc` (cq63): it stays pixel-exact, proving the new read is
5726 /// not taken when libaom does not write it.
5727 ///
5728 /// PIXEL RESIDUE (open, lane-kf900 r5): arm 1's frame is entropy-exact
5729 /// against the instrumented aomdec for 429 mode-ladder elements and then
5730 /// diverges inside the DV read of a SQUARE intrabc block at mi(32,44), so
5731 /// its pixels are not compared here. That is a separate defect in
5732 /// `read_intrabc_dv`, not in the read this gate covers.
5733 #[test]
5734 fn a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips() {
5735 const NAME: &str = "a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips";
5736 if !have_ffmpeg() {
5737 eprintln!("SKIP {NAME}: no ffmpeg");
5738 return;
5739 }
5740 if !have_aomenc() {
5741 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5742 return;
5743 }
5744 let (width, height) = (256usize, 192usize);
5745 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
5746 // must_read_use_intrabc)
5747 const TS: &str = "testsrc2=s=256x192:r=25";
5748 const SB: &str = "smptebars=size=256x192:rate=25";
5749 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
5750 // must_read_use_intrabc_on_a_rect_strip)
5751 let arms: [(&str, &str, &[&str], bool, bool); 8] = [
5752 ("testsrc2-cq50-txs0", TS, &["--cq-level=50", "--enable-palette=0", "--enable-tx-size-search=0"], true, true),
5753 ("smptebars-cq40-txs0", SB, &["--cq-level=40", "--enable-palette=0", "--enable-tx-size-search=0"], false, false),
5754 ("smptebars-cq45-txs0", SB, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=0"], false, true),
5755 ("smptebars-cq45-txs1", SB, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=1"], false, false),
5756 ("smptebars-cq50-txs1", SB, &["--cq-level=50", "--enable-palette=0", "--enable-tx-size-search=1"], false, false),
5757 ("smptebars-cq55-txs0", SB, &["--cq-level=55", "--enable-palette=0", "--enable-tx-size-search=0"], false, false),
5758 ("testsrc2-cq63-txs1", TS, &["--cq-level=63", "--enable-palette=0", "--enable-tx-size-search=1"], false, false),
5759 // lane-kf900 r7: the 8x8-LEAF intrabc arm. Rect and 1:4
5760 // partitions off (so no rect strip refuses first), palette on,
5761 // `TxMode::Largest`: aomenc puts exactly one `use_intrabc` block
5762 // on a `BLOCK_8X8` leaf here, the shape `decode_leaf8` decoded as
5763 // ordinary intra before this round.
5764 ("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),
5765 ];
5766 let (mut reads_total, mut refused, mut frames_compared) = (0usize, 0u32, 0usize);
5767 let (mut blocks_total, mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) =
5768 (0usize, 0u32, 0u32, 0u32);
5769 let mut leaf8_total = 0usize;
5770 for (arm, src, extra, expect_refusal, must_read) in &arms {
5771 let render = || {
5772 let out = Command::new("ffmpeg")
5773 .args([
5774 "-v", "error", "-f", "lavfi", "-i", *src, "-t", "0.2", "-pix_fmt",
5775 "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
5776 ])
5777 .stdin(Stdio::null())
5778 .stdout(Stdio::piped())
5779 .stderr(Stdio::piped())
5780 .output()
5781 .expect("ffmpeg failed to run");
5782 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
5783 out.stdout
5784 };
5785 let y4m_a = render();
5786 let y4m_b = render();
5787 assert_eq!(y4m_a, y4m_b, "{NAME}: {arm} must render byte-identical across two runs");
5788 let y4m = y4m_a;
5789 let mut child = Command::new(aomenc_path())
5790 .args([
5791 "--codec=av1",
5792 "--bit-depth=8",
5793 "--input-bit-depth=8",
5794 "--passes=1",
5795 "--end-usage=q",
5796 "--cpu-used=0",
5797 "--lag-in-frames=0",
5798 "--kf-max-dist=1",
5799 "--limit=1",
5800 "--threads=1",
5801 "--tile-columns=0",
5802 "--enable-rect-partitions=1",
5803 "--enable-1to4-partitions=1",
5804 "--min-partition-size=8",
5805 "--max-partition-size=32",
5806 "--sb-size=64",
5807 // `allow_screen_content_tools` (and with it the frame
5808 // header's `allow_intrabc` bit) comes from here.
5809 "--tune-content=screen",
5810 // Spelled so `gate_coverage` counts the tool as exercised
5811 // rather than defaulted (class `tool-disabled-in-every-gate`).
5812 "--enable-intrabc=1",
5813 ])
5814 // aomenc keeps the LAST occurrence of a repeated flag.
5815 .args(*extra)
5816 .args(["--obu", "-o", "-", "-"])
5817 .stdin(Stdio::piped())
5818 .stdout(Stdio::piped())
5819 .stderr(Stdio::piped())
5820 .spawn()
5821 .expect("aomenc failed to start");
5822 child
5823 .stdin
5824 .take()
5825 .expect("aomenc stdin")
5826 .write_all(&y4m)
5827 .or_else(|e| match e.kind() {
5828 std::io::ErrorKind::BrokenPipe => Ok(()),
5829 _ => Err(e),
5830 })
5831 .expect("writing y4m to aomenc");
5832 let out = child.wait_with_output().expect("aomenc failed to run");
5833 assert!(
5834 out.status.success(),
5835 "{NAME}: aomenc refused {arm}: {}",
5836 String::from_utf8_lossy(&out.stderr)
5837 );
5838 let stream = out.stdout;
5839 decode::reset_rect_intrabc_reads();
5840 crate::decode::reset_intrabc_hits();
5841 crate::decode::reset_leaf8_intrabc_hits();
5842 let decoded = decode_stream(&stream);
5843 let reads = decode::rect_intrabc_reads();
5844 // Blocks that decoded `use_intrabc == 1` (square path), i.e. that
5845 // read a DV and predicted from the current frame -- distinct from
5846 // `reads`, which counts rect strips that merely READ the flag.
5847 let blocks = crate::decode::intrabc_hits();
5848 reads_total += reads;
5849 blocks_total += blocks;
5850 // The 8x8-leaf shape has its own counter: without it this gate's
5851 // other arms (all rect/32x32 intrabc) would stay green while the
5852 // leaf path decoded an intrabc block as ordinary intra (class
5853 // `gate-blind-to-feature`).
5854 let leaf8 = crate::decode::leaf8_intrabc_hits();
5855 leaf8_total += leaf8;
5856 if *arm == "testsrc2-cq55-leaf8" {
5857 assert!(
5858 leaf8 > 0,
5859 "{NAME}: {arm} decoded no intrabc block at an 8x8 leaf -- the arm no longer exercises `decode_leaf8`'s intrabc path"
5860 );
5861 }
5862 if *must_read {
5863 assert!(
5864 reads > 0,
5865 "{NAME}: {arm} read no use_intrabc symbol on a rect strip -- the \
5866 arm no longer exercises the fix (allow_intrabc not set?)"
5867 );
5868 }
5869 match decoded {
5870 Ok(frames) => {
5871 assert!(
5872 !*expect_refusal,
5873 "{NAME}: {arm} decoded a frame whose rect strips use intrabc -- \
5874 reconstruction is not ported, it must refuse by name"
5875 );
5876 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
5877 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
5878 assert_eq!(frames.len(), ffmpeg_frames.len(), "{NAME}: {arm} frame count");
5879 // EVERY frame is compared; an arm whose decode never hit an
5880 // intrabc block proves nothing about the DV/prediction path,
5881 // so it is counted OUT OF SCOPE -- but a mismatch there is
5882 // still a failure (`out_of_scope_mismatch == 0`), never a skip.
5883 let mut same = true;
5884 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
5885 let ok = ours.y == theirs.y && ours.u == theirs.u && ours.v == theirs.v;
5886 if !ok {
5887 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
5888 }
5889 same &= ok;
5890 frames_compared += 1;
5891 }
5892 if blocks > 0 {
5893 fired_arms += 1;
5894 assert!(
5895 same,
5896 "{NAME}: {arm} decoded {blocks} intrabc block(s) and did not match ffmpeg"
5897 );
5898 } else {
5899 out_of_scope += 1;
5900 if !same {
5901 out_of_scope_mismatch += 1;
5902 }
5903 }
5904 eprintln!(
5905 "{NAME}: {arm} {} frame(s), {reads} rect use_intrabc reads, \
5906 {blocks} intrabc block(s), exact={same}",
5907 frames.len()
5908 );
5909 }
5910 Err(e) => {
5911 let msg = e.to_string();
5912 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
5913 assert!(
5914 *expect_refusal,
5915 "{NAME}: {arm} was expected to decode, it refused: {e}"
5916 );
5917 assert!(
5918 msg.contains("intra block copy") || msg.contains("intrabc"),
5919 "{NAME}: {arm} refused for an unrelated reason: {e}"
5920 );
5921 eprintln!("{NAME}: {arm} REFUSED (expected): {e}");
5922 refused += 1;
5923 }
5924 }
5925 }
5926 eprintln!(
5927 "{NAME}: {reads_total} rect-strip use_intrabc symbol(s) read, \
5928 {blocks_total} intrabc block(s) decoded across {fired_arms} arm(s), \
5929 {refused} refused by name, {frames_compared} frames compared, \
5930 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched)"
5931 );
5932 eprintln!("{NAME}: {leaf8_total} intrabc block(s) at an 8x8 leaf");
5933 assert!(reads_total > 0, "{NAME}: gate is vacuous -- no arm read the symbol");
5934 assert!(
5935 leaf8_total > 0,
5936 "{NAME}: no arm decoded an intrabc block at an 8x8 leaf -- lane-kf900 r7's fix is untested"
5937 );
5938 assert!(
5939 blocks_total > 0 && fired_arms > 0,
5940 "{NAME}: gate is vacuous -- no compared arm actually decoded an intrabc block"
5941 );
5942 assert_eq!(refused, 1, "{NAME}: expected exactly one named intrabc refusal");
5943 assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact");
5944 assert_eq!(
5945 out_of_scope_mismatch, 0,
5946 "{NAME}: an arm without an intrabc block still mismatched ffmpeg"
5947 );
5948 }
5949
5950 /// lane-t900 r31: builds one `--tune-content=screen --enable-intrabc=1`
5951 /// key frame, 256x192 8-bit, from a deterministic lavfi source. `tiled`
5952 /// renders a 2x2 tiling of a 128x96 pattern -- exact spatial repetition,
5953 /// the content intra block copy exists for; `square_only` turns the rect
5954 /// and 1:4 partitions off so an intrabc block lands on a SQUARE block
5955 /// instead of stopping on the rect-strip intrabc refusal first.
5956 fn screen_intrabc_stream(src: &str, cq: &str, txs: &str, tiled: bool, square_only: bool) -> Vec<u8> {
5957 screen_intrabc_stream_with(src, cq, txs, tiled, square_only, &[])
5958 }
5959
5960 /// [`screen_intrabc_stream`] with per-arm flags appended AFTER the base
5961 /// recipe -- aomenc keeps the LAST occurrence of a repeated flag, so an
5962 /// arm can override `--sb-size` / `--min-partition-size` here.
5963 fn screen_intrabc_stream_with(
5964 src: &str,
5965 cq: &str,
5966 txs: &str,
5967 tiled: bool,
5968 square_only: bool,
5969 extra: &[&str],
5970 ) -> Vec<u8> {
5971 let mut ff = Command::new("ffmpeg");
5972 ff.args(["-v", "error", "-f", "lavfi", "-i", src, "-t", "0.2"]);
5973 if tiled {
5974 ff.args(["-vf", "tile=2x2"]);
5975 }
5976 let out = ff
5977 .args(["-pix_fmt", "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-"])
5978 .stdin(Stdio::null())
5979 .stdout(Stdio::piped())
5980 .stderr(Stdio::piped())
5981 .output()
5982 .expect("ffmpeg failed to run");
5983 assert!(out.status.success(), "ffmpeg failed for {src}");
5984 let y4m = out.stdout;
5985 let mut child = Command::new(aomenc_path())
5986 .args([
5987 "--codec=av1",
5988 "--bit-depth=8",
5989 "--input-bit-depth=8",
5990 "--passes=1",
5991 "--end-usage=q",
5992 "--cpu-used=0",
5993 "--lag-in-frames=0",
5994 "--kf-max-dist=1",
5995 "--limit=1",
5996 "--threads=1",
5997 "--tile-columns=0",
5998 "--min-partition-size=8",
5999 "--max-partition-size=32",
6000 "--sb-size=64",
6001 "--tune-content=screen",
6002 "--enable-intrabc=1",
6003 "--enable-palette=0",
6004 ])
6005 .args([format!("--cq-level={cq}"), format!("--enable-tx-size-search={txs}")])
6006 // aomenc keeps the LAST occurrence of a repeated flag.
6007 .args(if square_only {
6008 &["--enable-rect-partitions=0", "--enable-1to4-partitions=0"][..]
6009 } else {
6010 &[][..]
6011 })
6012 .args(extra)
6013 .args(["--obu", "-o", "-", "-"])
6014 .stdin(Stdio::piped())
6015 .stdout(Stdio::piped())
6016 .stderr(Stdio::piped())
6017 .spawn()
6018 .expect("aomenc failed to start");
6019 child
6020 .stdin
6021 .take()
6022 .expect("aomenc stdin")
6023 .write_all(&y4m)
6024 .or_else(|e| match e.kind() {
6025 std::io::ErrorKind::BrokenPipe => Ok(()),
6026 _ => Err(e),
6027 })
6028 .expect("writing y4m to aomenc");
6029 let enc = child.wait_with_output().expect("aomenc failed to run");
6030 assert!(
6031 enc.status.success(),
6032 "aomenc refused {src} cq={cq}: {}",
6033 String::from_utf8_lossy(&enc.stderr)
6034 );
6035 enc.stdout
6036 }
6037
6038 /// The sequence header's `use_128x128_superblock`, and how many frames of
6039 /// `stream` keep `allow_intrabc` -- the two bits the refusal "intrabc
6040 /// under a 128x128 superblock" is the conjunction of, read out of the
6041 /// headers rather than assumed from the flags handed to the encoder.
6042 fn sb128_and_intrabc_frames(stream: &[u8]) -> (bool, u32) {
6043 let mut parser = Av1Parser::new();
6044 let mut pos = 0usize;
6045 let (mut sb128, mut intrabc) = (false, 0u32);
6046 while pos < stream.len() {
6047 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
6048 break;
6049 };
6050 pos += obu.total_size.max(1);
6051 if let Some(seq) = parser.sequence_header() {
6052 sb128 = seq.use_128x128_superblock;
6053 }
6054 let header = match &obu.kind {
6055 ObuKind::Frame(h, _) => Some(&**h),
6056 ObuKind::FrameHeader(h) => Some(&**h),
6057 _ => None,
6058 };
6059 if header.is_some_and(|h| h.allow_intrabc) {
6060 intrabc += 1;
6061 }
6062 }
6063 (sb128, intrabc)
6064 }
6065
6066 /// lane-t900 r34, the WITNESS (r33 pinned it ignored) that intrabc under
6067 /// a 128x128 superblock decodes pixel-exact.
6068 ///
6069 /// All four arms of r33's census -- `--sb-size=128 --tune-content=screen
6070 /// --enable-intrabc=1` over both `--enable-tx-size-search` settings and
6071 /// two quantisers, on a 2x2 tiling of a 128x96 bar pattern (256x192,
6072 /// 8-bit, `--cpu-used=0 --min-partition-size=8 --max-partition-size=32`,
6073 /// rect and 1:4 off) -- code `use_128x128_superblock && allow_intrabc`.
6074 ///
6075 /// The lift was one constant: `av1_find_ref_dv` (mvref_common.c) takes
6076 /// `mib_size`, the SEQUENCE's superblock size in mi units, so the
6077 /// fallback DV is one 128-px superblock up (or 128 + `INTRABC_DELAY_PIXELS`
6078 /// left on the tile's first superblock row) under a 128 superblock, where
6079 /// [`crate::decode::read_intrabc_dv`] hardcoded 64. Every arm is compared
6080 /// to ffmpeg and the decoded-intrabc-block counter is asserted non-zero,
6081 /// so a stream that stopped using intrabc could not make this vacuous.
6082 #[test]
6083 fn an_sb128_screen_stream_with_intrabc_decodes_pixel_exact() {
6084 const NAME: &str = "an_sb128_screen_stream_with_intrabc_decodes_pixel_exact";
6085 if !have_ffmpeg() || !have_aomenc() {
6086 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
6087 return;
6088 }
6089 let (width, height) = (256usize, 192usize);
6090 let _guard = lock_gate_counters();
6091 let (mut blocks_total, mut frames_compared) = (0usize, 0u32);
6092 for txs in ["0", "1"] {
6093 for cq in ["30", "45"] {
6094 let arm = format!("sb128 txs={txs} cq={cq}");
6095 let stream = screen_intrabc_stream_with(
6096 "smptebars=size=128x96:rate=25",
6097 cq,
6098 txs,
6099 true,
6100 true,
6101 &["--sb-size=128"],
6102 );
6103 let (sb128, intrabc_frames) = sb128_and_intrabc_frames(&stream);
6104 assert!(
6105 sb128 && intrabc_frames > 0,
6106 "{NAME}: {arm} no longer codes sb128 + allow_intrabc"
6107 );
6108 crate::decode::reset_intrabc_hits();
6109 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm}: {e}"));
6110 let blocks = crate::decode::intrabc_hits();
6111 blocks_total += blocks;
6112 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
6113 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
6114 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
6115 assert!(
6116 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
6117 "{NAME}: {arm} frame {i} does not match ffmpeg"
6118 );
6119 frames_compared += 1;
6120 }
6121 eprintln!(
6122 "{NAME}: {arm} intrabc_frames={intrabc_frames} intrabc_blocks={blocks} \
6123 DECODED {} frame(s) exact",
6124 frames.len()
6125 );
6126 }
6127 }
6128 assert!(frames_compared > 0, "{NAME}: no frame was compared");
6129 assert!(
6130 blocks_total > 0,
6131 "{NAME}: gate is vacuous -- no arm decoded a single intrabc block"
6132 );
6133 }
6134
6135 /// lane-t900 r33, CENSUS for "a sub-8x8 leaf that uses intrabc".
6136 ///
6137 /// The `use_intrabc` symbol IS read at that reader for every sub-8x8 leaf
6138 /// of an `allow_intrabc` frame, so arrival is provable rather than
6139 /// assumed: the arms below force 4x4 leaves (`--min-partition-size=4`) on
6140 /// the exact-repetition screen content that keeps `allow_intrabc`, and the
6141 /// gate requires both counters -- `allow_intrabc` frames and decoded sub-8
6142 /// leaves -- to be non-zero before it reads anything into the refusal
6143 /// firing 0 times (class `gate-blind-to-feature`).
6144 #[test]
6145 fn a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal() {
6146 const NAME: &str = "a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal";
6147 if !have_ffmpeg() || !have_aomenc() {
6148 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
6149 return;
6150 }
6151 let (width, height) = (256usize, 192usize);
6152 let _guard = lock_gate_counters();
6153 let (mut premise_arms, mut reached, mut sub8_total, mut frames_compared) =
6154 (0u32, 0u32, 0usize, 0u32);
6155 for cq in ["30", "45"] {
6156 let arm = format!("sub8 cq={cq}");
6157 let stream = screen_intrabc_stream_with(
6158 "smptebars=size=128x96:rate=25",
6159 cq,
6160 "0",
6161 true,
6162 true,
6163 &["--min-partition-size=4"],
6164 );
6165 let (_, intrabc_frames) = sb128_and_intrabc_frames(&stream);
6166 if intrabc_frames > 0 {
6167 premise_arms += 1;
6168 }
6169 // No reset for this counter, so measure the delta (the gate lock
6170 // above keeps another gate's decode out of it).
6171 let sub8_before = crate::decode::sub8_split_hits();
6172 match decode_stream(&stream) {
6173 Ok(frames) => {
6174 let sub8 = crate::decode::sub8_split_hits() - sub8_before;
6175 sub8_total += sub8;
6176 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
6177 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
6178 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
6179 assert!(
6180 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
6181 "{NAME}: {arm} frame {i} does not match ffmpeg"
6182 );
6183 frames_compared += 1;
6184 }
6185 eprintln!(
6186 "{NAME}: {arm} intrabc_frames={intrabc_frames} sub8_leaves={sub8} \
6187 DECODED {} frame(s) exact",
6188 frames.len()
6189 );
6190 }
6191 Err(e) => {
6192 let msg = e.to_string();
6193 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
6194 if msg.contains("a sub-8x8 leaf that uses intrabc") {
6195 reached += 1;
6196 }
6197 sub8_total += crate::decode::sub8_split_hits() - sub8_before;
6198 eprintln!(
6199 "{NAME}: {arm} intrabc_frames={intrabc_frames} REFUSED: {e}"
6200 );
6201 }
6202 }
6203 }
6204 eprintln!(
6205 "{NAME}: {premise_arms}/2 arm(s) keep allow_intrabc, {sub8_total} sub-8 leaf/leaves \
6206 decoded, {reached} reach the refusal, {frames_compared} frame(s) exact"
6207 );
6208 assert!(
6209 premise_arms > 0,
6210 "{NAME}: census is vacuous -- no arm kept allow_intrabc, so the refusal's own \
6211 premise was never within reach"
6212 );
6213 assert!(
6214 sub8_total > 0,
6215 "{NAME}: census is vacuous -- no sub-8 leaf was decoded at all, so the \
6216 `use_intrabc` symbol this refusal guards was never read"
6217 );
6218 }
6219
6220 /// lane-t900 r33, CENSUS for "an intrabc block whose var-tx tree resolved
6221 /// to mixed leaf transform sizes" -- the residue lane-t900 r32 left when
6222 /// it lifted the intrabc `TX_MODE_SELECT` refusal.
6223 ///
6224 /// The tree is read in full, but the luma reconstruct loop it feeds is a
6225 /// UNIFORM grid of one square transform, so a tree that split unevenly
6226 /// would be reconstructed at the wrong stride. This census sweeps the
6227 /// quantiser across the exact-repetition recipe that reaches the tree at
6228 /// all and requires the tree to actually be read (`intrabc_vartx_hits`)
6229 /// before reading anything into the refusal firing 0 times.
6230 #[test]
6231 fn an_intrabc_vartx_census_measures_the_mixed_leaf_refusal() {
6232 const NAME: &str = "an_intrabc_vartx_census_measures_the_mixed_leaf_refusal";
6233 if !have_ffmpeg() || !have_aomenc() {
6234 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
6235 return;
6236 }
6237 let (width, height) = (256usize, 192usize);
6238 let _guard = lock_gate_counters();
6239 let (mut vartx_total, mut reached, mut frames_compared) = (0usize, 0u32, 0u32);
6240 for cq in ["20", "30", "45", "55"] {
6241 let arm = format!("vartx cq={cq}");
6242 let stream =
6243 screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
6244 let (select, premise) = tx_select_and_intrabc_frames(&stream);
6245 crate::decode::reset_intrabc_vartx_hits();
6246 match decode_stream(&stream) {
6247 Ok(frames) => {
6248 let vartx = crate::decode::intrabc_vartx_hits();
6249 vartx_total += vartx;
6250 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
6251 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
6252 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
6253 assert!(
6254 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
6255 "{NAME}: {arm} frame {i} does not match ffmpeg"
6256 );
6257 frames_compared += 1;
6258 }
6259 eprintln!(
6260 "{NAME}: {arm} select={select} premise={premise} vartx_blocks={vartx} \
6261 DECODED {} frame(s) exact",
6262 frames.len()
6263 );
6264 }
6265 Err(e) => {
6266 let msg = e.to_string();
6267 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
6268 vartx_total += crate::decode::intrabc_vartx_hits();
6269 if msg.contains("mixed leaf transform sizes") {
6270 reached += 1;
6271 }
6272 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
6273 }
6274 }
6275 }
6276 eprintln!(
6277 "{NAME}: {vartx_total} intrabc block(s) read the var-tx tree, {reached} resolved to \
6278 mixed leaves, {frames_compared} frame(s) exact"
6279 );
6280 assert!(
6281 vartx_total > 0,
6282 "{NAME}: census is vacuous -- no intrabc block read the var-tx tree at all"
6283 );
6284 assert_eq!(
6285 reached, 0,
6286 "{NAME}: an intrabc var-tx tree resolved to mixed leaves -- the refusal is a live \
6287 capability gap and needs a pinned witness, not this census"
6288 );
6289 }
6290
6291 /// How many frames of `stream` carry `tx_mode == Select`, and how many of
6292 /// those also keep `allow_intrabc` -- the frame-level premise of the
6293 /// refusal "an intrabc block under TxMode::Select", read out of the
6294 /// headers rather than assumed from the flags handed to the encoder
6295 /// (libaom clears `allow_intrabc` again when no block picked it,
6296 /// encodeframe.c:2336).
6297 fn tx_select_and_intrabc_frames(stream: &[u8]) -> (u32, u32) {
6298 let (mut select, mut premise) = (0u32, 0u32);
6299 let mut p = Av1Parser::new();
6300 let mut pos = 0usize;
6301 while pos < stream.len() {
6302 let obu = p.parse_obu(&stream[pos..]).expect("parse");
6303 pos += obu.total_size;
6304 let header = match &obu.kind {
6305 ObuKind::Frame(h, _) => Some(&**h),
6306 ObuKind::FrameHeader(h) => Some(&**h),
6307 _ => None,
6308 };
6309 if let Some(h) = header {
6310 if h.tx_mode == TxMode::Select {
6311 select += 1;
6312 if h.allow_intrabc {
6313 premise += 1;
6314 }
6315 }
6316 }
6317 }
6318 (select, premise)
6319 }
6320
6321 /// lane-t900 r31, CENSUS for the refusal "an intrabc block under
6322 /// TxMode::Select" -- which this gate DISPROVES as an "no encoder writes
6323 /// one" claim and pins as a real capability gap instead.
6324 ///
6325 /// The premise is reachable by the SPEC: `tx_mode` (5.9.21) is forced to
6326 /// `ONLY_4X4` only under `CodedLossless`, while `allow_intrabc` (5.9.2)
6327 /// needs `allow_screen_content_tools` at unscaled resolution -- two
6328 /// independent conditions. libaom leaves it open too: `select_tx_mode`
6329 /// (encodeframe.c:2355) never consults `allow_intrabc`, and the only
6330 /// downgrade to `TX_MODE_LARGEST` is `txb_split_count == 0`
6331 /// (encodeframe.c:2690).
6332 ///
6333 /// The measurement over 14 real `--tune-content=screen --enable-intrabc=1`
6334 /// recipes:
6335 ///
6336 /// * the 10 non-repeating arms never present the premise at all -- with
6337 /// `--enable-tx-size-search=1` the frame codes `TX_MODE_SELECT` but RD
6338 /// never picks intrabc, so libaom clears `allow_intrabc` again; with
6339 /// `=0` intrabc IS used and the frame is `TX_MODE_LARGEST`. That
6340 /// correlation, not any rule, is why earlier rounds never saw this;
6341 /// * the four EXACT-REPETITION arms (a 2x2 tiling of one 128x96 bar
6342 /// pattern) all code `allow_intrabc && tx_mode == Select`. Two of them
6343 /// stop on the older rect-strip intrabc refusal (the shape that fires
6344 /// first, class `refusal-hides-a-defect`), and the two with rect/1:4
6345 /// partitions off put intrabc on a SQUARE block: `cq=30` reaches THIS
6346 /// refusal by name, `cq=45`'s intrabc blocks are all `skip` and decode
6347 /// pixel-exact against ffmpeg.
6348 ///
6349 /// So the refusal is correct and load-bearing, exactly one arm reaches it,
6350 /// and the lift it names has a waiting witness:
6351 /// [`an_intrabc_block_under_tx_mode_select_decodes_pixel_exact`] (ignored
6352 /// until the intra path reads the inter var-tx tree for an intrabc block).
6353 #[test]
6354 fn an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal() {
6355 const NAME: &str =
6356 "an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal";
6357 if !have_ffmpeg() {
6358 eprintln!("SKIP {NAME}: no ffmpeg");
6359 return;
6360 }
6361 if !have_aomenc() {
6362 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6363 return;
6364 }
6365 const TS: &str = "testsrc2=s=256x192:r=25";
6366 const SB: &str = "smptebars=size=256x192:rate=25";
6367 const PB: &str = "pal75bars=size=256x192:rate=25";
6368 const TILE: &str = "smptebars=size=128x96:rate=25";
6369 let (width, height) = (256usize, 192usize);
6370 // (arm, source, cq, tx-size-search, tiled, square_only)
6371 let arms: [(&str, &str, &str, &str, bool, bool); 14] = [
6372 ("smptebars-cq40-txs1", SB, "40", "1", false, false),
6373 ("smptebars-cq45-txs1", SB, "45", "1", false, false),
6374 ("smptebars-cq55-txs1", SB, "55", "1", false, false),
6375 ("smptebars-cq63-txs1", SB, "63", "1", false, false),
6376 ("pal75bars-cq40-txs1", PB, "40", "1", false, false),
6377 ("pal75bars-cq55-txs1", PB, "55", "1", false, false),
6378 ("testsrc2-cq50-txs1", TS, "50", "1", false, false),
6379 ("testsrc2-cq63-txs1", TS, "63", "1", false, false),
6380 ("smptebars-cq45-txs0", SB, "45", "0", false, false),
6381 ("pal75bars-cq45-txs0", PB, "45", "0", false, false),
6382 ("tiled-cq30-txs1", TILE, "30", "1", true, false),
6383 ("tiled-cq45-txs1", TILE, "45", "1", true, false),
6384 ("tiled-square-cq30-txs1", TILE, "30", "1", true, true),
6385 // lane-t900 r32: both square arms are now ORDINARY census members
6386 // -- cq30 (unskipped intrabc, the inter var-tx tree) and cq45
6387 // (all-skip intrabc, `maxRectTxSize` with no symbol at all) decode
6388 // pixel-exact, so nothing here reaches the lifted refusal.
6389 ("tiled-square-cq45-txs1", TILE, "45", "1", true, true),
6390 ];
6391 let (mut select_arms, mut premise_arms, mut intrabc_arms, mut blocks_total) =
6392 (0u32, 0u32, 0u32, 0usize);
6393 let (mut refused_tx_select, mut frames_compared) = (0u32, 0usize);
6394 for (arm, src, cq, txs, tiled, square_only) in &arms {
6395 let stream = screen_intrabc_stream(src, cq, txs, *tiled, *square_only);
6396 let (select, premise) = tx_select_and_intrabc_frames(&stream);
6397 if select > 0 {
6398 select_arms += 1;
6399 }
6400 if premise > 0 {
6401 premise_arms += 1;
6402 }
6403 crate::decode::reset_intrabc_hits();
6404 let decoded = decode_stream(&stream);
6405 let blocks = crate::decode::intrabc_hits();
6406 blocks_total += blocks;
6407 if blocks > 0 {
6408 intrabc_arms += 1;
6409 }
6410 match decoded {
6411 Ok(frames) => {
6412 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
6413 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
6414 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
6415 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
6416 assert!(
6417 ours.y == ref_frame.y
6418 && ours.u == ref_frame.u
6419 && ours.v == ref_frame.v,
6420 "{NAME}: {arm} frame {i} does not match ffmpeg"
6421 );
6422 frames_compared += 1;
6423 }
6424 eprintln!(
6425 "{NAME}: {arm} select={select} premise={premise} {blocks} intrabc \
6426 block(s), {} frame(s) exact",
6427 frames.len()
6428 );
6429 }
6430 Err(e) => {
6431 let msg = e.to_string();
6432 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
6433 if msg.contains("an intrabc block under TxMode::Select") {
6434 refused_tx_select += 1;
6435 assert!(
6436 premise > 0,
6437 "{NAME}: {arm} reached the TxMode::Select intrabc refusal in a \
6438 frame that codes no such header"
6439 );
6440 } else {
6441 assert!(
6442 msg.contains("intra block copy"),
6443 "{NAME}: {arm} refused for an unrelated reason: {e}"
6444 );
6445 }
6446 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
6447 }
6448 }
6449 }
6450 eprintln!(
6451 "{NAME}: {select_arms}/{n} arm(s) code a TX_MODE_SELECT frame, {premise_arms} of \
6452 those keep allow_intrabc, {intrabc_arms} arm(s) decode an intrabc block \
6453 ({blocks_total} total), {refused_tx_select} reach the refusal, \
6454 {frames_compared} frame(s) compared exact",
6455 n = arms.len()
6456 );
6457 assert!(
6458 intrabc_arms > 0 && blocks_total > 0,
6459 "{NAME}: census is vacuous -- no arm decoded an intrabc block at all"
6460 );
6461 assert!(
6462 premise_arms > 0,
6463 "{NAME}: census is vacuous -- no arm coded a frame with both allow_intrabc and \
6464 tx_mode == Select, so the refusal's own premise was never within reach"
6465 );
6466 assert_eq!(
6467 refused_tx_select, 0,
6468 "{NAME}: lane-t900 r32 lifted this refusal -- an intrabc block now reads the \
6469 INTER tx-size syntax, so no arm may reach it again"
6470 );
6471 assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact");
6472 }
6473
6474 /// lane-t900 r31, the WAITING witness for the capability
6475 /// [`an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal`]
6476 /// pins: a real aomenc screen key frame whose intrabc block sits on a
6477 /// square block of a `TX_MODE_SELECT` frame, unskipped. libaom's
6478 /// `parse_decode_block` treats an intrabc block as `inter_block_tx`, so
6479 /// its transform size comes off the inter var-tx partition tree
6480 /// (`read_var_tx_size`), which this decoder reads nowhere on the intra
6481 /// path -- reading the intra `tx_depth` symbol instead desyncs.
6482 ///
6483 /// lane-t900 r32 closed both arms. A SKIPPED intrabc block reads no
6484 /// tx-size symbol at all (`allowSelect = !skip || !is_inter`, false for an
6485 /// intrabc block since libaom's `is_inter_block` counts one); reading the
6486 /// intra `tx_depth` for it consumed a symbol libaom never wrote and
6487 /// desynced the tile a whole block later, at the superblock corner
6488 /// (192,64) (class `equal-range-means-unread`). An UNSKIPPED one reads the
6489 /// inter var-tx tree (`read_var_tx_size`). r31's note that cq=45's blocks
6490 /// are all `skip` was read off that desynced decode: with the tx-size read
6491 /// corrected, cq=45 carries 3 unskipped intrabc blocks of 10 and cq=30
6492 /// carries 1 of 16, so both arms exercise both sides of the split.
6493 #[test]
6494 fn an_intrabc_block_under_tx_mode_select_decodes_pixel_exact() {
6495 const NAME: &str = "an_intrabc_block_under_tx_mode_select_decodes_pixel_exact";
6496 if !have_ffmpeg() || !have_aomenc() {
6497 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
6498 return;
6499 }
6500 let (width, height) = (256usize, 192usize);
6501 for cq in ["30", "45"] {
6502 let stream = screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
6503 let (select, premise) = tx_select_and_intrabc_frames(&stream);
6504 assert!(
6505 select > 0 && premise > 0,
6506 "{NAME}: cq={cq} no longer codes allow_intrabc under TX_MODE_SELECT \
6507 (select={select} premise={premise})"
6508 );
6509 crate::decode::reset_intrabc_hits();
6510 crate::decode::reset_intrabc_vartx_hits();
6511 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: cq={cq}: {e}"));
6512 let (blocks, vartx) =
6513 (crate::decode::intrabc_hits(), crate::decode::intrabc_vartx_hits());
6514 assert!(blocks > 0, "{NAME}: cq={cq} no longer decodes an intrabc block");
6515 // r31 recorded cq=45's intrabc blocks as ALL skip; that was read
6516 // off the desynced decode. With the tx-size read corrected both
6517 // arms carry unskipped ones (cq30 1 of 16, cq45 3 of 10), so both
6518 // must reach the var-tx tree or the gate is blind to the lift
6519 // (class `gate-blind-to-feature`).
6520 assert!(
6521 vartx > 0,
6522 "{NAME}: cq={cq} no longer reads the inter var-tx tree for an intrabc block"
6523 );
6524 eprintln!("{NAME}: cq={cq} {blocks} intrabc block(s), {vartx} through var-tx");
6525 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
6526 assert_eq!(frames.len(), theirs.len(), "{NAME}: cq={cq} frame count");
6527 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
6528 assert!(
6529 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
6530 "{NAME}: cq={cq} frame {i} does not match ffmpeg"
6531 );
6532 }
6533 }
6534 }
6535
6536 /// lane-kf900 r4, the gate for the two lifted palette refusals ("a 1:4
6537 /// rect strip that actually uses a palette (reconstruction is not ported
6538 /// at this shape)" and "a palette block on a HORZ/VERT intra strip below
6539 /// 16x16 (reconstruction not ported)"): real `aomenc` streams that put a
6540 /// palette on a RECT strip, decoded whole-frame pixel-exact against
6541 /// ffmpeg's own decode of the identical bytes, at 8 AND 10 bit.
6542 ///
6543 /// Arm 0 is the stream lane-kf900 r3 pinned and stopped on -- `testsrc2`
6544 /// 256x192, `--cq-level=59 --cpu-used=0 --min-partition-size=8
6545 /// --enable-rect-partitions=1 --enable-tx-size-search=1`, md5
6546 /// `e5f033d8fe34e4418d8cca3ac9d2b595` at 10 bit. Arms 1-2 force the shape
6547 /// on screen-like content with `--tune-content=screen --enable-palette=1
6548 /// --enable-1to4-partitions=1`.
6549 ///
6550 /// An attempt whose decode never hit a rect-strip palette block proves
6551 /// nothing about the lift, so it is counted OUT OF SCOPE rather than
6552 /// silently passing -- but a mismatch on one is still a failure
6553 /// (`out_of_scope_mismatch == 0`), and at least one attempt must fire the
6554 /// counter or the gate is vacuous.
6555 #[test]
6556 fn a_real_aomenc_rect_strip_palette_decodes_pixel_exact() {
6557 const NAME: &str = "a_real_aomenc_rect_strip_palette_decodes_pixel_exact";
6558 if !have_ffmpeg() {
6559 eprintln!("SKIP {NAME}: no ffmpeg");
6560 return;
6561 }
6562 if !have_aomenc() {
6563 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6564 return;
6565 }
6566 let (width, height) = (256usize, 192usize);
6567 let screen: &[&str] = &[
6568 "--tune-content=screen",
6569 "--enable-palette=1",
6570 "--enable-1to4-partitions=1",
6571 "--min-partition-size=8",
6572 ];
6573 // lane-kf900 r6: arms 3-4 are the palette + `--enable-tx-size-search=1`
6574 // shape whose neighbour palette lookup was SUB-granular -- a 16x8 strip
6575 // pair shares one 16px cell, so strip 1 read strip 0's palette size and
6576 // the colour cache came out short. Both were whole-frame wrong before
6577 // the mi-granular fix (`$HOME/.cache/kf900-r6/sweep.log`: smptebars
6578 // cq40/cq55 txs=1 pal=1 = DIFF).
6579 let screen_txs: &[&str] = &[
6580 "--tune-content=screen",
6581 "--enable-palette=1",
6582 "--enable-1to4-partitions=1",
6583 "--min-partition-size=8",
6584 "--max-partition-size=32",
6585 "--sb-size=64",
6586 "--enable-intrabc=1",
6587 "--enable-tx-size-search=1",
6588 ];
6589 let cq40: Vec<&str> = screen_txs.iter().copied().chain(["--cq-level=40"]).collect();
6590 let cq55: Vec<&str> = screen_txs.iter().copied().chain(["--cq-level=55"]).collect();
6591 let arms: [(&str, String, &[&str]); 5] = [
6592 ("testsrc2-pinned", "testsrc2=s=256x192:r=25".to_string(), &[]),
6593 ("testsrc2-screen", "testsrc2=s=256x192:r=25".to_string(), screen),
6594 ("smptebars-screen", "smptebars=size=256x192:rate=25".to_string(), screen),
6595 ("smptebars-screen-txs-cq40", "smptebars=size=256x192:rate=25".to_string(), &cq40),
6596 ("smptebars-screen-txs-cq55", "smptebars=size=256x192:rate=25".to_string(), &cq55),
6597 ];
6598 let (mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32, 0u32);
6599 let mut refused = 0u32;
6600 let mut fired_at_depth = [0u32; 2];
6601 let mut frames_compared = 0usize;
6602 for (arm, src, extra) in &arms {
6603 for depth in [8usize, 10] {
6604 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
6605 let render = || {
6606 let out = Command::new("ffmpeg")
6607 .args([
6608 "-v", "error", "-f", "lavfi", "-i", src.as_str(), "-t", "0.2",
6609 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
6610 ])
6611 .stdin(Stdio::null())
6612 .stdout(Stdio::piped())
6613 .stderr(Stdio::piped())
6614 .output()
6615 .expect("ffmpeg failed to run");
6616 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
6617 out.stdout
6618 };
6619 let y4m_a = render();
6620 let y4m_b = render();
6621 assert_eq!(
6622 y4m_a, y4m_b,
6623 "{NAME}: {arm} must render byte-identical across two runs at {depth}-bit"
6624 );
6625 let y4m = y4m_a;
6626 let depth_arg = format!("--bit-depth={depth}");
6627 let in_depth_arg = format!("--input-bit-depth={depth}");
6628 let mut child = Command::new(aomenc_path())
6629 .args(["--codec=av1"])
6630 .args([&depth_arg, &in_depth_arg])
6631 .args([
6632 "--passes=1",
6633 "--end-usage=q",
6634 "--cq-level=59",
6635 "--cpu-used=0",
6636 "--lag-in-frames=0",
6637 "--kf-max-dist=1",
6638 "--limit=1",
6639 "--threads=1",
6640 "--tile-columns=0",
6641 "--enable-tx-size-search=1",
6642 "--min-partition-size=8",
6643 "--enable-rect-partitions=1",
6644 ])
6645 // Per-arm overrides go AFTER the base recipe: aomenc keeps
6646 // the LAST occurrence of a repeated flag.
6647 .args(*extra)
6648 // The 8-bit twin of the pinned recipe picks a 128-root
6649 // HORZ partition, which this decoder still refuses by name
6650 // ("a 128x128 superblock HORZ/VERT or AB partition") --
6651 // an open refusal of another lane, unrelated to palette.
6652 // Pinning the superblock to 64 keeps the 8-bit arm on the
6653 // shape this gate is about; the 10-bit arms are the
6654 // untouched pinned recipe.
6655 .args(if depth == 8 { &["--sb-size=64"][..] } else { &[][..] })
6656 .args(["--obu", "-o", "-", "-"])
6657 .stdin(Stdio::piped())
6658 .stdout(Stdio::piped())
6659 .stderr(Stdio::piped())
6660 .spawn()
6661 .expect("aomenc failed to start");
6662 child
6663 .stdin
6664 .take()
6665 .expect("aomenc stdin")
6666 .write_all(&y4m)
6667 .or_else(|e| match e.kind() {
6668 // aomenc rejecting the input closes the pipe before we
6669 // finish writing; its own stderr below is the report.
6670 std::io::ErrorKind::BrokenPipe => Ok(()),
6671 _ => Err(e),
6672 })
6673 .expect("writing y4m to aomenc");
6674 let out = child.wait_with_output().expect("aomenc failed to run");
6675 assert!(
6676 out.status.success(),
6677 "{NAME}: aomenc refused {arm} at {depth}-bit: {}",
6678 String::from_utf8_lossy(&out.stderr)
6679 );
6680 let stream = out.stdout;
6681 let before = decode::rect4_palette_hits();
6682 let frames = match decode_stream(&stream) {
6683 Ok(frames) => frames,
6684 // A NAMED refusal is another lane's open shape (here: a
6685 // palette on an 8x8 SQUARE leaf, still out of scope), never
6686 // a pass -- the attempt is counted out of scope and the
6687 // per-depth firing assert below keeps the gate honest.
6688 Err(e) if e.to_string().contains("unsupported") => {
6689 eprintln!("{NAME}: {arm} {depth}-bit REFUSED: {e}");
6690 refused += 1;
6691 continue;
6692 }
6693 Err(e) => panic!("{NAME}: decode failed on {arm} at {depth}-bit: {e}"),
6694 };
6695 let fired = decode::rect4_palette_hits() - before;
6696 let ffmpeg_frames = if depth == 10 {
6697 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
6698 } else {
6699 ffmpeg_decode_sequence(&stream, width, height, frames.len())
6700 };
6701 assert_eq!(
6702 frames.len(),
6703 ffmpeg_frames.len(),
6704 "{NAME}: {arm} at {depth}-bit -- frame count"
6705 );
6706 assert!(!frames.is_empty(), "{NAME}: {arm} at {depth}-bit decoded no frame");
6707 // EVERY decode-order frame, all three planes.
6708 let mut exact = true;
6709 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
6710 if ours.y != theirs.y || ours.u != theirs.u || ours.v != theirs.v {
6711 exact = false;
6712 eprintln!("{NAME}: {arm} {depth}-bit frame {i} differs");
6713 }
6714 frames_compared += 1;
6715 }
6716 if fired > 0 {
6717 fired_arms += 1;
6718 fired_at_depth[usize::from(depth == 10)] += 1;
6719 assert!(
6720 exact,
6721 "{NAME}: {arm} at {depth}-bit has {fired} rect-strip palette block(s) \
6722 and does NOT decode pixel-exact"
6723 );
6724 } else {
6725 out_of_scope += 1;
6726 if !exact {
6727 out_of_scope_mismatch += 1;
6728 }
6729 }
6730 }
6731 }
6732 eprintln!(
6733 "{NAME}: {fired_arms} attempt(s) with a rect-strip palette block, \
6734 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
6735 {refused} refused, {frames_compared} frames compared, \
6736 fired 8-bit={} 10-bit={}",
6737 fired_at_depth[0], fired_at_depth[1]
6738 );
6739 // MEASURED 2026-09-02, every 8-bit attempt of these recipes: aomenc
6740 // puts its palettes on SQUARE blocks at 8 bit and every 8-bit stream
6741 // that reaches a rect strip with one lands on a palette shape still
6742 // out of scope (8x8 square leaf, or a 64x32/32x64 superblock strip
6743 // with a real transform). So the 8-bit arms here prove the DECODE
6744 // path, not the lift -- `fired_at_depth[0] == 0` is a known, reported
6745 // coverage gap and not a silent pass: the counter is printed.
6746 assert!(
6747 fired_at_depth[1] > 0,
6748 "{NAME}: no attempt put a palette on a rect strip \
6749 (8-bit={}, 10-bit={}) -- gate is vacuous",
6750 fired_at_depth[0],
6751 fired_at_depth[1]
6752 );
6753 assert!(fired_arms > 0, "{NAME}: gate is vacuous");
6754 assert_eq!(
6755 out_of_scope_mismatch, 0,
6756 "{NAME}: {out_of_scope_mismatch} attempt(s) without a rect-strip palette block \
6757 still mismatched -- an unrelated defect, not a SKIP"
6758 );
6759 }
6760
6761 /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through
6762 /// this crate's own 10-bit planes (`Picture` widened to `u16` in an
6763 /// earlier round) and checked pixel-exact against ffmpeg's own decode of
6764 /// the identical bytes via [`ffmpeg_decode_sequence_10bit`]. Confirms
6765 /// (hard-asserts, not just trusts) the sequence header this stream
6766 /// actually parses to says `bit_depth == 10` before trusting any pixel
6767 /// match -- a stream that silently fell back to 8-bit would still
6768 /// "match" trivially.
6769 #[test]
6770 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
6771 const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";
6772 if !have_ffmpeg() {
6773 eprintln!("SKIP {NAME}: no ffmpeg");
6774 return;
6775 }
6776 if !have_aomenc() {
6777 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6778 return;
6779 }
6780 let (width, height) = (64usize, 64usize);
6781 let y4m = Command::new("ffmpeg")
6782 .args([
6783 "-v",
6784 "error",
6785 "-f",
6786 "lavfi",
6787 "-i",
6788 &gradients_source(42, width, height, "duration=0.04:rate=25"),
6789 "-pix_fmt",
6790 "yuv420p10le",
6791 "-strict",
6792 "-1",
6793 "-t",
6794 "0.04",
6795 "-f",
6796 "yuv4mpegpipe",
6797 "-",
6798 ])
6799 .stdin(Stdio::null())
6800 .stdout(Stdio::piped())
6801 .stderr(Stdio::piped())
6802 .output()
6803 .expect("ffmpeg failed to run");
6804 assert!(
6805 y4m.status.success(),
6806 "ffmpeg failed to render the 10-bit fixture: {}",
6807 String::from_utf8_lossy(&y4m.stderr)
6808 );
6809 let mut child = Command::new(aomenc_path())
6810 .args([
6811 "--codec=av1",
6812 "--passes=1",
6813 "--end-usage=q",
6814 "--cq-level=30",
6815 "--cpu-used=0",
6816 "--threads=1",
6817 "--row-mt=0",
6818 "--sb-size=64",
6819 "--input-bit-depth=10",
6820 "--bit-depth=10",
6821 "--limit=1",
6822 "--obu",
6823 "-o",
6824 "-",
6825 "-",
6826 ])
6827 .stdin(Stdio::piped())
6828 .stdout(Stdio::piped())
6829 .stderr(Stdio::piped())
6830 .spawn()
6831 .expect("aomenc failed to start");
6832 child
6833 .stdin
6834 .take()
6835 .expect("aomenc stdin")
6836 .write_all(&y4m.stdout)
6837 .expect("writing y4m to aomenc");
6838 let out = child.wait_with_output().expect("aomenc failed to run");
6839 assert!(
6840 out.status.success(),
6841 "aomenc refused the 10-bit fixture: {}",
6842 String::from_utf8_lossy(&out.stderr)
6843 );
6844 let stream = out.stdout;
6845 // Confirm the sequence header this stream actually parses to before
6846 // trusting any pixel comparison below.
6847 let mut probe = Av1Parser::new();
6848 let mut pos = 0usize;
6849 while pos < stream.len() && probe.sequence_header().is_none() {
6850 let obu = probe.parse_obu(&stream[pos..]).unwrap();
6851 pos += obu.total_size;
6852 }
6853 let seq = probe
6854 .sequence_header()
6855 .expect("stream has a sequence header OBU");
6856 assert_eq!(
6857 seq.color_config.bit_depth, 10,
6858 "{NAME}: aomenc did not actually write a 10-bit sequence header"
6859 );
6860 let frames = match decode_stream(&stream) {
6861 Ok(frames) => frames,
6862 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"),
6863 };
6864 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
6865 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)");
6866 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)");
6867 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
6868 }
6869
6870 /// The 10-bit *inter* counterpart of the gate above: a real `aomenc`
6871 /// `yuv420p10le` sequence whose non-key frames are plain forward
6872 /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0
6873 /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate),
6874 /// decoded pixel-exact on every frame. 10-bit intra was proven exact by
6875 /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated.
6876 #[test]
6877 fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() {
6878 const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact";
6879 let _gate_lock = lock_gate_counters();
6880 if !have_ffmpeg() {
6881 eprintln!("SKIP {NAME}: no ffmpeg");
6882 return;
6883 }
6884 if !have_aomenc() {
6885 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6886 return;
6887 }
6888 let (width, height, frame_count) = (128usize, 64usize, 16usize);
6889 let y4m = Command::new("ffmpeg")
6890 .args([
6891 "-v",
6892 "error",
6893 "-f",
6894 "lavfi",
6895 "-i",
6896 &gradients_source(42, width, height, "duration=0.64:rate=25"),
6897 "-pix_fmt",
6898 "yuv420p10le",
6899 "-strict",
6900 "-1",
6901 "-t",
6902 "0.64",
6903 "-f",
6904 "yuv4mpegpipe",
6905 "-",
6906 ])
6907 .stdin(Stdio::null())
6908 .stdout(Stdio::piped())
6909 .stderr(Stdio::piped())
6910 .output()
6911 .expect("ffmpeg failed to run");
6912 assert!(
6913 y4m.status.success(),
6914 "ffmpeg failed to render the 10-bit fixture: {}",
6915 String::from_utf8_lossy(&y4m.stderr)
6916 );
6917 let mut child = Command::new(aomenc_path())
6918 .args([
6919 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
6920 // occurrence, so overrides go before the base list).
6921 "--loopfilter-control=1",
6922 "--codec=av1",
6923 "--passes=1",
6924 "--end-usage=q",
6925 "--cq-level=15",
6926 "--cpu-used=0",
6927 "--threads=1",
6928 "--row-mt=0",
6929 "--sb-size=64",
6930 "--input-bit-depth=10",
6931 "--bit-depth=10",
6932 "--lag-in-frames=0",
6933 "--auto-alt-ref=0",
6934 "--kf-max-dist=1000",
6935 "--error-resilient=1",
6936 "--aq-mode=0",
6937 "--deltaq-mode=0",
6938 "--enable-cdef=0",
6939 "--enable-rect-partitions=0",
6940 "--enable-ab-partitions=0",
6941 "--enable-1to4-partitions=0",
6942 "--enable-filter-intra=0",
6943 "--enable-smooth-intra=0",
6944 "--enable-paeth-intra=0",
6945 "--enable-directional-intra=0",
6946 "--enable-angle-delta=0",
6947 "--enable-tx-size-search=0",
6948 "--enable-cdef=1",
6949 "--enable-restoration=1",
6950 "--min-partition-size=16",
6951 "--max-partition-size=32",
6952 "--enable-palette=0",
6953 "--enable-intrabc=0",
6954 "--enable-cfl-intra=0",
6955 "--enable-ref-frame-mvs=0",
6956 "--obu",
6957 "-o",
6958 "-",
6959 "-",
6960 ])
6961 .stdin(Stdio::piped())
6962 .stdout(Stdio::piped())
6963 .stderr(Stdio::piped())
6964 .spawn()
6965 .expect("aomenc failed to start");
6966 child
6967 .stdin
6968 .take()
6969 .expect("aomenc stdin")
6970 .write_all(&y4m.stdout)
6971 .expect("writing y4m to aomenc");
6972 let out = child.wait_with_output().expect("aomenc failed to run");
6973 assert!(
6974 out.status.success(),
6975 "aomenc refused the 10-bit fixture: {}",
6976 String::from_utf8_lossy(&out.stderr)
6977 );
6978 let stream = out.stdout;
6979 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
6980 std::fs::write(dump, &stream).expect("dump stream");
6981 }
6982 let mut probe = Av1Parser::new();
6983 let mut pos = 0usize;
6984 while pos < stream.len() && probe.sequence_header().is_none() {
6985 let obu = probe.parse_obu(&stream[pos..]).unwrap();
6986 pos += obu.total_size;
6987 }
6988 assert_eq!(
6989 probe
6990 .sequence_header()
6991 .expect("stream has a sequence header OBU")
6992 .color_config
6993 .bit_depth,
6994 10,
6995 "{NAME}: aomenc did not actually write a 10-bit sequence header"
6996 );
6997 let before_deblock = decode::deblock_hits();
6998 let before_inter = decode::inter_pred_hits();
6999 let before_lr = crate::restoration::wiener_hits()
7000 + crate::restoration::sgrproj_hits()
7001 + crate::restoration::switchable_hits();
7002 let frames = match decode_stream(&stream) {
7003 Ok(frames) => frames,
7004 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"),
7005 };
7006 assert!(
7007 decode::inter_pred_hits() > before_inter,
7008 "{NAME}: no inter-predicted block decoded -- the gate proves nothing"
7009 );
7010 assert!(
7011 decode::deblock_hits() > before_deblock,
7012 "{NAME}: no deblocking edge fired -- raise cq-level"
7013 );
7014 // Loop restoration is where the 10-bit inter/intra defect lived
7015 // (lane-hbdinter r1: the self-guided box sums were never brought back
7016 // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened
7017 // to pick RESTORE_NONE would pass while proving nothing.
7018 assert!(
7019 crate::restoration::wiener_hits()
7020 + crate::restoration::sgrproj_hits()
7021 + crate::restoration::switchable_hits()
7022 > before_lr,
7023 "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level"
7024 );
7025 eprintln!(
7026 "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}",
7027 decode::inter_pred_hits() - before_inter,
7028 decode::deblock_hits() - before_deblock,
7029 decode::cdef_idx_hits(),
7030 crate::restoration::wiener_hits(),
7031 crate::restoration::sgrproj_hits(),
7032 );
7033 assert_eq!(frames.len(), frame_count);
7034 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count);
7035 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7036 if got.y != want.y || got.u != want.u || got.v != want.v {
7037 let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu");
7038 let _ = std::fs::write(&pin, &stream);
7039 let first = |a: &Vec<u16>, b: &Vec<u16>| {
7040 a.iter()
7041 .zip(b)
7042 .enumerate()
7043 .find(|(_, (x, y))| x != y)
7044 .map(|(k, (x, y))| (k, *x, *y))
7045 };
7046 panic!(
7047 "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}",
7048 first(&got.y, &want.y),
7049 first(&got.u, &want.u),
7050 first(&got.v, &want.v),
7051 pin.display()
7052 );
7053 }
7054 }
7055 }
7056
7057 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
7058 /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
7059 /// identical bytes (ffmpeg synthesizes grain by default -- no
7060 /// grain-disable flag is passed anywhere in this file). Proves the
7061 /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
7062 /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
7063 /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
7064 /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
7065 /// silent 8-bit fallback nor a stream aomenc emitted without
7066 /// `apply_grain` can make it pass vacuously.
7067 #[test]
7068 fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
7069 const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
7070 if !have_ffmpeg() {
7071 eprintln!("SKIP {NAME}: no ffmpeg");
7072 return;
7073 }
7074 if !have_aomenc() {
7075 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7076 return;
7077 }
7078 let (width, height) = (64usize, 64usize);
7079 let stream = encode_10bit_gradients(
7080 NAME,
7081 width,
7082 height,
7083 1,
7084 &["--film-grain-test=1", "--limit=1"],
7085 );
7086 assert_eq!(
7087 parsed_bit_depth(&stream),
7088 10,
7089 "{NAME}: aomenc did not actually write a 10-bit sequence header"
7090 );
7091 let mut probe = Av1Parser::new();
7092 let mut pos = 0usize;
7093 let mut saw_grain = false;
7094 while pos < stream.len() {
7095 let obu = probe.parse_obu(&stream[pos..]).unwrap();
7096 pos += obu.total_size;
7097 if let ObuKind::Frame(header, _) = obu.kind
7098 && header.film_grain.apply_grain
7099 {
7100 // A grain block whose scaling LUT is empty would blend a
7101 // zero delta into every pixel and let this gate pass without
7102 // the bit-depth math mattering at all.
7103 assert!(
7104 header.film_grain.num_y_points > 0,
7105 "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
7106 );
7107 saw_grain = true;
7108 }
7109 }
7110 assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
7111 let before = crate::film_grain::grain_hits();
7112 let frames = match decode_stream(&stream) {
7113 Ok(frames) => frames,
7114 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
7115 };
7116 assert!(
7117 crate::film_grain::grain_hits() > before,
7118 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
7119 );
7120 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
7121 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
7122 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
7123 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
7124 eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits());
7125 }
7126
7127 /// lane-t900 r29: `fixtures/superres_kf_cdef_lr_64x64.obu` is a real
7128 /// aomenc key frame (64x64 upscaled from a coded 43x64,
7129 /// `--superres-mode=1 --superres-denominator=12 --cpu-used=0 --sb-size=64
7130 /// --enable-cdef=1 --enable-restoration=1 --cq-level=32`) -- the first
7131 /// stream in this repo that runs BOTH in-loop filters under superres.
7132 ///
7133 /// The defect it pins: spec 7.16's upscale runs between CDEF and loop
7134 /// restoration (libaom `superres_post_decode`, `decodeframe.c`, called
7135 /// between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`),
7136 /// but this decoder ran the whole filter chain on the DOWNSCALED frame
7137 /// and upscaled last, in `stream.rs`. Loop restoration therefore filtered
7138 /// downscaled pixels with a unit grid sized from the downscaled width
7139 /// (1873 wrong samples, max 7, on this very stream). Class
7140 /// `wrong-stage-width`: every plane width in the filter chain is either
7141 /// the downscaled one (deblock, CDEF, and the mi grid all three walk) or
7142 /// the upscaled one (loop restoration's `av1_get_upsampled_plane_size`
7143 /// unit grid, `av1_loop_restoration_corners_in_sb`'s `mi_to_num_x`
7144 /// superres arm, and the pixel filters themselves); the sweep is every
7145 /// caller of `apply_deblock`/`apply_cdef`/`apply_loop_restoration` plus
7146 /// `RestorationGrid::new` and `read_lr`.
7147 #[test]
7148 fn a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact() {
7149 const NAME: &str =
7150 "a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact";
7151 let _gate_lock = lock_gate_counters();
7152 if !have_ffmpeg() {
7153 eprintln!("SKIP {NAME}: no ffmpeg");
7154 return;
7155 }
7156 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7157 .join("fixtures/superres_kf_cdef_lr_64x64.obu");
7158 let stream = std::fs::read(&path)
7159 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7160 let (width, height) = (64usize, 64usize);
7161 let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
7162 let frames = match decode_stream(&stream) {
7163 Ok(frames) => frames,
7164 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
7165 };
7166 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
7167 assert_eq!((frames[0].width, frames[0].height), (width, height));
7168 // class `gate-blind-to-feature`: the stream must actually upscale and
7169 // actually run a real restoration filter, or this gate proves nothing.
7170 assert!(
7171 crate::superres::superres_hits() > 0,
7172 "{NAME}: zero superres_hits -- the frame was never upscaled"
7173 );
7174 assert!(
7175 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
7176 "{NAME}: zero restoration units fired -- LR never ran under superres"
7177 );
7178 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
7179 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
7180 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
7181 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
7182 }
7183
7184 /// lane-filt1: `EC_AV1_FILTER_THREADS` splits every in-frame filter stage
7185 /// -- deblock (row bands for the vertical-edge pass, column bands for the
7186 /// horizontal one), CDEF (mi row bands), loop restoration (RU row bands)
7187 /// and film grain (32-pixel block rows) -- across scoped worker threads.
7188 /// A split is only legal if it is BYTE-EXACT, so this gate decodes two
7189 /// real aomenc streams at 1 and at 4 filter threads and compares every
7190 /// output frame's three planes.
7191 ///
7192 /// Between them the fixtures fire all four stages, and the firing
7193 /// counters are asserted rather than assumed (class `gate-blind-to-feature`):
7194 /// `superres_alltools_sb128_320x180.obu` is the 10-bit CDEF + loop
7195 /// restoration stream, `grain_cdef_lr_128x128.obu` a 128x128
7196 /// `--denoise-noise-level=25` stream whose frames carry film grain
7197 /// parameters (small enough that 4 bands is one block row each, which is
7198 /// what exercises the grain band's one-row `prelude` replay).
7199 /// lane-wave1 step (ii): the superblock-row wavefront
7200 /// (`EC_AV1_RECON_THREADS`) reconstructs every output frame byte for
7201 /// byte as the inline path does, on a hidden-ARF 10-bit stream (no-show
7202 /// frames, CfL, 128 superblocks) and on the two screen-content streams
7203 /// whose palette/intrabc blocks READ the current frame's pixels while
7204 /// parsing -- the sites that make the workers barrier.
7205 #[test]
7206 fn a_real_stream_reconstructs_identically_with_one_and_four_recon_threads() {
7207 const NAME: &str = "a_real_stream_reconstructs_identically_with_one_and_four_recon_threads";
7208 let _gate_lock = lock_gate_counters();
7209 for fixture in [
7210 "reelb_arf_witness.obu",
7211 "palette_screen_witness.obu",
7212 "palette_screen_witness_10bit.obu",
7213 ] {
7214 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7215 .join("fixtures")
7216 .join(fixture);
7217 let stream = std::fs::read(&path)
7218 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7219 crate::par::set_recon_threads(1);
7220 let one = match decode_stream(&stream) {
7221 Ok(frames) => frames,
7222 Err(e) => panic!("{NAME}: {fixture} refused at 1 recon thread: {e}"),
7223 };
7224 crate::par::set_recon_threads(4);
7225 let four = match decode_stream(&stream) {
7226 Ok(frames) => frames,
7227 Err(e) => {
7228 crate::par::set_recon_threads(1);
7229 panic!("{NAME}: {fixture} refused at 4 recon threads: {e}")
7230 }
7231 };
7232 crate::par::set_recon_threads(1);
7233 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
7234 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
7235 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
7236 assert_eq!(a.y, b.y, "{NAME}: {fixture} frame {i} luma differs at 4 recon threads");
7237 assert_eq!(a.u, b.u, "{NAME}: {fixture} frame {i} U differs at 4 recon threads");
7238 assert_eq!(a.v, b.v, "{NAME}: {fixture} frame {i} V differs at 4 recon threads");
7239 }
7240 }
7241 }
7242
7243 /// lane-memfix: the pool grows to the peak of `busy + queued` over the
7244 /// job tree and stops there. Before, a job running on a pool worker
7245 /// opened a SECOND pool on that worker's own thread-local -- one level
7246 /// per pipeline stage, none of them ever shrinking -- which is how a 4K
7247 /// decode at `(16, 4, 2)` reached 1038 live threads. Two decodes of the
7248 /// same stream: the count stays inside the composed setting and the
7249 /// second decode adds nothing (the ratchet is what cost the memory).
7250 #[test]
7251 fn the_worker_pool_stays_bounded_across_repeated_threaded_decodes() {
7252 const NAME: &str = "the_worker_pool_stays_bounded_across_repeated_threaded_decodes";
7253 let _gate_lock = lock_gate_counters();
7254 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7255 .join("fixtures")
7256 .join("superres_alltools_sb128_320x180.obu");
7257 let stream = std::fs::read(&path)
7258 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7259 crate::par::set_filter_threads(4);
7260 crate::par::set_recon_threads(2);
7261 let mut counts = [0usize; 2];
7262 let mut frames = [0usize; 2];
7263 for (i, slot) in counts.iter_mut().enumerate() {
7264 let mut n = 0usize;
7265 let r = decode_stream_with_threads(&stream, 4, |_, _, _| {
7266 n += 1;
7267 Ok(())
7268 });
7269 if let Err(e) = r {
7270 crate::par::set_filter_threads(1);
7271 crate::par::set_recon_threads(1);
7272 panic!("{NAME}: refused on decode {i}: {e}");
7273 }
7274 frames[i] = n;
7275 *slot = crate::par::pool_threads();
7276 }
7277 crate::par::set_filter_threads(1);
7278 crate::par::set_recon_threads(1);
7279 assert!(frames[0] > 1, "{NAME}: the fixture decoded {} frames, so nothing was threaded", frames[0]);
7280 // 4 frame workers x (recon 2 + filter 4) plus the two in-flight
7281 // slots `stream.rs` allows over the thread count, with room for the
7282 // show jobs -- 1038 was three orders past this.
7283 assert!(
7284 counts[1] <= 4 * (2 + 4) + 2 * 4,
7285 "{NAME}: the pool grew to {} threads at 4 frame / 4 filter / 2 recon",
7286 counts[1]
7287 );
7288 // The pool grows to `busy + queued`, so a loaded box can queue one
7289 // more job than an idle one did (seen: 9 -> 10 at load 62). The
7290 // bound above is the structural claim; here only a runaway counts.
7291 assert!(
7292 counts[1] <= counts[0] + 4,
7293 "{NAME}: a second decode of the same stream grew the pool from {} to {} threads",
7294 counts[0], counts[1]
7295 );
7296 }
7297
7298 #[test]
7299 fn a_real_stream_filters_identically_with_one_and_four_filter_threads() {
7300 const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads";
7301 let _gate_lock = lock_gate_counters();
7302 for (fixture, wants_lr, wants_grain) in [
7303 ("superres_alltools_sb128_320x180.obu", true, false),
7304 ("grain_cdef_lr_128x128.obu", false, true),
7305 ] {
7306 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7307 .join("fixtures")
7308 .join(fixture);
7309 let stream = std::fs::read(&path)
7310 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7311 let before = (
7312 crate::decode::deblock_hits(),
7313 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
7314 crate::film_grain::grain_hits(),
7315 );
7316 crate::par::set_filter_threads(1);
7317 let one = match decode_stream(&stream) {
7318 Ok(frames) => frames,
7319 Err(e) => panic!("{NAME}: {fixture} refused at 1 filter thread: {e}"),
7320 };
7321 let after = (
7322 crate::decode::deblock_hits(),
7323 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
7324 crate::film_grain::grain_hits(),
7325 );
7326 crate::par::set_filter_threads(4);
7327 let four = match decode_stream(&stream) {
7328 Ok(frames) => frames,
7329 Err(e) => {
7330 crate::par::set_filter_threads(1);
7331 panic!("{NAME}: {fixture} refused at 4 filter threads: {e}")
7332 }
7333 };
7334 crate::par::set_filter_threads(1);
7335 assert!(after.0 > before.0, "{NAME}: {fixture} deblocked no edge at all");
7336 if wants_lr {
7337 assert!(after.1 > before.1, "{NAME}: {fixture} ran no restoration unit");
7338 }
7339 if wants_grain {
7340 assert!(after.2 > before.2, "{NAME}: {fixture} applied no film grain");
7341 }
7342 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
7343 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
7344 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
7345 assert_eq!(a.y, b.y, "{NAME}: {fixture} frame {i} luma differs at 4 filter threads");
7346 assert_eq!(a.u, b.u, "{NAME}: {fixture} frame {i} U differs at 4 filter threads");
7347 assert_eq!(a.v, b.v, "{NAME}: {fixture} frame {i} V differs at 4 filter threads");
7348 }
7349 }
7350 }
7351
7352 /// lane-t900 r30b: `fixtures/superres_alltools_sb128_320x180.obu` is 10
7353 /// frames of `--cpu-used=4 --sb-size=128 --superres-mode=1
7354 /// --superres-denominator=12 --cq-level=32` with every tool aomenc turns
7355 /// on by default (CDEF, loop restoration, OBMC, compound, warp) -- the
7356 /// first stream here that deblocks CHROMA across a group of 4x4 luma
7357 /// blocks.
7358 ///
7359 /// The defect it pins (fixed at this commit, `decode.rs`'s
7360 /// `plane_to_mi`/`edge_params`): `set_lpf_parameters`
7361 /// (`av1_loopfilter.c:245`) indexes the mi grid for a CHROMA edge at
7362 /// `scale | ((coord << scale) >> MI_SIZE_LOG2)` -- the BOTTOM/RIGHT mi of
7363 /// the co-located 8x8 luma group, the same cell that donates the group's
7364 /// chroma prediction. This decoder dropped that `| 1` and read the
7365 /// group's top-left mi, stepped to the previous cell by one mi instead of
7366 /// `1 << ss`, and priced `pu_edge` by comparing mi origins rather than
7367 /// the edge coordinate against the block size in the FILTERED plane's own
7368 /// pixels (chroma bottoms out at 4). All three are invisible while every
7369 /// block is 8x8 or larger (all four mi of a group carry the same tx size,
7370 /// ref frame, skip flag and delta_lf) and wrong the moment cpu-used=4
7371 /// splits a group into 4x4 blocks: on this stream one U sample of frame 2
7372 /// took a filter level of 12 where libaom's neighbouring 4x4 block gives
7373 /// 8, and the error compounded through the reference chain to 280 U + 331
7374 /// V samples (max 9) by frame 9. Class `context-read-from-one-cell`.
7375 ///
7376 /// Post-deblock, this stream is now byte-exact against the instrumented
7377 /// libaom (`EC_AV1_POSTDEBLOCK_DUMP`) in all 10 frames, and the final
7378 /// output matches ffmpeg's.
7379 #[test]
7380 fn a_superres_all_tools_sb128_stream_decodes_pixel_exact() {
7381 const NAME: &str = "a_superres_all_tools_sb128_stream_decodes_pixel_exact";
7382 let _gate_lock = lock_gate_counters();
7383 if !have_ffmpeg() {
7384 eprintln!("SKIP {NAME}: no ffmpeg");
7385 return;
7386 }
7387 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7388 .join("fixtures/superres_alltools_sb128_320x180.obu");
7389 let stream = std::fs::read(&path)
7390 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7391 let (width, height, count) = (320usize, 180usize, 10usize);
7392 let frames = match decode_stream(&stream) {
7393 Ok(frames) => frames,
7394 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
7395 };
7396 assert_eq!(frames.len(), count, "{NAME}: frame count");
7397 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, count);
7398 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7399 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
7400 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
7401 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
7402 }
7403 }
7404
7405 /// lane-golomb r1: THE FILM ITSELF. `crates/ec-av1/fixtures/reelb_head_key_frame.obu`
7406 /// is the first frame of the user's ReelB AV1 release (3840x1608
7407 /// yuv420p10le, `ffmpeg -i <mkv> -c copy -frames:v 1 -f obu`, 147 bytes) --
7408 /// a real 10-bit key frame whose height is NOT a multiple of the 64-pixel
7409 /// superblock, so its last superblock row (mi_row=400 of 402) carries the
7410 /// edge partition symbol this lane fixed: libaom's `ec_read_partition_impl`
7411 /// returns `PARTITION_HORZ` when the gathered `split_or_horz` bit is 0, and
7412 /// this decoder used to READ that bit and throw it away, forcing SPLIT
7413 /// (class `parsed-then-discarded`). The desync surfaced two rows later as
7414 /// "a Golomb tail longer than this decoder reads" -- a refusal naming the
7415 /// symptom, never the cause.
7416 #[test]
7417 fn the_reelb_head_key_frame_decodes_pixel_exact() {
7418 const NAME: &str = "the_reelb_head_key_frame_decodes_pixel_exact";
7419 if !have_ffmpeg() {
7420 eprintln!("SKIP {NAME}: no ffmpeg");
7421 return;
7422 }
7423 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7424 .join("fixtures/reelb_head_key_frame.obu");
7425 let stream = std::fs::read(&path)
7426 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7427 let (width, height) = (3840usize, 1608usize);
7428 let frames = match decode_stream(&stream) {
7429 Ok(frames) => frames,
7430 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
7431 };
7432 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
7433 assert_eq!((frames[0].width, frames[0].height), (width, height));
7434 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
7435 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
7436 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
7437 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
7438 }
7439 /// lane-reelckf r2: `crates/ec-av1/fixtures/reelc_kf2700.obu` is a 1920x792
7440 /// 10-bit AV1 key frame taken out of one of the user's own films
7441 /// (`ffmpeg -ss 2700 -c:v copy -f obu`, then truncated to its first temporal
7442 /// unit, 36 kB) -- the ONLY stream in this repo that contains a SKIPPED
7443 /// `UV_CFL_PRED` block. 30 aomenc recipes (r1's 20 plus r2's chroma-correlated
7444 /// `geq` sweep, cq 40..63, cpu-used 0..2, min/max-partition 4..64, 8 and
7445 /// 10 bit) never made the encoder pick one, so the counter can only be
7446 /// hard-asserted against a real film frame. The instrumented oracle agrees:
7447 /// `EC_TRACE_MODE=1 aomdec` prints 5 `EC_IMODE_VAL ... uv_mode=13 skip=1`
7448 /// lines for this frame.
7449 ///
7450 /// The defect it pins (fixed at 29cd53f, `decode.rs:7719`/`:10528`/`:10891`):
7451 /// a skipped intra block must still PREDICT with CfL -- libaom's
7452 /// `predict_and_reconstruct_intra_block` predicts every plane and guards only
7453 /// the residual on `skip_txfm`. Before the fix this frame had 499 wrong
7454 /// chroma samples (U rows 48..79 cols 464..492); after it, zero.
7455 ///
7456 /// The ffmpeg reference is `ffmpeg -f obu -i <fixture> -f rawvideo
7457 /// -pix_fmt yuv420p10le -` (what `ffmpeg_decode_sequence_10bit` runs).
7458 #[test]
7459 fn a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact() {
7460 const NAME: &str = "a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact";
7461 let path =
7462 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelc_kf2700.obu");
7463 let stream = std::fs::read(&path)
7464 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7465 let (width, height) = (1920usize, 792usize);
7466 let before = crate::decode::reelc_chroma_counters();
7467 let frames = match decode_stream(&stream) {
7468 Ok(frames) => frames,
7469 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
7470 };
7471 let after = crate::decode::reelc_chroma_counters();
7472 let skip_cfl = after.0 - before.0;
7473 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
7474 assert_eq!((frames[0].width, frames[0].height), (width, height));
7475 // Asserted before the ffmpeg compare so an absent ffmpeg cannot make the
7476 // gate vacuous: the skipped-CfL path is exercised on every run.
7477 assert!(
7478 skip_cfl > 0,
7479 "{NAME}: zero skipped-CfL blocks -- the fixture no longer exercises defect 1"
7480 );
7481 if !have_ffmpeg() {
7482 eprintln!("SKIP {NAME} pixel compare: no ffmpeg (skipped_cfl={skip_cfl})");
7483 return;
7484 }
7485 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
7486 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
7487 assert_eq!(
7488 frames[0].u, ffmpeg_frames[0].u,
7489 "{NAME}: U vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
7490 );
7491 assert_eq!(
7492 frames[0].v, ffmpeg_frames[0].v,
7493 "{NAME}: V vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
7494 );
7495 eprintln!("{NAME}: pixel-exact, skipped_cfl={skip_cfl}");
7496 }
7497
7498 /// lane-kf1200 r2: the same film's `-ss 300` key frame, pinned because no
7499 /// aomenc recipe reaches its shape -- a SKIPPED sub-8x8 chroma block whose
7500 /// `uv_mode` is `UV_CFL_PRED`. (lane-reelckf r1 burned 20 recipes across cq
7501 /// 40..63 and nine lavfi sources hunting exactly this block and never got
7502 /// one; ledger dead-end "never produced a SKIPPED 1:4 or sub-8x8 CfL
7503 /// block".) Before the fix the two sub-8x8 skip arms passed `None` for the
7504 /// CfL argument, so the block reconstructed as flat DC and 463 bytes of
7505 /// this frame's chroma were wrong. HARD-asserts `skip_cfl_hits` moved, so
7506 /// the fixture cannot silently stop exercising the arm.
7507 #[test]
7508 fn the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact() {
7509 const NAME: &str = "the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact";
7510 if !have_ffmpeg() {
7511 eprintln!("SKIP {NAME}: no ffmpeg");
7512 return;
7513 }
7514 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7515 .join("fixtures/reelb_ss300_key_frame.obu");
7516 let stream = std::fs::read(&path)
7517 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7518 let (width, height) = (3840usize, 1608usize);
7519 let before = crate::decode::skip_cfl_hits();
7520 let frames = match decode_stream(&stream) {
7521 Ok(frames) => frames,
7522 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
7523 };
7524 let skipped_cfl = crate::decode::skip_cfl_hits() - before;
7525 assert!(
7526 skipped_cfl > 0,
7527 "{NAME}: zero skipped sub-8x8 CfL blocks -- the fixture no longer \
7528 exercises the arm this test exists for"
7529 );
7530 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
7531 assert_eq!((frames[0].width, frames[0].height), (width, height));
7532 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
7533 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
7534 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
7535 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
7536 eprintln!("{NAME}: {skipped_cfl} skipped sub-8x8 CfL chroma blocks, frame pixel-exact");
7537 }
7538
7539 /// lane-kf900 r2: the film's key frame at -ss 900, one frame
7540 /// (`crates/ec-av1/fixtures/reelb_kf900.obu`, 484640 bytes, sha256
7541 /// `a273ae99328388be14a1ff8fa1c5a6d391a9948159eaef120e1b50e02015eb83`,
7542 /// extracted twice from independent
7543 /// `ffmpeg -ss 900 -t 2 -i <2160p AV1 HDR10 mkv> -c:v copy -f obu` runs and
7544 /// truncated to the first frame; both extracts hashed identically).
7545 ///
7546 /// This is the ONLY stream that reaches the r1 defect: a SKIPPED 8x8 intra
7547 /// leaf whose `tx_depth` symbol resolved to `TX_4X4` still publishes 4 --
7548 /// not its 8-pixel block side -- to the next block's `get_tx_size_context`
7549 /// (`set_txfm_ctxs(mbmi->tx_size, bw, bh, skip_txfm && is_inter_block(...))`,
7550 /// `decodemv.c`; the skip term is 0 for intra). It fires 15 times here and
7551 /// zero times across 108 measured aomenc recipes, so the counter is
7552 /// asserted against the film rather than against a synthesised stream.
7553 ///
7554 /// LUMA only. U/V still differ (open residue, lane-kf900 r2: 221 U and
7555 /// 47912 V samples, max |d| 23/2, first at chroma (195, 640) -- chroma
7556 /// RESIDUAL, the prediction there is bit-exact against aomdec's
7557 /// `EC_PREDOUT`), so this gate pins what is proven and no more.
7558 #[test]
7559 fn a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact()
7560 {
7561 const NAME: &str = "a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact";
7562 if !have_ffmpeg() {
7563 eprintln!("SKIP {NAME}: no ffmpeg");
7564 return;
7565 }
7566 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_kf900.obu");
7567 let stream = std::fs::read(&path)
7568 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7569 let (width, height) = (3840usize, 1608usize);
7570 crate::decode::reset_skip_split_tx_hits();
7571 let frames = match decode_stream(&stream) {
7572 Ok(frames) => frames,
7573 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
7574 };
7575 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
7576 assert_eq!((frames[0].width, frames[0].height), (width, height));
7577 assert!(
7578 crate::decode::skip_split_tx_hits() >= 15,
7579 "{NAME}: skip_split_tx_hits() == {} -- the stream that carries the tx-context \
7580 defect stopped carrying it, so this gate proves nothing",
7581 crate::decode::skip_split_tx_hits()
7582 );
7583 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
7584 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
7585 }
7586
7587 /// lane-kf1200 r3: the same film's `-ss 600` key frame (3840x1608, one
7588 /// 8-px partial bottom superblock row), pinned because no aomenc recipe
7589 /// reaches its shape -- a SKIPPED 8x8 intra leaf whose `tx_depth` resolved
7590 /// to TX_4X4. (80 recipes swept this round: 4 frame shapes x 2 sources x
7591 /// cq 32..63 x cpu-used 0/3 x 8/10-bit, all with
7592 /// `--enable-tx-size-search=1 --enable-filter-intra=1`; every one came
7593 /// back with `skip_split_tx_hits == 0`, `lanes/kf1200-r3.report.md`.)
7594 /// An intra block reads `tx_depth` whether or not it is skipped, so the
7595 /// leaf must record its resolved 4 -- not its 8x8 side -- in the txfm
7596 /// context; recording 8 gave the NEXT block's `tx_depth` symbol the wrong
7597 /// `tx_size_cdf` row (ctx 2 where libaom reads 1) and desynced the
7598 /// entropy stream at mi (400,46). HARD-asserts `skip_split_tx_hits` moved.
7599 #[test]
7600 fn the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact() {
7601 const NAME: &str = "the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact";
7602 if !have_ffmpeg() {
7603 eprintln!("SKIP {NAME}: no ffmpeg");
7604 return;
7605 }
7606 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7607 .join("fixtures/reelb_ss600_key_frame.obu");
7608 let stream = std::fs::read(&path)
7609 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7610 let (width, height) = (3840usize, 1608usize);
7611 crate::decode::reset_skip_split_tx_hits();
7612 let frames = match decode_stream(&stream) {
7613 Ok(frames) => frames,
7614 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
7615 };
7616 let skipped_split_tx = crate::decode::skip_split_tx_hits();
7617 assert!(
7618 skipped_split_tx > 0,
7619 "{NAME}: zero skipped 8x8 leaves with a split transform -- the fixture no longer \
7620 exercises the arm this test exists for"
7621 );
7622 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
7623 assert_eq!((frames[0].width, frames[0].height), (width, height));
7624 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
7625 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
7626 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
7627 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
7628 eprintln!("{NAME}: {skipped_split_tx} skipped 8x8 TX_4X4 leaves, frame pixel-exact");
7629 }
7630
7631 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
7632 /// --superres-denominator=12` key frame, decoded pixel-exact against
7633 /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
7634 /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
7635 /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
7636 /// `bit_depth == 10` and `superres_hits > 0`.
7637 #[test]
7638 fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
7639 const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
7640 if !have_ffmpeg() {
7641 eprintln!("SKIP {NAME}: no ffmpeg");
7642 return;
7643 }
7644 if !have_aomenc() {
7645 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7646 return;
7647 }
7648 let (width, height) = (64usize, 64usize);
7649 let stream = encode_10bit_gradients(
7650 NAME,
7651 width,
7652 height,
7653 1,
7654 &[
7655 "--limit=1",
7656 "--kf-max-dist=0",
7657 "--superres-mode=1",
7658 "--superres-denominator=12",
7659 "--superres-kf-denominator=12",
7660 "--enable-rect-partitions=0",
7661 "--enable-ab-partitions=0",
7662 "--enable-1to4-partitions=0",
7663 "--enable-filter-intra=0",
7664 "--enable-smooth-intra=0",
7665 "--enable-paeth-intra=0",
7666 "--enable-directional-intra=0",
7667 "--enable-angle-delta=0",
7668 "--enable-tx-size-search=0",
7669 "--enable-cdef=0",
7670 "--enable-restoration=0",
7671 "--max-partition-size=32",
7672 "--min-partition-size=32",
7673 "--enable-palette=0",
7674 "--enable-intrabc=0",
7675 "--enable-cfl-intra=0",
7676 ],
7677 );
7678 assert_eq!(
7679 parsed_bit_depth(&stream),
7680 10,
7681 "{NAME}: aomenc did not actually write a 10-bit sequence header"
7682 );
7683 let before = crate::superres::superres_hits();
7684 let frames = match decode_stream(&stream) {
7685 Ok(frames) => frames,
7686 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
7687 };
7688 assert!(
7689 crate::superres::superres_hits() > before,
7690 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
7691 );
7692 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
7693 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
7694 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
7695 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
7696 eprintln!(
7697 "{NAME}: pixel-exact, superres_hits={}",
7698 crate::superres::superres_hits()
7699 );
7700 }
7701
7702 /// lane-hbdgates r1: drive one 10-bit aomenc recipe over `seeds`, decode
7703 /// every attempt and pixel-compare every SHOWN frame against ffmpeg's own
7704 /// 10-bit decode of the identical bytes. Per-tool firing counters are
7705 /// sampled PER ATTEMPT and summed only over attempts that decoded *and*
7706 /// compared -- a stream that hit a named refusal contributes nothing
7707 /// (class `counter-from-refused-stream`). Named refusals are tolerated
7708 /// and reported; a pixel mismatch is a hard failure, never a SKIP.
7709 fn ten_bit_tool_gate(
7710 name: &str,
7711 width: usize,
7712 height: usize,
7713 frames: usize,
7714 extra: &[&str],
7715 seeds: &[u32],
7716 counters: &[(&str, fn() -> usize)],
7717 ) {
7718 fn first_diff(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
7719 ours.iter()
7720 .zip(theirs.iter())
7721 .position(|(a, b)| a != b)
7722 .map(|i| {
7723 format!(
7724 "first diff at index {i} (row {}, col {}): ours {} vs ffmpeg {}",
7725 i / width,
7726 i % width,
7727 ours[i],
7728 theirs[i]
7729 )
7730 })
7731 }
7732 let mut totals = vec![0usize; counters.len()];
7733 let mut refusals: Vec<String> = Vec::new();
7734 let mut compared = 0usize;
7735 for &seed in seeds {
7736 let stream = encode_10bit_gradients_seed(name, seed, width, height, frames, extra);
7737 assert_eq!(
7738 parsed_bit_depth(&stream),
7739 10,
7740 "{name}: aomenc did not write a 10-bit sequence header (seed {seed})"
7741 );
7742 let before: Vec<usize> = counters.iter().map(|(_, f)| f()).collect();
7743 let decoded = match decode_stream(&stream) {
7744 Ok(frames) => frames,
7745 Err(e) => {
7746 refusals.push(format!("seed {seed}: {e}"));
7747 continue;
7748 }
7749 };
7750 // Deltas are read BEFORE the pixel compare so a mismatch report
7751 // says whether the tool under test actually fired on the failing
7752 // stream (a mismatch with a zero delta is some other defect).
7753 let deltas: Vec<usize> = counters
7754 .iter()
7755 .zip(before.iter())
7756 .map(|((_, f), b)| f() - b)
7757 .collect();
7758 let fired: Vec<String> = counters
7759 .iter()
7760 .zip(deltas.iter())
7761 .map(|((label, _), d)| format!("{label}={d}"))
7762 .collect();
7763 let fired = fired.join(" ");
7764 let reference = ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len());
7765 assert_eq!(
7766 decoded.len(),
7767 reference.len(),
7768 "{name}: seed {seed}: shown-frame count vs ffmpeg"
7769 );
7770 for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
7771 for (plane, (a, b), w) in [
7772 ("Y", (&ours.y, &theirs.y), width),
7773 ("U", (&ours.u, &theirs.u), width / 2),
7774 ("V", (&ours.v, &theirs.v), width / 2),
7775 ] {
7776 if let Some(d) = first_diff(a, b, w) {
7777 panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]");
7778 }
7779 }
7780 }
7781 compared += 1;
7782 for (i, d) in deltas.iter().enumerate() {
7783 totals[i] += d;
7784 }
7785 }
7786 assert!(
7787 compared > 0,
7788 "{name}: every attempt hit a named refusal:\n{}",
7789 refusals.join("\n")
7790 );
7791 for (i, (label, _)) in counters.iter().enumerate() {
7792 assert!(
7793 totals[i] > 0,
7794 "{name}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
7795 the gate would prove nothing about that tool. refusals:\n{}",
7796 refusals.join("\n")
7797 );
7798 }
7799 let summary: Vec<String> = counters
7800 .iter()
7801 .zip(totals.iter())
7802 .map(|((label, _), t)| format!("{label}={t}"))
7803 .collect();
7804 eprintln!(
7805 "{name}: {compared}/{} attempts pixel-exact, {}",
7806 seeds.len(),
7807 summary.join(" ")
7808 );
7809 }
7810
7811 /// lane-hbdgates r1: the four intra tools that had an 8-bit gate and no
7812 /// 10-bit one (`filter-intra`, `smooth-intra`, `paeth-intra`,
7813 /// `intra-edge-filter`) on ONE real 10-bit `aomenc` key frame, each with
7814 /// its own hard-asserted counter. His two films are yuv420p10le, so an
7815 /// 8-bit-only gate for these tools proves nothing about the streams that
7816 /// matter (lane-covbd r1).
7817 #[test]
7818 fn a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact() {
7819 const NAME: &str = "a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact";
7820 if !have_ffmpeg() {
7821 eprintln!("SKIP {NAME}: no ffmpeg");
7822 return;
7823 }
7824 if !have_aomenc() {
7825 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7826 return;
7827 }
7828 ten_bit_tool_gate(
7829 NAME,
7830 64,
7831 64,
7832 1,
7833 &[
7834 "--limit=1",
7835 "--kf-max-dist=0",
7836 "--enable-filter-intra=1",
7837 "--enable-smooth-intra=1",
7838 "--enable-paeth-intra=1",
7839 "--enable-intra-edge-filter=1",
7840 "--enable-directional-intra=1",
7841 "--enable-angle-delta=0",
7842 "--enable-rect-partitions=0",
7843 "--enable-ab-partitions=0",
7844 "--enable-1to4-partitions=0",
7845 "--enable-tx-size-search=0",
7846 "--enable-cdef=0",
7847 "--enable-restoration=0",
7848 "--max-partition-size=32",
7849 "--min-partition-size=16",
7850 "--enable-palette=0",
7851 "--enable-intrabc=0",
7852 "--enable-cfl-intra=0",
7853 "--enable-ref-frame-mvs=0",
7854 ],
7855 &[42, 7, 11, 23, 31, 57],
7856 &[
7857 ("filter_intra_hits", decode::filter_intra_hits),
7858 ("smooth_pred_hits", crate::intra::smooth_pred_hits),
7859 ("paeth_pred_hits", crate::intra::paeth_pred_hits),
7860 ("intra_edge_filter_hits", crate::intra::intra_edge_filter_hits),
7861 ],
7862 );
7863 }
7864
7865 /// lane-hbdgates r1: `--enable-restoration=1` at 10 bits. Every earlier
7866 /// bit-depth gate ran `--enable-restoration=0`, which is exactly why two
7867 /// high-bit-depth loop-restoration defects survived to 2026-09-01
7868 /// (SGR box sums unscaled, Wiener clamp at the 8-bit bound). Same recipe
7869 /// as the 8-bit LR gate, at 10 bits.
7870 // Written `#[ignore]`d on lane-hbdgates (the branch lacked lane-hbdinter's
7871 // 10-bit LR fix and failed at seed 42, frame 0, Y index 122: ours 351 vs
7872 // ffmpeg 350). Un-ignored on the merge into main 2026-09-01, where the
7873 // SGR box-sum scaling and the Wiener clamp are fixed: 16/16 attempts
7874 // pixel-exact, lr_hits=28.
7875 #[test]
7876 fn a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact() {
7877 const NAME: &str = "a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact";
7878 if !have_ffmpeg() {
7879 eprintln!("SKIP {NAME}: no ffmpeg");
7880 return;
7881 }
7882 if !have_aomenc() {
7883 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7884 return;
7885 }
7886 // 192x128 = 3x2 superblocks, so `read_lr` is re-entered per SB
7887 // (the 8-bit LR gate's own trap warning); cq-level=15 because
7888 // aomenc's RD only picks a non-RESTORE_NONE frame type at low cq.
7889 ten_bit_tool_gate(
7890 NAME,
7891 192,
7892 128,
7893 1,
7894 &[
7895 "--limit=1",
7896 "--kf-max-dist=0",
7897 "--cq-level=15",
7898 "--enable-restoration=1",
7899 "--enable-cdef=0",
7900 "--enable-rect-partitions=0",
7901 "--enable-ab-partitions=0",
7902 "--enable-1to4-partitions=0",
7903 "--enable-filter-intra=0",
7904 "--enable-smooth-intra=0",
7905 "--enable-paeth-intra=0",
7906 "--enable-tx-size-search=0",
7907 "--max-partition-size=32",
7908 "--min-partition-size=16",
7909 "--enable-palette=0",
7910 "--enable-intrabc=0",
7911 "--enable-cfl-intra=0",
7912 "--enable-ref-frame-mvs=0",
7913 ],
7914 &LR_SEEDS,
7915 &[("lr_hits", ten_bit_lr_hits)],
7916 );
7917 }
7918
7919 /// Seeds swept by the 10-bit LR gate (the 8-bit gate needs ~40 attempts
7920 /// to land a non-RESTORE_NONE frame; every attempt here still has to
7921 /// decode pixel-exact).
7922 /// lane-obmcrec r1: the `LR_SEEDS` members whose 1:4-partition stream both
7923 /// fires `obmc_pair_filter_hits` and decodes every frame pixel-exact.
7924 /// Measured over seeds 42..=73 (32 encodes): 43/46/47/65/66 fire and are
7925 /// exact; 70 and 73 fire and mismatch, but mismatch IDENTICALLY with
7926 /// `--enable-obmc=0` (seed 73 frame 1 luma, seed 70 frame 16), so their
7927 /// defect is in the `--min-partition-size=4` recipe, not in OBMC -- kept
7928 /// out of this gate rather than papered over, and reported as open.
7929 const OBMC_PAIR_SEEDS: [u32; 5] = [43, 46, 47, 65, 66];
7930
7931 const LR_SEEDS: [u32; 16] = [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
7932
7933 /// Wiener + SGR + switchable loop-restoration firings, summed.
7934 fn ten_bit_lr_hits() -> usize {
7935 crate::restoration::wiener_hits()
7936 + crate::restoration::sgrproj_hits()
7937 + crate::restoration::switchable_hits()
7938 }
7939
7940 /// lane-reelckf2 r1: loop restoration on frame sizes whose LAST stripe is
7941 /// partial, with 128-sample superblocks -- the two stripe shapes whose
7942 /// boundary substitution is special (`filter_restoration_unit`: the first
7943 /// stripe is 8 rows short and takes its above boundary from the frame's
7944 /// own top rows, the last one is truncated and takes its below boundary
7945 /// from the frame's own bottom row) had no gate at all: every earlier LR
7946 /// size (192x128, 160x96) is a whole multiple of 64 rows and ran at
7947 /// `--sb-size=64`. 152 = 2*64+24 and 216 = 3*64+24 both leave a 32-row
7948 /// tail stripe, mirroring the 792-row 10-bit film that made this lane.
7949 /// `lr_stripe0_hits`/`lr_last_stripe_hits` are hard-asserted per attempt
7950 /// by [`ten_bit_tool_gate`], so an RD that picked RESTORE_NONE on either
7951 /// stripe cannot pass.
7952 #[test]
7953 fn a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact() {
7954 const NAME: &str =
7955 "a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact";
7956 if !have_ffmpeg() {
7957 eprintln!("SKIP {NAME}: no ffmpeg");
7958 return;
7959 }
7960 if !have_aomenc() {
7961 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7962 return;
7963 }
7964 // `--sb-size=128` goes in `extra`, which the helper appends AFTER its
7965 // own `--sb-size=64` (aomenc keeps the LAST occurrence of a repeated
7966 // flag, measured 2026-09-02); `--max-partition-size=32` keeps the 128
7967 // root on SPLIT, the only 128-root partition decoded today.
7968 for (width, height, cq) in [(256usize, 152usize, "15"), (384, 216, "15"), (256, 152, "25")]
7969 {
7970 ten_bit_tool_gate(
7971 &format!("{NAME} {width}x{height} cq{cq}"),
7972 width,
7973 height,
7974 1,
7975 &[
7976 "--limit=1",
7977 "--kf-max-dist=0",
7978 &format!("--cq-level={cq}"),
7979 "--sb-size=128",
7980 "--enable-restoration=1",
7981 "--enable-cdef=0",
7982 "--enable-rect-partitions=0",
7983 "--enable-ab-partitions=0",
7984 "--enable-1to4-partitions=0",
7985 "--enable-filter-intra=0",
7986 "--enable-smooth-intra=0",
7987 "--enable-paeth-intra=0",
7988 "--enable-tx-size-search=0",
7989 "--max-partition-size=32",
7990 "--min-partition-size=16",
7991 "--enable-palette=0",
7992 "--enable-intrabc=0",
7993 "--enable-cfl-intra=0",
7994 "--enable-ref-frame-mvs=0",
7995 ],
7996 &LR_SEEDS,
7997 &[
7998 ("lr_hits", ten_bit_lr_hits),
7999 ("lr_stripe0_hits", crate::restoration::lr_stripe0_hits),
8000 ("lr_last_stripe_hits", crate::restoration::lr_last_stripe_hits),
8001 ],
8002 );
8003 }
8004 }
8005
8006 /// lane-hbdgates r1: `--enable-rect-partitions=1 --enable-ab-partitions=1`
8007 /// at 10 bits, one intra stream, one counter per tool
8008 /// (`rect_partition_hits`, `partab_hits`) so a stream that only fired the
8009 /// rect arms cannot stand in for AB.
8010 #[test]
8011 fn a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact() {
8012 const NAME: &str = "a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact";
8013 if !have_ffmpeg() {
8014 eprintln!("SKIP {NAME}: no ffmpeg");
8015 return;
8016 }
8017 if !have_aomenc() {
8018 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8019 return;
8020 }
8021 // The 8-bit free-partition/AB recipe, verbatim, at 10 bits: AB
8022 // splits are an INTER dispatch here (intra-frame AB is still a named
8023 // refusal), so the stream needs alt-refs and 24 frames, not one key
8024 // frame.
8025 ten_bit_tool_gate(
8026 NAME,
8027 64,
8028 64,
8029 24,
8030 &[
8031 "--cq-level=45",
8032 "--kf-max-dist=1000",
8033 "--auto-alt-ref=1",
8034 "--lag-in-frames=16",
8035 "--enable-fwd-kf=0",
8036 "--enable-order-hint=1",
8037 "--enable-warped-motion=1",
8038 "--enable-obmc=1",
8039 "--tune-content=default",
8040 "--enable-masked-comp=0",
8041 "--enable-interintra-comp=0",
8042 "--enable-onesided-comp=0",
8043 "--enable-interintra-wedge=0",
8044 "--enable-smooth-interintra=0",
8045 "--enable-rect-partitions=1",
8046 "--enable-ab-partitions=1",
8047 "--enable-1to4-partitions=0",
8048 "--enable-filter-intra=0",
8049 "--enable-smooth-intra=0",
8050 "--enable-paeth-intra=0",
8051 "--enable-directional-intra=0",
8052 "--enable-angle-delta=0",
8053 "--enable-tx-size-search=0",
8054 "--enable-cdef=0",
8055 "--enable-restoration=0",
8056 "--max-partition-size=32",
8057 "--min-partition-size=16",
8058 "--enable-palette=0",
8059 "--enable-intrabc=0",
8060 "--enable-cfl-intra=0",
8061 "--enable-ref-frame-mvs=0",
8062 ],
8063 &LR_SEEDS,
8064 &[
8065 ("rect_partition_hits", decode::rect_partition_hits),
8066 ("partab_hits", decode::partab_hits),
8067 ],
8068 );
8069 }
8070
8071 /// lane-obmcrec r1: OBMC whose above/left neighbour is a 4-wide/4-tall
8072 /// 1:4-partition strip -- the shape the three 1080p 10-bit film cuts
8073 /// refused on ("an OBMC neighbour whose switchable interp filter was never
8074 /// recorded"). `overlappable_above`/`_left` snap such a neighbour to the
8075 /// chroma pair's SECOND mi but used to read its interp filter from the
8076 /// FIRST one, a different block whose filter record is the intra
8077 /// `[3, 3]` sentinel whenever that half is intra. `obmc_pair_filter_hits`
8078 /// counts exactly that neighbour shape, so a stream without 1:4 strips
8079 /// next to an OBMC block cannot stand in for it.
8080 #[test]
8081 fn a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact() {
8082 const NAME: &str = "a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact";
8083 if !have_ffmpeg() {
8084 eprintln!("SKIP {NAME}: no ffmpeg");
8085 return;
8086 }
8087 if !have_aomenc() {
8088 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8089 return;
8090 }
8091 ten_bit_tool_gate(
8092 NAME,
8093 128,
8094 128,
8095 24,
8096 &[
8097 "--ec-fixture-noise",
8098 "--cq-level=45",
8099 "--kf-max-dist=1000",
8100 "--auto-alt-ref=1",
8101 "--lag-in-frames=16",
8102 "--enable-fwd-kf=0",
8103 "--enable-order-hint=1",
8104 "--enable-warped-motion=0",
8105 "--enable-obmc=1",
8106 "--tune-content=default",
8107 "--enable-masked-comp=0",
8108 "--enable-interintra-comp=0",
8109 "--enable-onesided-comp=0",
8110 "--enable-interintra-wedge=0",
8111 "--enable-smooth-interintra=0",
8112 "--enable-rect-partitions=1",
8113 "--enable-ab-partitions=0",
8114 "--enable-1to4-partitions=1",
8115 "--enable-filter-intra=0",
8116 "--enable-smooth-intra=0",
8117 "--enable-paeth-intra=0",
8118 "--enable-directional-intra=0",
8119 "--enable-angle-delta=0",
8120 "--enable-tx-size-search=0",
8121 "--enable-cdef=0",
8122 "--enable-restoration=0",
8123 "--max-partition-size=32",
8124 "--min-partition-size=4",
8125 "--enable-palette=0",
8126 "--enable-intrabc=0",
8127 "--enable-cfl-intra=0",
8128 "--enable-ref-frame-mvs=0",
8129 ],
8130 &OBMC_PAIR_SEEDS,
8131 &[("obmc_pair_filter_hits", decode::obmc_pair_filter_hits)],
8132 );
8133 }
8134
8135 /// `bit_depth` of the first sequence header in `stream`.
8136 fn parsed_bit_depth(stream: &[u8]) -> u8 {
8137 let mut probe = Av1Parser::new();
8138 let mut pos = 0usize;
8139 while pos < stream.len() && probe.sequence_header().is_none() {
8140 let obu = probe.parse_obu(&stream[pos..]).unwrap();
8141 pos += obu.total_size;
8142 }
8143 probe
8144 .sequence_header()
8145 .expect("stream has a sequence header OBU")
8146 .color_config
8147 .bit_depth
8148 }
8149
8150 /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and
8151 /// encode it with a real 10-bit `aomenc`, returning the OBU stream.
8152 /// `extra` carries the tool flags under test.
8153 fn encode_10bit_gradients(
8154 name: &str,
8155 width: usize,
8156 height: usize,
8157 frames: usize,
8158 extra: &[&str],
8159 ) -> Vec<u8> {
8160 encode_10bit_gradients_seed(name, 42, width, height, frames, extra)
8161 }
8162
8163 /// As [`encode_10bit_gradients`], but with the fixture seed exposed --
8164 /// lane-hbdgates r1 sweeps seeds so a tool that aomenc's RD declines on
8165 /// one fixture still gets a firing stream.
8166 fn encode_10bit_gradients_seed(
8167 name: &str,
8168 seed: u32,
8169 width: usize,
8170 height: usize,
8171 frames: usize,
8172 extra: &[&str],
8173 ) -> Vec<u8> {
8174 let duration = frames as f64 / 25.0;
8175 // lane-ab32 r1: `--ec-fixture-noise` is not an aomenc flag -- it is a
8176 // fixture request, consumed (and stripped) here: the smooth gradients
8177 // source codes as PARTITION_NONE everywhere, so a partition gate needs
8178 // seeded noise on top of it to give the RD a reason to split.
8179 let noisy = extra.contains(&"--ec-fixture-noise");
8180 let stripped: Vec<&str> = extra
8181 .iter()
8182 .copied()
8183 .filter(|a| *a != "--ec-fixture-noise")
8184 .collect();
8185 let extra: &[&str] = &stripped;
8186 let base = gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
8187 let source = if noisy {
8188 format!("{base},noise=alls=40:all_seed={seed}")
8189 } else {
8190 base
8191 };
8192 let y4m = Command::new("ffmpeg")
8193 .args([
8194 "-v",
8195 "error",
8196 "-f",
8197 "lavfi",
8198 "-i",
8199 &source,
8200 "-pix_fmt",
8201 "yuv420p10le",
8202 "-strict",
8203 "-1",
8204 "-t",
8205 &format!("{duration}"),
8206 "-f",
8207 "yuv4mpegpipe",
8208 "-",
8209 ])
8210 .stdin(Stdio::null())
8211 .stdout(Stdio::piped())
8212 .stderr(Stdio::piped())
8213 .output()
8214 .expect("ffmpeg failed to run");
8215 assert!(
8216 y4m.status.success(),
8217 "{name}: ffmpeg failed to render the 10-bit fixture: {}",
8218 String::from_utf8_lossy(&y4m.stderr)
8219 );
8220 let mut args: Vec<&str> = vec!["--codec=av1", "--passes=1", "--end-usage=q"];
8221 // lane-hbdgates r1: a caller-supplied `--cq-level` REPLACES the
8222 // default rather than being appended after it -- two `--cq-level`
8223 // flags on one aomenc line is a coin flip on which one lands.
8224 if !extra.iter().any(|a| a.starts_with("--cq-level=")) {
8225 args.push("--cq-level=30");
8226 }
8227 args.extend_from_slice(&[
8228 "--cpu-used=0",
8229 "--threads=1",
8230 "--row-mt=0",
8231 "--sb-size=64",
8232 "--input-bit-depth=10",
8233 "--bit-depth=10",
8234 ]);
8235 args.extend_from_slice(extra);
8236 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
8237 let mut child = Command::new(aomenc_path())
8238 .args(&args)
8239 .stdin(Stdio::piped())
8240 .stdout(Stdio::piped())
8241 .stderr(Stdio::piped())
8242 .spawn()
8243 .expect("aomenc failed to start");
8244 child
8245 .stdin
8246 .take()
8247 .expect("aomenc stdin")
8248 .write_all(&y4m.stdout)
8249 .expect("writing y4m to aomenc");
8250 let out = child.wait_with_output().expect("aomenc failed to run");
8251 assert!(
8252 out.status.success(),
8253 "{name}: aomenc refused the 10-bit fixture: {}",
8254 String::from_utf8_lossy(&out.stderr)
8255 );
8256 out.stdout
8257 }
8258
8259 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
8260 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
8261 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
8262 /// which flattened chroma to a single value specifically to avoid
8263 /// exercising this path). Same square-only recipe as the palette-Y gate
8264 /// (`--enable-rect-partitions=0`/`-ab-`/`-1to4-`, fixed 32x32 partition)
8265 /// so a UV palette block never lands inside the still-refused HORZ/VERT
8266 /// screen-content strip. HARD-asserts [`decode::palette_uv_hits`] moved
8267 /// -- a stream that never reads a real UV palette block would decode (or
8268 /// not) by construction without proving this milestone at all
8269 /// ([[gate-blind-to-feature]]).
8270 #[test]
8271 fn a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact() {
8272 const NAME: &str = "a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact";
8273 if !have_ffmpeg() {
8274 eprintln!("SKIP {NAME}: no ffmpeg");
8275 return;
8276 }
8277 if !have_aomenc() {
8278 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8279 return;
8280 }
8281 let source = "testsrc2=size=64x64:rate=25";
8282 fn render(source: &str) -> Vec<u8> {
8283 Command::new("ffmpeg")
8284 .args([
8285 "-v",
8286 "error",
8287 "-f",
8288 "lavfi",
8289 "-i",
8290 source,
8291 "-pix_fmt",
8292 "yuv420p",
8293 "-t",
8294 "0.16",
8295 "-f",
8296 "yuv4mpegpipe",
8297 "-",
8298 ])
8299 .stdin(Stdio::null())
8300 .stdout(Stdio::piped())
8301 .stderr(Stdio::piped())
8302 .output()
8303 .expect("ffmpeg failed to run")
8304 .stdout
8305 }
8306 let y4m_a = render(source);
8307 let y4m_b = render(source);
8308 assert_eq!(
8309 y4m_a, y4m_b,
8310 "testsrc2 must render byte-identical across two runs"
8311 );
8312 let y4m = y4m_a;
8313 let mut child = Command::new(aomenc_path())
8314 .args([
8315 "--codec=av1",
8316 "--passes=1",
8317 "--end-usage=q",
8318 "--cq-level=30",
8319 "--cpu-used=0",
8320 "--threads=1",
8321 "--row-mt=0",
8322 "--sb-size=64",
8323 "--tune-content=screen",
8324 "--enable-palette=1",
8325 "--enable-intrabc=0",
8326 "--enable-rect-partitions=0",
8327 "--enable-ab-partitions=0",
8328 "--enable-1to4-partitions=0",
8329 "--min-partition-size=32",
8330 "--max-partition-size=32",
8331 "--enable-filter-intra=0",
8332 "--enable-cdef=0",
8333 "--enable-restoration=0",
8334 "--enable-tx-size-search=0",
8335 "--loopfilter-control=0",
8336 "--obu",
8337 "-o",
8338 "-",
8339 "-",
8340 ])
8341 .stdin(Stdio::piped())
8342 .stdout(Stdio::piped())
8343 .stderr(Stdio::piped())
8344 .spawn()
8345 .expect("aomenc failed to start");
8346 child
8347 .stdin
8348 .take()
8349 .expect("aomenc stdin")
8350 .write_all(&y4m)
8351 .expect("writing y4m to aomenc");
8352 let out = child.wait_with_output().expect("aomenc failed to run");
8353 assert!(
8354 out.status.success(),
8355 "aomenc refused the fixture: {}",
8356 String::from_utf8_lossy(&out.stderr)
8357 );
8358 let stream = out.stdout;
8359 let before = decode::palette_uv_hits();
8360 let frames = match decode_stream(&stream) {
8361 Ok(frames) => frames,
8362 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
8363 };
8364 assert!(
8365 decode::palette_uv_hits() > before,
8366 "palette_uv_mode never fired decoding this stream -- gate is vacuous"
8367 );
8368 let frame_count = frames.len();
8369 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, frame_count);
8370 for i in 0..frame_count {
8371 assert_eq!(frames[i].y, ffmpeg_frames[i].y, "luma vs ffmpeg, frame {i}");
8372 assert_eq!(frames[i].u, ffmpeg_frames[i].u, "U vs ffmpeg, frame {i}");
8373 assert_eq!(frames[i].v, ffmpeg_frames[i].v, "V vs ffmpeg, frame {i}");
8374 }
8375 }
8376
8377 /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT
8378 /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect`
8379 /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a
8380 /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc
8381 /// partition FIRST on every size/cq combo probed -- `--enable-ab-
8382 /// partitions=0` measurably does not stop aomenc choosing one at this
8383 /// screen-content tune (byte-identical output with `=0` vs `=1`, same
8384 /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing
8385 /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code
8386 /// path: the only choices left at the (single, key-frame) superblock are
8387 /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`],
8388 /// and a size/cq sweep (measured live this round) reliably lands
8389 /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both
8390 /// sources. Drives `decode_stream` directly (below any refusal) and
8391 /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that
8392 /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) --
8393 /// a decode that never lands a rect palette block is not a match.
8394 #[test]
8395 fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() {
8396 const NAME: &str = "a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact";
8397 let _gate_lock = lock_gate_counters();
8398 if !have_ffmpeg() {
8399 eprintln!("SKIP {NAME}: no ffmpeg");
8400 return;
8401 }
8402 if !have_aomenc() {
8403 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8404 return;
8405 }
8406 let mut matched = 0u32;
8407 let mut uncounted_exact = 0u32;
8408 let mut named_refusals = 0u32;
8409 let mut attempts = 0u32;
8410 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
8411 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
8412 for src_name in ["smptebars", "rgbtestsrc"] {
8413 for (width, height) in sizes {
8414 for cq in cqs {
8415 attempts += 1;
8416 let source = format!("{src_name}=size={width}x{height}:rate=25");
8417 let y4m = Command::new("ffmpeg")
8418 .args([
8419 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p",
8420 "-t", "0.04", "-f", "yuv4mpegpipe", "-",
8421 ])
8422 .stdin(Stdio::null())
8423 .stdout(Stdio::piped())
8424 .stderr(Stdio::piped())
8425 .output()
8426 .expect("ffmpeg failed to run");
8427 assert!(
8428 y4m.status.success(),
8429 "ffmpeg fixture: {}",
8430 String::from_utf8_lossy(&y4m.stderr)
8431 );
8432 let cq_arg = format!("--cq-level={cq}");
8433 let mut child = Command::new(aomenc_path())
8434 .args([
8435 "--codec=av1",
8436 "--passes=1",
8437 "--end-usage=q",
8438 &cq_arg,
8439 "--cpu-used=4",
8440 "--threads=1",
8441 "--row-mt=0",
8442 "--sb-size=64",
8443 "--enable-palette=1",
8444 "--min-partition-size=16",
8445 "--max-partition-size=64",
8446 "--obu",
8447 "-o",
8448 "-",
8449 "-",
8450 ])
8451 .stdin(Stdio::piped())
8452 .stdout(Stdio::piped())
8453 .stderr(Stdio::piped())
8454 .spawn()
8455 .expect("aomenc failed to start");
8456 child
8457 .stdin
8458 .take()
8459 .expect("aomenc stdin")
8460 .write_all(&y4m.stdout)
8461 .expect("writing y4m to aomenc");
8462 let out = child.wait_with_output().expect("aomenc failed to run");
8463 assert!(
8464 out.status.success(),
8465 "aomenc refused the fixture ({source} cq={cq}): {}",
8466 String::from_utf8_lossy(&out.stderr)
8467 );
8468 let stream = out.stdout;
8469 let before = crate::decode::palette_rect_hits();
8470 let frames = match decode_stream(&stream) {
8471 Err(e) => {
8472 let msg = e.to_string();
8473 assert!(
8474 msg.contains("unsupported"),
8475 "{NAME} failed outright, not a named refusal \
8476 ({source} cq={cq}): {msg}"
8477 );
8478 named_refusals += 1;
8479 eprintln!("{source} cq={cq}: refusal: {msg}");
8480 continue;
8481 }
8482 Ok(frames) => frames,
8483 };
8484 // A successful decode is ALWAYS pixel-compared; the hit
8485 // counter only decides whether the attempt counts toward
8486 // the hit-asserting total (class
8487 // [[gate-skips-on-its-own-failure]]: the old `continue`
8488 // here let 16/70 decoded attempts past without any pixel
8489 // check at all).
8490 let counted = crate::decode::palette_rect_hits() != before;
8491 if !counted {
8492 eprintln!(
8493 "{NAME}: {source} cq={cq} decoded without ever landing a rect \
8494 palette block (palette_rect_hits unchanged) -- pixel-compared, \
8495 not counted toward the hit assertion"
8496 );
8497 }
8498 let frame_count = frames.len();
8499 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
8500 if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| {
8501 got.y != want.y || got.u != want.u || got.v != want.v
8502 }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
8503 {
8504 std::fs::write(&path, &stream).expect("writing pinned stream");
8505 eprintln!(
8506 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
8507 );
8508 }
8509 for i in 0..frame_count {
8510 assert_eq!(
8511 frames[i].y, ffmpeg_frames[i].y,
8512 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
8513 );
8514 assert_eq!(
8515 frames[i].u, ffmpeg_frames[i].u,
8516 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
8517 );
8518 assert_eq!(
8519 frames[i].v, ffmpeg_frames[i].v,
8520 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
8521 );
8522 }
8523 if counted {
8524 matched += 1;
8525 } else {
8526 uncounted_exact += 1;
8527 }
8528 }
8529 }
8530 }
8531 assert!(
8532 matched > 0,
8533 "{NAME}: no attempt out of {attempts} ever landed a matching rect palette \
8534 block ({named_refusals} named refusals) -- palette_rect_hits never proven \
8535 pixel-exact"
8536 );
8537 eprintln!(
8538 "{NAME}: {matched}/{attempts} attempts matched pixel-exact, \
8539 {uncounted_exact} decoded-and-pixel-exact but uncounted, {named_refusals} \
8540 named refusals, palette_rect_hits={}",
8541 crate::decode::palette_rect_hits()
8542 );
8543 }
8544
8545 /// The BROAD case (lane-palette2 r6, per its charter): a HORZ/VERT intra
8546 /// strip in a screen-content-tools frame that does NOT necessarily use a
8547 /// palette. This is what the refusal r4 removed actually guarded --
8548 /// [`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`] above
8549 /// gates the rarer "and picks a palette" case, which r5 measured RD
8550 /// almost never chooses -- 39/70 of that same sweep DID land here (a
8551 /// clean rect-strip decode with `palette_rect_hits` unchanged), just
8552 /// uncounted by r5's narrower assertion. Same `--min/max-partition-size=64`
8553 /// recipe r5 measured live to dodge the 32x32-level AB-partition quirk
8554 /// ([[lane-sbpart-r2]]), single key frame, size/cq sweep. HARD-asserts
8555 /// [`decode::rect_screen_content_hits`] moved -- proof this stream
8556 /// actually ran [`read_intra_mode_rect`]'s screen-content-tools branch --
8557 /// before comparing pixels.
8558 #[test]
8559 fn a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact() {
8560 const NAME: &str = "a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact";
8561 let _gate_lock = lock_gate_counters();
8562 if !have_ffmpeg() {
8563 eprintln!("SKIP {NAME}: no ffmpeg");
8564 return;
8565 }
8566 if !have_aomenc() {
8567 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8568 return;
8569 }
8570 let mut matched = 0u32;
8571 // Blocks that reconstructed a palette-Y prediction through a SPLIT
8572 // luma transform (lane-palette2 r7's lifted refusal): the same
8573 // screen-content streams exercise it, so this gate proves both.
8574 let mut split_palette_matched = 0u32;
8575 let mut uncounted_exact = 0u32;
8576 let mut named_refusals = 0u32;
8577 let mut attempts = 0u32;
8578 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
8579 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
8580 for src_name in ["smptebars", "rgbtestsrc"] {
8581 for (width, height) in sizes {
8582 for cq in cqs {
8583 attempts += 1;
8584 let source = format!("{src_name}=size={width}x{height}:rate=25");
8585 let y4m = Command::new("ffmpeg")
8586 .args([
8587 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p",
8588 "-t", "0.04", "-f", "yuv4mpegpipe", "-",
8589 ])
8590 .stdin(Stdio::null())
8591 .stdout(Stdio::piped())
8592 .stderr(Stdio::piped())
8593 .output()
8594 .expect("ffmpeg failed to run");
8595 assert!(
8596 y4m.status.success(),
8597 "ffmpeg fixture: {}",
8598 String::from_utf8_lossy(&y4m.stderr)
8599 );
8600 let cq_arg = format!("--cq-level={cq}");
8601 let mut child = Command::new(aomenc_path())
8602 .args([
8603 "--codec=av1",
8604 "--passes=1",
8605 "--end-usage=q",
8606 &cq_arg,
8607 "--cpu-used=4",
8608 "--threads=1",
8609 "--row-mt=0",
8610 "--sb-size=64",
8611 "--enable-palette=1",
8612 "--min-partition-size=16",
8613 "--max-partition-size=64",
8614 "--obu",
8615 "-o",
8616 "-",
8617 "-",
8618 ])
8619 .stdin(Stdio::piped())
8620 .stdout(Stdio::piped())
8621 .stderr(Stdio::piped())
8622 .spawn()
8623 .expect("aomenc failed to start");
8624 child
8625 .stdin
8626 .take()
8627 .expect("aomenc stdin")
8628 .write_all(&y4m.stdout)
8629 .expect("writing y4m to aomenc");
8630 let out = child.wait_with_output().expect("aomenc failed to run");
8631 assert!(
8632 out.status.success(),
8633 "aomenc refused the fixture ({source} cq={cq}): {}",
8634 String::from_utf8_lossy(&out.stderr)
8635 );
8636 let stream = out.stdout;
8637 let before = crate::decode::rect_screen_content_hits();
8638 let split_before = crate::decode::palette_split_tx_hits();
8639 let frames = match decode_stream(&stream) {
8640 Err(e) => {
8641 let msg = e.to_string();
8642 assert!(
8643 msg.contains("unsupported"),
8644 "{NAME} failed outright, not a named refusal \
8645 ({source} cq={cq}): {msg}"
8646 );
8647 named_refusals += 1;
8648 eprintln!("{source} cq={cq}: refusal: {msg}");
8649 continue;
8650 }
8651 Ok(frames) => frames,
8652 };
8653 // Same integrity rule as the palette gate above: decoded
8654 // means pixel-compared, counter or no counter.
8655 let counted = crate::decode::rect_screen_content_hits() != before;
8656 if !counted {
8657 eprintln!(
8658 "{NAME}: {source} cq={cq} decoded without ever running the rect \
8659 screen-content path (rect_screen_content_hits unchanged) -- \
8660 pixel-compared, not counted toward the hit assertion"
8661 );
8662 }
8663 let frame_count = frames.len();
8664 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
8665 if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| {
8666 got.y != want.y || got.u != want.u || got.v != want.v
8667 }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
8668 {
8669 std::fs::write(&path, &stream).expect("writing pinned stream");
8670 eprintln!(
8671 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
8672 );
8673 }
8674 for i in 0..frame_count {
8675 assert_eq!(
8676 frames[i].y, ffmpeg_frames[i].y,
8677 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
8678 );
8679 assert_eq!(
8680 frames[i].u, ffmpeg_frames[i].u,
8681 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
8682 );
8683 assert_eq!(
8684 frames[i].v, ffmpeg_frames[i].v,
8685 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
8686 );
8687 }
8688 if counted {
8689 matched += 1;
8690 } else {
8691 uncounted_exact += 1;
8692 }
8693 if counted && crate::decode::palette_split_tx_hits() > split_before {
8694 split_palette_matched += 1;
8695 }
8696 }
8697 }
8698 }
8699 assert!(
8700 split_palette_matched > 0,
8701 "{NAME}: no pixel-exact attempt ever reconstructed a palette block with a \
8702 split luma transform -- the lifted refusal is ungated"
8703 );
8704 assert!(
8705 matched > 0,
8706 "{NAME}: no attempt out of {attempts} ever landed a matching rect \
8707 screen-content block ({named_refusals} named refusals) -- \
8708 rect_screen_content_hits never proven pixel-exact"
8709 );
8710 eprintln!(
8711 "{NAME}: {matched}/{attempts} attempts matched pixel-exact \
8712 ({split_palette_matched} of them through a split-transform palette block), \
8713 {uncounted_exact} decoded-and-pixel-exact but uncounted, \
8714 {named_refusals} named refusals, rect_screen_content_hits={}, \
8715 palette_split_tx_hits={}",
8716 crate::decode::rect_screen_content_hits(),
8717 crate::decode::palette_split_tx_hits()
8718 );
8719 }
8720
8721 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
8722 /// harness, but with the deblocking filter left *on* (no
8723 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
8724 /// picks a nonzero level -- proves `apply_deblock` itself, not just that
8725 /// this decoder still works when every edge lands on level 0. CDEF
8726 /// stays off so a pixel mismatch can only come from the loop filter.
8727 #[test]
8728 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {
8729 if !have_ffmpeg() {
8730 eprintln!(
8731 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no ffmpeg"
8732 );
8733 return;
8734 }
8735 if !have_aomenc() {
8736 eprintln!(
8737 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no aomenc at {}",
8738 aomenc_path().display()
8739 );
8740 return;
8741 }
8742 let (width, height) = (64usize, 64usize);
8743 let source = gradients_source(42, width, height, "duration=0.04:rate=25");
8744 let y4m = Command::new("ffmpeg")
8745 .args(["-v", "error", "-f", "lavfi", "-i"])
8746 .arg(&source)
8747 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
8748 .stdin(Stdio::null())
8749 .stdout(Stdio::piped())
8750 .stderr(Stdio::piped())
8751 .output()
8752 .expect("ffmpeg failed to run");
8753 assert!(
8754 y4m.status.success(),
8755 "ffmpeg fixture: {}",
8756 String::from_utf8_lossy(&y4m.stderr)
8757 );
8758 let mut child = Command::new(aomenc_path())
8759 .args([
8760 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
8761 // occurrence, so overrides go before the base list).
8762 "--loopfilter-control=1",
8763 "--codec=av1",
8764 "--passes=1",
8765 "--end-usage=q",
8766 "--cq-level=55",
8767 "--cpu-used=0",
8768 "--enable-filter-intra=0",
8769 "--enable-smooth-intra=0",
8770 "--enable-paeth-intra=0",
8771 "--enable-directional-intra=0",
8772 "--enable-angle-delta=0",
8773 "--enable-tx-size-search=0",
8774 "--enable-cdef=0",
8775 // Loop restoration is a named refusal (aomenc's RD picks
8776 // Sgrproj on this kind of content) -- off in every recipe
8777 // whose test targets a different surface.
8778 "--enable-restoration=0",
8779 "--max-partition-size=32",
8780 "--enable-palette=0",
8781 "--enable-intrabc=0",
8782 "--enable-cfl-intra=0",
8783 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
8784 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
8785 "--enable-ref-frame-mvs=0",
8786 "--obu",
8787 "-o",
8788 "-",
8789 "-",
8790 ])
8791 .stdin(Stdio::piped())
8792 .stdout(Stdio::piped())
8793 .stderr(Stdio::piped())
8794 .spawn()
8795 .expect("aomenc failed to start");
8796 child
8797 .stdin
8798 .take()
8799 .expect("aomenc stdin")
8800 .write_all(&y4m.stdout)
8801 .expect("writing y4m to aomenc");
8802 let out = child.wait_with_output().expect("aomenc failed to run");
8803 assert!(
8804 out.status.success(),
8805 "aomenc refused the fixture: {}",
8806 String::from_utf8_lossy(&out.stderr)
8807 );
8808 let stream = out.stdout;
8809 let before = decode::deblock_hits();
8810 let frames = match decode_stream(&stream) {
8811 Ok(frames) => frames,
8812 Err(e) => {
8813 eprintln!(
8814 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: {e}"
8815 );
8816 return;
8817 }
8818 };
8819 assert!(
8820 decode::deblock_hits() > before,
8821 "no deblocking edge fired decoding this stream -- raise cq-level"
8822 );
8823 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
8824 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
8825 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
8826 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
8827 }
8828
8829 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],
8830 /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other
8831 /// recipe in this file pins off specifically to keep the stream on
8832 /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick
8833 /// `TxMode::Select` and split some blocks' luma transform below their own
8834 /// side (spec 5.11.16), which is what this test's `tx_depth_hits()`
8835 /// counter proves actually happened -- a stream that resolves every
8836 /// `tx_depth` to 0 would pixel-match by construction (identical to
8837 /// `TxMode::Largest`) without exercising the new split-TU decode path at
8838 /// all. Same multi-seed retry shape as
8839 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]:
8840 /// aomenc's own RD is free (with tx-size search on) to also occasionally
8841 /// pick `allow_screen_content_tools` on this content, a separate,
8842 /// already-named refusal -- try several seeds, and the first stream that
8843 /// both decodes AND actually split a transform must be pixel-exact.
8844 #[test]
8845 fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() {
8846 if !have_ffmpeg() {
8847 eprintln!(
8848 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg"
8849 );
8850 return;
8851 }
8852 if !have_aomenc() {
8853 eprintln!(
8854 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}",
8855 aomenc_path().display()
8856 );
8857 return;
8858 }
8859 let (width, height) = (64usize, 64usize);
8860 let mut refusals = Vec::new();
8861 let mut uncounted_exact = 0u32;
8862 for attempt in 0..40u32 {
8863 let seed = 42 + attempt;
8864 // A flat gradient never has enough local detail for the RD
8865 // search to prefer a split transform over the block's own full
8866 // size -- `mandelbrot`'s fractal boundary gives every attempt
8867 // (a different `start_scale`) sharp, varied-frequency edges.
8868 // start_scale 5.0 is the proven first try (decodes pixel-exact
8869 // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs);
8870 // later attempts walk down for variety when aomenc's RD flips
8871 // elsewhere.
8872 let source = format!(
8873 "mandelbrot=size=64x64:start_scale={}:rate=25",
8874 5.0 - f64::from(attempt) * 0.06
8875 );
8876 let y4m = Command::new("ffmpeg")
8877 .args([
8878 "-v",
8879 "error",
8880 "-f",
8881 "lavfi",
8882 "-i",
8883 &source,
8884 // Desaturated: chroma stays flat (constant 128) so
8885 // `uv_mode` always resolves to `DC_PRED` and this
8886 // decoder's still-unsupported directional-chroma round-2
8887 // gap never fires, leaving the luma detail alone to
8888 // drive whether `TxMode::Select`'s RD splits a block.
8889 "-vf",
8890 "hue=s=0",
8891 "-pix_fmt",
8892 "yuv420p",
8893 "-t",
8894 "0.04",
8895 "-f",
8896 "yuv4mpegpipe",
8897 "-",
8898 ])
8899 .stdin(Stdio::null())
8900 .stdout(Stdio::piped())
8901 .stderr(Stdio::piped())
8902 .output()
8903 .expect("ffmpeg failed to run");
8904 assert!(
8905 y4m.status.success(),
8906 "ffmpeg fixture: {}",
8907 String::from_utf8_lossy(&y4m.stderr)
8908 );
8909 let mut child = Command::new(aomenc_path())
8910 .args([
8911 "--codec=av1",
8912 "--passes=1",
8913 "--end-usage=q",
8914 "--cq-level=45",
8915 "--cpu-used=0",
8916 "--enable-rect-partitions=0",
8917 "--enable-ab-partitions=0",
8918 "--enable-1to4-partitions=0",
8919 "--enable-filter-intra=0",
8920 // Every non-DC intra tool off: directional chroma and
8921 // angle deltas are separate round-2 gaps, and DC-only
8922 // residual is exactly what gives the RD search a reason
8923 // to split a transform.
8924 "--enable-smooth-intra=0",
8925 "--enable-paeth-intra=0",
8926 "--enable-directional-intra=0",
8927 "--enable-angle-delta=0",
8928 "--enable-cdef=0",
8929 // Loop restoration is a named refusal (aomenc's RD picks
8930 // Sgrproj on this kind of content) -- off in every recipe
8931 // whose test targets a different surface.
8932 "--enable-restoration=0",
8933 "--max-partition-size=32",
8934 // 16x16 blocks are what split into the TX8 TUs whose
8935 // set-1 tx_type rows this gate exists to prove; some
8936 // scales resolve depth 2 (TX4, a named refusal) and the
8937 // attempt loop just moves on.
8938 "--min-partition-size=16",
8939 "--enable-palette=0",
8940 "--enable-intrabc=0",
8941 "--enable-cfl-intra=0",
8942 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
8943 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
8944 "--enable-ref-frame-mvs=0",
8945 "--obu",
8946 "-o",
8947 "-",
8948 "-",
8949 ])
8950 .stdin(Stdio::piped())
8951 .stdout(Stdio::piped())
8952 .stderr(Stdio::piped())
8953 .spawn()
8954 .expect("aomenc failed to start");
8955 child
8956 .stdin
8957 .take()
8958 .expect("aomenc stdin")
8959 .write_all(&y4m.stdout)
8960 .expect("writing y4m to aomenc");
8961 let out = child.wait_with_output().expect("aomenc failed to run");
8962 assert!(
8963 out.status.success(),
8964 "aomenc refused the fixture: {}",
8965 String::from_utf8_lossy(&out.stderr)
8966 );
8967 let stream = out.stdout;
8968 let before = decode::tx_depth_hits();
8969 let frames = match decode_stream(&stream) {
8970 Ok(frames) => frames,
8971 Err(e) => {
8972 refusals.push(format!("seed {seed}: {e}"));
8973 continue;
8974 }
8975 };
8976 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
8977 // is ALWAYS pixel-compared below; the hit counter only decides whether
8978 // the attempt counts toward the firing total.
8979 let counted = decode::tx_depth_hits() != before;
8980 if !counted {
8981 uncounted_exact += 1;
8982 refusals.push(format!(
8983 "seed {seed}: decoded and pixel-compared, but no block resolved a split \
8984 tx_depth"
8985 ));
8986 }
8987 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
8988 assert_eq!(
8989 frames[0].y, ffmpeg_frames[0].y,
8990 "luma vs ffmpeg (seed {seed})"
8991 );
8992 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
8993 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
8994 if counted {
8995 gate_buckets(
8996 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
8997 1,
8998 uncounted_exact,
8999 refusals.len() - uncounted_exact as usize,
9000 );
9001 return;
9002 }
9003 }
9004 gate_buckets(
9005 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
9006 0,
9007 uncounted_exact,
9008 refusals.len() - uncounted_exact as usize,
9009 );
9010 eprintln!(
9011 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \
9012 hit a named refusal or never split a transform:\n{}",
9013 refusals.join("\n")
9014 );
9015 }
9016
9017 /// lane-txselect's decisive gate: a real aomenc INTER sequence WITHOUT
9018 /// `--enable-tx-size-search=0`, the flag every other inter recipe in this
9019 /// file pins off precisely to keep the stream on `TxMode::Largest`.
9020 /// Dropped, aomenc takes its own default (`TX_MODE_SELECT` -- which is
9021 /// what both of the user's real films use), and an inter block's
9022 /// transform size is then the recursive `txfm_split` tree of spec
9023 /// 5.11.17 rather than one whole-block transform. A stream that decoded
9024 /// pixel-exact while every `txfm_split` symbol resolved to "no split"
9025 /// would prove nothing (it is `TxMode::Largest` by another name), so this
9026 /// gate hard-asserts BOTH counters: at least one `txfm_split` symbol read
9027 /// AND at least one split actually taken. Exhausting every attempt is a
9028 /// FAILURE, not a SKIP -- an unfired gate is a vacuous gate.
9029 #[test]
9030 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact() {
9031 tx_select_inter_gate(8);
9032 }
9033
9034 /// The 10-bit arm of the gate above (lane-txselect r2): both of the
9035 /// user's films are `yuv420p10le` and var-tx is exactly the tool they
9036 /// use, so an 8-bit-only proof would not reach them. Same recipe plus
9037 /// `-b 10 --input-bit-depth=10`.
9038 #[test]
9039 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact_10bit() {
9040 tx_select_inter_gate(10);
9041 }
9042
9043 /// lane-intrarect r1's decisive gate: a real aomenc INTER sequence whose
9044 /// hard mid-GOP content cut makes aomenc code INTRA blocks inside inter
9045 /// frames, with rect partitions ON so those intra blocks land on
9046 /// HORZ/VERT strip shapes. Every such block was the named refusal "an
9047 /// intra-coded HORZ/VERT strip needs rectangular intra prediction this
9048 /// decoder does not code yet" until this round; they now decode through
9049 /// the same `decode_rect_split` machinery the key-frame rect paths use.
9050 ///
9051 /// Hard-asserts per-shape counters (`intra_rect_strip_in_inter_hits`:
9052 /// 0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16) summed over the
9053 /// attempts that were actually pixel-compared -- at least TWO of the
9054 /// three shape classes must fire, so a green run cannot come from one
9055 /// lucky size. A decode that succeeds is ALWAYS pixel-compared (class
9056 /// [[gate-skips-on-its-own-failure]]); exhausting every attempt without
9057 /// two shapes is a FAILURE, never a SKIP.
9058 #[test]
9059 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact() {
9060 intra_rect_in_inter_gate(8);
9061 }
9062
9063 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
9064 #[test]
9065 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact_10bit() {
9066 intra_rect_in_inter_gate(10);
9067 }
9068
9069 fn intra_rect_in_inter_gate(bit_depth: u32) {
9070 const NAME: &str = "a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact";
9071 if !have_ffmpeg() {
9072 eprintln!("SKIP {NAME}: no ffmpeg");
9073 return;
9074 }
9075 if !have_aomenc() {
9076 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9077 return;
9078 }
9079 let (width, height, frame_count) = (96usize, 96usize, 8usize);
9080 let mut refusals: Vec<String> = Vec::new();
9081 let mut uncounted_exact = 0u32;
9082 let mut compared = 0u32;
9083 let mut shapes = [0usize; 3];
9084 for attempt in 0..45u32 {
9085 let seed = 42 + attempt;
9086 // mandelbrot's fractal detail plus a HARD cut at frame 4: half
9087 // the picture becomes a flat white box, which no motion vector
9088 // can predict, so aomenc's RD codes those blocks INTRA inside an
9089 // inter frame. The box's vertical edge at x=48 is what makes the
9090 // partition search reach for HORZ/VERT strips there.
9091 // A FAST ZOOM: `end_scale`/`end_pts` make mandelbrot rush
9092 // through its own zoom, so consecutive frames share almost no
9093 // content and aomenc's RD codes blocks INTRA inside INTER frames
9094 // (`--kf-min-dist=1000` forbids a new key frame). That is the
9095 // only way a real encoder reaches this decoder's intra-in-inter
9096 // arm; a slowly-evolving source codes every rect strip inter.
9097 let source = format!(
9098 "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25",
9099 5.0 - f64::from(attempt) * 0.06
9100 );
9101 let y4m = Command::new("ffmpeg")
9102 .args([
9103 "-v",
9104 "error",
9105 "-f",
9106 "lavfi",
9107 "-i",
9108 &source,
9109 "-vf",
9110 "hue=s=0",
9111 "-pix_fmt",
9112 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
9113 "-strict",
9114 "-1",
9115 "-t",
9116 "0.32",
9117 "-f",
9118 "yuv4mpegpipe",
9119 "-strict",
9120 "-1",
9121 "-",
9122 ])
9123 .stdin(Stdio::null())
9124 .stdout(Stdio::piped())
9125 .stderr(Stdio::piped())
9126 .output()
9127 .expect("ffmpeg failed to run");
9128 assert!(
9129 y4m.status.success(),
9130 "ffmpeg fixture: {}",
9131 String::from_utf8_lossy(&y4m.stderr)
9132 );
9133 let depth_args: &[&str] = if bit_depth == 10 {
9134 &["-b", "10", "--input-bit-depth=10"]
9135 } else {
9136 &[]
9137 };
9138 // MEASURED (r1): the speed preset gates the feature (class
9139 // [[gate-preset-gates-the-feature]]) -- at `--cpu-used=4` this
9140 // content produces no rect partition at all, at `--cpu-used=0`
9141 // aomenc emits AB partitions the tile path refuses (it ignores
9142 // `--enable-ab-partitions=0`, ledger). So the attempt sweep walks
9143 // the preset as well as the seed.
9144 let cpu = format!("--cpu-used={}", attempt % 5);
9145 // The quantiser drives how finely the RD partitions: the sweep
9146 // walks it too, so "no rect strip fired" cannot be an artefact of
9147 // one cq.
9148 let cq = format!("--cq-level={}", [30u32, 20, 12][(attempt / 5) as usize % 3]);
9149 let mut child = Command::new(aomenc_path())
9150 .args(depth_args)
9151 .arg(&cpu)
9152 .arg(&cq)
9153 .args([
9154 // class [[aomenc-first-flag-wins]]: every flag is spelled
9155 // exactly ONCE in this recipe, so there is no override to
9156 // order. These four are what this gate is about.
9157 "--enable-rect-partitions=1",
9158 // MEASURED (r1): the charter's `--min-partition-size=8`
9159 // makes 24/24 attempts stop at a sub-16 AB-partition
9160 // refusal ("a HORZ_A/HORZ_B/VERT_A partition below 16x16",
9161 // "a coded (non-skip) HORZ_B/VERT_B rect strip below
9162 // 16x16") before any intra rect strip is reached -- those
9163 // are other lanes' surfaces. 16 keeps the 16x8/8x16 shape
9164 // reachable (a 16x16 block's own HORZ/VERT children).
9165 "--min-partition-size=16",
9166 "--max-partition-size=64",
9167 // MEASURED (r1): with tx-size search ON, 24/24 attempts stop at
9168 // the SQUARE intra-in-inter arm's own refusal ("an intra
9169 // block in an inter frame whose tx_depth splits its luma
9170 // transform (round 1)", read_block_tx_size) long before a
9171 // rect strip is reached -- that arm is another lane's
9172 // surface. OFF, no tx-depth symbol is coded at all and
9173 // every rect strip here is the unsplit single-transform
9174 // case. The SPLIT rect arm (`depth_to_tx_wh` +
9175 // decode_rect_split's per-unit walk) is wired but stays
9176 // UNGATED on this path until that square refusal lifts.
9177 "--enable-tx-size-search=0",
9178 "--codec=av1",
9179 "--passes=1",
9180 "--end-usage=q",
9181 "--lag-in-frames=0",
9182 "--auto-alt-ref=0",
9183 // One key frame at the head: the frames after the cut must
9184 // stay INTER frames carrying intra blocks, not become a
9185 // new key frame.
9186 "--kf-min-dist=1000",
9187 "--kf-max-dist=1000",
9188 "--threads=1",
9189 "--row-mt=0",
9190 "--enable-order-hint=0",
9191 "--enable-warped-motion=0",
9192 "--enable-obmc=0",
9193 "--enable-masked-comp=0",
9194 "--enable-interintra-comp=0",
9195 "--enable-dist-wtd-comp=0",
9196 "--enable-diff-wtd-comp=0",
9197 "--enable-onesided-comp=0",
9198 "--enable-interintra-wedge=0",
9199 "--enable-smooth-interintra=0",
9200 "--enable-ab-partitions=0",
9201 "--enable-1to4-partitions=0",
9202 // The intra-in-inter arm reads no `use_filter_intra`
9203 // symbol (square OR rect) -- lane-fiinter owns that read.
9204 "--enable-filter-intra=0",
9205 "--enable-smooth-intra=0",
9206 "--enable-paeth-intra=0",
9207 "--enable-directional-intra=0",
9208 "--enable-angle-delta=0",
9209 "--enable-cdef=0",
9210 "--enable-restoration=0",
9211 "--enable-palette=0",
9212 "--enable-intrabc=0",
9213 "--enable-cfl-intra=0",
9214 "--enable-ref-frame-mvs=0",
9215 "--obu",
9216 "-o",
9217 "-",
9218 "-",
9219 ])
9220 .stdin(Stdio::piped())
9221 .stdout(Stdio::piped())
9222 .stderr(Stdio::piped())
9223 .spawn()
9224 .expect("aomenc failed to start");
9225 child
9226 .stdin
9227 .take()
9228 .expect("aomenc stdin")
9229 .write_all(&y4m.stdout)
9230 .expect("writing y4m to aomenc");
9231 let out = child.wait_with_output().expect("aomenc failed to run");
9232 assert!(
9233 out.status.success(),
9234 "aomenc refused the fixture: {}",
9235 String::from_utf8_lossy(&out.stderr)
9236 );
9237 let stream = out.stdout;
9238 let before = [
9239 decode::intra_rect_strip_in_inter_hits(0),
9240 decode::intra_rect_strip_in_inter_hits(1),
9241 decode::intra_rect_strip_in_inter_hits(2),
9242 ];
9243 let kf_rect_before = decode::rect_partition_hits();
9244 let frames = match decode_stream(&stream) {
9245 Ok(frames) => frames,
9246 Err(e) => {
9247 let msg = e.to_string();
9248 assert!(
9249 msg.contains("unsupported"),
9250 "intra-rect-in-inter decode failed outright (seed {seed}): {msg}"
9251 );
9252 refusals.push(format!("seed {seed} {cpu} {cq}: {msg}"));
9253 continue;
9254 }
9255 };
9256 let delta = [
9257 decode::intra_rect_strip_in_inter_hits(0) - before[0],
9258 decode::intra_rect_strip_in_inter_hits(1) - before[1],
9259 decode::intra_rect_strip_in_inter_hits(2) - before[2],
9260 ];
9261 let ffmpeg_frames = if bit_depth == 10 {
9262 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
9263 } else {
9264 ffmpeg_decode_sequence(&stream, width, height, frame_count)
9265 };
9266 assert_eq!(frames.len(), frame_count);
9267 eprintln!(
9268 "intrarect gate {bit_depth}-bit seed={seed} {cpu} {cq}: intra rect strips in inter frames \
9269 64-level={} 32-level={} 16-level={}, key-frame rect strips this stream={}",
9270 delta[0], delta[1], delta[2],
9271 decode::rect_partition_hits() - kf_rect_before
9272 );
9273 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9274 for (plane, (g, w)) in [
9275 ("Y", (&got.y, &want.y)),
9276 ("U", (&got.u, &want.u)),
9277 ("V", (&got.v, &want.v)),
9278 ] {
9279 let stride = if plane == "Y" { width } else { width / 2 };
9280 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
9281 eprintln!(
9282 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} first \
9283 diff at ({}, {}) got {} want {} ({} samples differ)",
9284 at % stride,
9285 at / stride,
9286 g[at],
9287 w[at],
9288 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
9289 );
9290 // Magnitude separates a deblock/prediction difference
9291 // (all |d| == 1) from an entropy desync (large,
9292 // arbitrary): the first thing r2 needs to know.
9293 let maxd = g
9294 .iter()
9295 .zip(w.iter())
9296 .map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b)))
9297 .max()
9298 .unwrap_or(0);
9299 let rows: std::collections::BTreeSet<usize> = g
9300 .iter()
9301 .zip(w.iter())
9302 .enumerate()
9303 .filter(|(_, (a, b))| a != b)
9304 .map(|(k, _)| k / stride)
9305 .collect();
9306 eprintln!(
9307 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} max \
9308 |diff|={maxd}, rows {:?}..{:?}",
9309 rows.iter().next(),
9310 rows.iter().next_back()
9311 );
9312 }
9313 assert_eq!(g, w, "{plane} vs ffmpeg (seed {seed}, frame {i})");
9314 }
9315 }
9316 compared += 1;
9317 if delta.iter().all(|d| *d == 0) {
9318 uncounted_exact += 1;
9319 refusals.push(format!(
9320 "seed {seed} {cpu} {cq}: decoded and pixel-compared, but no intra rect strip on the \
9321 inter path"
9322 ));
9323 }
9324 for k in 0..3 {
9325 shapes[k] += delta[k];
9326 }
9327 if shapes.iter().filter(|n| **n > 0).count() >= 2 {
9328 break;
9329 }
9330 }
9331 gate_buckets(
9332 NAME,
9333 compared - uncounted_exact,
9334 uncounted_exact,
9335 refusals.len() - uncounted_exact as usize,
9336 );
9337 eprintln!(
9338 "{NAME} ({bit_depth}-bit): compared {compared} streams, intra rect strips in inter \
9339 frames per shape: 64x32/32x64={} 32x16/16x32={} 16x8/8x16={}; refusals:\n{}",
9340 shapes[0],
9341 shapes[1],
9342 shapes[2],
9343 refusals.join("\n")
9344 );
9345 assert!(
9346 compared > 0,
9347 "{NAME} ({bit_depth}-bit): every attempt hit a named refusal -- nothing was \
9348 pixel-compared:\n{}",
9349 refusals.join("\n")
9350 );
9351 // MEASURED (r1, 90 attempts; r2 re-ran the 45-attempt sweep at both
9352 // depths): only the 32x16/16x32 class is REACHABLE on this branch --
9353 // the inter tile path refuses any SB-level partition other than
9354 // NONE/SPLIT, so a 64x32/32x64 intra strip cannot be produced at all,
9355 // and every 16x8/8x16 candidate stops at a sub-16 refusal owned by
9356 // another lane. So the bar is that class, hard, not "two of three":
9357 // a green run still cannot come from a stream that fired nothing.
9358 assert!(
9359 shapes[1] > 0,
9360 "{NAME} ({bit_depth}-bit): no 32x16/16x32 intra rect strip fired over \
9361 {compared} compared streams (64-level={} 32-level={} 16-level={})",
9362 shapes[0],
9363 shapes[1],
9364 shapes[2]
9365 );
9366 }
9367
9368 fn tx_select_inter_gate(bit_depth: u32) {
9369 if !have_ffmpeg() {
9370 eprintln!(
9371 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg"
9372 );
9373 return;
9374 }
9375 if !have_aomenc() {
9376 eprintln!(
9377 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}",
9378 aomenc_path().display()
9379 );
9380 return;
9381 }
9382 let (width, height, frame_count) = (64usize, 64usize, 4usize);
9383 let mut refusals = Vec::new();
9384 let mut uncounted_exact = 0u32;
9385 for attempt in 0..40u32 {
9386 let seed = 42 + attempt;
9387 // Detail is what makes aomenc's RD prefer a split transform; a
9388 // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s
9389 // fractal boundary is the same source the sibling intra tx-select
9390 // gate uses, at a different `start_scale` per attempt.
9391 let source = format!(
9392 "mandelbrot=size=64x64:start_scale={}:rate=25",
9393 5.0 - f64::from(attempt) * 0.06
9394 );
9395 let y4m = Command::new("ffmpeg")
9396 .args([
9397 "-v",
9398 "error",
9399 "-f",
9400 "lavfi",
9401 "-i",
9402 &source,
9403 // Desaturated chroma: `uv_mode` stays DC_PRED, so the
9404 // still-refused directional-chroma gap never fires and
9405 // luma detail alone drives the transform split.
9406 "-vf",
9407 "hue=s=0",
9408 "-pix_fmt",
9409 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
9410 // y4m carries no official 10-bit tag; ffmpeg writes one
9411 // only under `-strict -1` (a no-op at 8 bit).
9412 "-strict",
9413 "-1",
9414 "-t",
9415 "0.16",
9416 "-f",
9417 "yuv4mpegpipe",
9418 "-strict",
9419 "-1",
9420 "-",
9421 ])
9422 .stdin(Stdio::null())
9423 .stdout(Stdio::piped())
9424 .stderr(Stdio::piped())
9425 .output()
9426 .expect("ffmpeg failed to run");
9427 assert!(
9428 y4m.status.success(),
9429 "ffmpeg fixture: {}",
9430 String::from_utf8_lossy(&y4m.stderr)
9431 );
9432 let depth_args: &[&str] = if bit_depth == 10 {
9433 &["-b", "10", "--input-bit-depth=10"]
9434 } else {
9435 &[]
9436 };
9437 let mut child = Command::new(aomenc_path())
9438 .args(depth_args)
9439 .args([
9440 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
9441 // occurrence, so overrides go before the base list).
9442 "--enable-tx-size-search=1",
9443 "--codec=av1",
9444 "--passes=1",
9445 "--end-usage=q",
9446 "--cq-level=55",
9447 "--cpu-used=0",
9448 "--lag-in-frames=0",
9449 "--auto-alt-ref=0",
9450 "--kf-max-dist=1000",
9451 "--threads=1",
9452 "--row-mt=0",
9453 "--enable-order-hint=0",
9454 "--enable-warped-motion=0",
9455 "--enable-obmc=0",
9456 "--enable-masked-comp=0",
9457 "--enable-interintra-comp=0",
9458 "--enable-dist-wtd-comp=0",
9459 "--enable-diff-wtd-comp=0",
9460 "--enable-onesided-comp=0",
9461 "--enable-interintra-wedge=0",
9462 "--enable-smooth-interintra=0",
9463 "--enable-rect-partitions=0",
9464 "--enable-ab-partitions=0",
9465 "--enable-1to4-partitions=0",
9466 "--enable-filter-intra=0",
9467 "--enable-smooth-intra=0",
9468 "--enable-paeth-intra=0",
9469 "--enable-directional-intra=0",
9470 "--enable-angle-delta=0",
9471 // DELIBERATELY ABSENT: --enable-tx-size-search=0.
9472 "--enable-cdef=0",
9473 "--enable-restoration=0",
9474 "--max-partition-size=32",
9475 // Sub-16 inter partitions are a separate named refusal
9476 // (this decoder codes no inter block below 16x16 through
9477 // the square path this gate drives), and detailed content
9478 // makes aomenc's RD reach for them on nearly every seed.
9479 "--min-partition-size=16",
9480 "--enable-palette=0",
9481 "--enable-intrabc=0",
9482 "--enable-cfl-intra=0",
9483 "--enable-ref-frame-mvs=0",
9484 "--obu",
9485 "-o",
9486 "-",
9487 "-",
9488 ])
9489 .stdin(Stdio::piped())
9490 .stdout(Stdio::piped())
9491 .stderr(Stdio::piped())
9492 .spawn()
9493 .expect("aomenc failed to start");
9494 child
9495 .stdin
9496 .take()
9497 .expect("aomenc stdin")
9498 .write_all(&y4m.stdout)
9499 .expect("writing y4m to aomenc");
9500 let out = child.wait_with_output().expect("aomenc failed to run");
9501 assert!(
9502 out.status.success(),
9503 "aomenc refused the fixture: {}",
9504 String::from_utf8_lossy(&out.stderr)
9505 );
9506 let stream = out.stdout;
9507 let (reads_before, hits_before) =
9508 (decode::txfm_split_reads(), decode::txfm_split_hits());
9509 let frames = match decode_stream(&stream) {
9510 Ok(frames) => frames,
9511 Err(e) => {
9512 let msg = e.to_string();
9513 assert!(
9514 msg.contains("unsupported"),
9515 "tx-select inter decode failed outright (seed {seed}): {msg}"
9516 );
9517 refusals.push(format!("seed {seed}: {msg}"));
9518 continue;
9519 }
9520 };
9521 let (reads, hits) = (
9522 decode::txfm_split_reads() - reads_before,
9523 decode::txfm_split_hits() - hits_before,
9524 );
9525 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
9526 // is ALWAYS pixel-compared below; the hit counter only decides whether
9527 // the attempt counts toward the firing total.
9528 let counted = hits != 0;
9529 if !counted {
9530 uncounted_exact += 1;
9531 refusals.push(format!(
9532 "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \
9533 ({reads} symbols read)"
9534 ));
9535 }
9536 let ffmpeg_frames = if bit_depth == 10 {
9537 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
9538 } else {
9539 ffmpeg_decode_sequence(&stream, width, height, frame_count)
9540 };
9541 assert_eq!(frames.len(), frame_count);
9542 eprintln!(
9543 "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}"
9544 );
9545 // Name the first differing sample before the assert fires: a
9546 // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for
9547 // locating a desync.
9548 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9549 for (plane, (g, w)) in [
9550 ("Y", (&got.y, &want.y)),
9551 ("U", (&got.u, &want.u)),
9552 ("V", (&got.v, &want.v)),
9553 ] {
9554 let stride = if plane == "Y" { width } else { width / 2 };
9555 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
9556 eprintln!(
9557 "txselect gate seed={seed}: frame {i} {plane} first diff at \
9558 ({}, {}) got {} want {} ({} samples differ)",
9559 at % stride,
9560 at / stride,
9561 g[at],
9562 w[at],
9563 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
9564 );
9565 let coords: Vec<String> = g
9566 .iter()
9567 .zip(w.iter())
9568 .enumerate()
9569 .filter(|(_, (a, b))| a != b)
9570 .take(12)
9571 .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride))
9572 .collect();
9573 eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}");
9574 }
9575 }
9576 }
9577 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9578 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
9579 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
9580 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
9581 }
9582 if counted {
9583 gate_buckets(
9584 &format!("tx_select_inter_gate({bit_depth})"),
9585 1,
9586 uncounted_exact,
9587 refusals.len() - uncounted_exact as usize,
9588 );
9589 return;
9590 }
9591 }
9592 gate_buckets(
9593 &format!("tx_select_inter_gate({bit_depth})"),
9594 0,
9595 uncounted_exact,
9596 refusals.len() - uncounted_exact as usize,
9597 );
9598 panic!(
9599 "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}",
9600 refusals.join("\n")
9601 );
9602 }
9603
9604 /// lane-intrainter r1's decisive gate: a real aomenc INTER sequence in
9605 /// which aomenc's RD picks an INTRA block inside an inter frame AND
9606 /// splits that block's luma transform (`tx_depth >= 1`, the intra depth
9607 /// symbol -- not the inter var-tx tree). That block codes one intra
9608 /// prediction plus one coefficient set per transform unit, exactly like a
9609 /// key frame's split block but with the inter frame's CDF state and the
9610 /// inter-frame intra mode syntax; before this lane it was a named
9611 /// refusal. Hard-asserts [`decode::intra_in_inter_split_tx_hits`] per
9612 /// block size: an attempt that never produced such a block proves
9613 /// nothing, and exhausting every attempt is a FAILURE, not a SKIP.
9614 #[test]
9615 fn a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
9616 intra_in_inter_split_tx_gate(8);
9617 }
9618
9619 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
9620 #[test]
9621 fn a_real_aomenc_10bit_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
9622 intra_in_inter_split_tx_gate(10);
9623 }
9624
9625 fn intra_in_inter_split_tx_gate(bit_depth: u32) {
9626 let name = format!("intra_in_inter_split_tx_gate({bit_depth})");
9627 if !have_ffmpeg() {
9628 eprintln!("SKIP {name}: no ffmpeg");
9629 return;
9630 }
9631 if !have_aomenc() {
9632 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
9633 return;
9634 }
9635 let (width, height, frame_count) = (64usize, 64usize, 8usize);
9636 let mut refusals = Vec::new();
9637 let mut uncounted_exact = 0u32;
9638 for attempt in 0..40u32 {
9639 let seed = 42 + attempt;
9640 // A zooming fractal: every frame moves (so the sequence is
9641 // genuinely inter-coded) and keeps sharp new detail entering at
9642 // the borders, which is what makes aomenc's RD choose an INTRA
9643 // block inside an inter frame -- and then split its transform.
9644 // A zooming fractal with a hard CUT halfway (`overlay` switching
9645 // a second, unrelated fractal on at frame 4): after the cut every
9646 // block is unpredictable from the reference, which is what makes
9647 // aomenc code INTRA blocks inside an inter frame -- and at this
9648 // cq the RD then splits their transforms.
9649 let source = format!(
9650 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
9651 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
9652 [a][b]overlay=enable='gte(n,4)'",
9653 5.0 - f64::from(attempt) * 0.06,
9654 0.9 + f64::from(attempt) * 0.11
9655 );
9656 let y4m = Command::new("ffmpeg")
9657 .args([
9658 "-v",
9659 "error",
9660 "-f",
9661 "lavfi",
9662 "-i",
9663 &source,
9664 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
9665 // still-refused directional-chroma gaps never fire and
9666 // luma detail alone drives the transform split.
9667 "-vf",
9668 "hue=s=0",
9669 "-pix_fmt",
9670 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
9671 "-strict",
9672 "-1",
9673 "-t",
9674 "0.32",
9675 "-f",
9676 "yuv4mpegpipe",
9677 "-strict",
9678 "-1",
9679 "-",
9680 ])
9681 .stdin(Stdio::null())
9682 .stdout(Stdio::piped())
9683 .stderr(Stdio::piped())
9684 .output()
9685 .expect("ffmpeg failed to run");
9686 assert!(
9687 y4m.status.success(),
9688 "ffmpeg fixture: {}",
9689 String::from_utf8_lossy(&y4m.stderr)
9690 );
9691 let depth_args: &[&str] = if bit_depth == 10 {
9692 &["-b", "10", "--input-bit-depth=10"]
9693 } else {
9694 &[]
9695 };
9696 let mut child = Command::new(aomenc_path())
9697 .args(depth_args)
9698 .args([
9699 "--codec=av1",
9700 "--passes=1",
9701 "--end-usage=q",
9702 "--cq-level=30",
9703 "--cpu-used=0",
9704 "--lag-in-frames=0",
9705 "--auto-alt-ref=0",
9706 // One key frame only: every later frame is an inter frame,
9707 // which is where this gate's intra blocks must sit. The
9708 // MIN distance is what stops aomenc's scene-cut detector
9709 // from inserting a second key frame at the cut this gate's
9710 // source deliberately contains.
9711 "--kf-max-dist=1000",
9712 "--kf-min-dist=1000",
9713 "--threads=1",
9714 "--row-mt=0",
9715 "--enable-order-hint=0",
9716 "--enable-warped-motion=0",
9717 "--enable-obmc=0",
9718 "--enable-masked-comp=0",
9719 "--enable-interintra-comp=0",
9720 "--enable-dist-wtd-comp=0",
9721 "--enable-diff-wtd-comp=0",
9722 "--enable-onesided-comp=0",
9723 "--enable-interintra-wedge=0",
9724 "--enable-smooth-interintra=0",
9725 "--enable-ab-partitions=0",
9726 "--enable-1to4-partitions=0",
9727 "--enable-filter-intra=0",
9728 "--enable-smooth-intra=0",
9729 "--enable-paeth-intra=0",
9730 "--enable-directional-intra=0",
9731 "--enable-angle-delta=0",
9732 "--enable-cdef=0",
9733 "--enable-restoration=0",
9734 "--enable-palette=0",
9735 "--enable-intrabc=0",
9736 "--enable-cfl-intra=0",
9737 "--enable-ref-frame-mvs=0",
9738 // Per-arm overrides go LAST (aomenc keeps the last
9739 // occurrence of a repeated --enable-* flag): the intra
9740 // tx_depth symbol only exists under TX_MODE_SELECT, and
9741 // rect partitions are a separate named refusal.
9742 "--enable-tx-size-search=1",
9743 "--enable-rect-partitions=0",
9744 "--max-partition-size=32",
9745 // Sub-16 inter partitions are a separate named refusal,
9746 // as is the 8x8 intra leaf's own TX_4X4 split.
9747 "--min-partition-size=16",
9748 "--obu",
9749 "-o",
9750 "-",
9751 "-",
9752 ])
9753 .stdin(Stdio::piped())
9754 .stdout(Stdio::piped())
9755 .stderr(Stdio::piped())
9756 .spawn()
9757 .expect("aomenc failed to start");
9758 child
9759 .stdin
9760 .take()
9761 .expect("aomenc stdin")
9762 .write_all(&y4m.stdout)
9763 .expect("writing y4m to aomenc");
9764 let out = child.wait_with_output().expect("aomenc failed to run");
9765 assert!(
9766 out.status.success(),
9767 "aomenc refused the fixture: {}",
9768 String::from_utf8_lossy(&out.stderr)
9769 );
9770 let stream = out.stdout;
9771 let before = decode::intra_in_inter_split_tx_hits();
9772 let frames = match decode_stream(&stream) {
9773 Ok(frames) => frames,
9774 Err(e) => {
9775 let msg = e.to_string();
9776 assert!(
9777 msg.contains("unsupported"),
9778 "{name} decode failed outright (seed {seed}): {msg}"
9779 );
9780 refusals.push(format!("seed {seed}: {msg}"));
9781 continue;
9782 }
9783 };
9784 let after = decode::intra_in_inter_split_tx_hits();
9785 let mut per_size = [0usize; 4];
9786 for i in 0..4 {
9787 per_size[i] = after[i] - before[i];
9788 }
9789 // class [[gate-skips-on-its-own-failure]]: a decode that
9790 // succeeded is ALWAYS pixel-compared below; the counter only
9791 // decides whether the attempt counts as firing.
9792 let counted = per_size.iter().sum::<usize>() != 0;
9793 if !counted {
9794 uncounted_exact += 1;
9795 refusals.push(format!(
9796 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
9797 frame split its transform"
9798 ));
9799 }
9800 let ffmpeg_frames = if bit_depth == 10 {
9801 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
9802 } else {
9803 ffmpeg_decode_sequence(&stream, width, height, frame_count)
9804 };
9805 assert_eq!(frames.len(), frame_count);
9806 eprintln!(
9807 "{name} seed={seed}: split intra-in-inter blocks 8x8={} 16x16={} 32x32={} \
9808 64x64={}",
9809 per_size[0], per_size[1], per_size[2], per_size[3]
9810 );
9811 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9812 for (plane, (g, w)) in [
9813 ("Y", (&got.y, &want.y)),
9814 ("U", (&got.u, &want.u)),
9815 ("V", (&got.v, &want.v)),
9816 ] {
9817 let stride = if plane == "Y" { width } else { width / 2 };
9818 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
9819 eprintln!(
9820 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
9821 want {} ({} samples differ)",
9822 at % stride,
9823 at / stride,
9824 g[at],
9825 w[at],
9826 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
9827 );
9828 }
9829 }
9830 }
9831 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9832 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
9833 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
9834 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
9835 }
9836 if counted {
9837 gate_buckets(
9838 &name,
9839 1,
9840 uncounted_exact,
9841 refusals.len() - uncounted_exact as usize,
9842 );
9843 return;
9844 }
9845 }
9846 gate_buckets(
9847 &name,
9848 0,
9849 uncounted_exact,
9850 refusals.len() - uncounted_exact as usize,
9851 );
9852 panic!(
9853 "{name} never observed a split-transform intra block in an inter frame:\n{}",
9854 refusals.join("\n")
9855 );
9856 }
9857
9858 /// lane-fiinter r1 (class [[symbol-consumption-gap]] +
9859 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
9860 /// `--enable-filter-intra=1` (aomenc's own default -- every inter gate
9861 /// recipe before this one pinned it OFF, so nothing ever exercised it) in
9862 /// which the RD picks an INTRA block inside an inter frame and gives it
9863 /// filter intra. `read_intra_block_mode_info` reads `use_filter_intra`
9864 /// there exactly as a key frame does; this decoder read no such symbol at
9865 /// all until this round, so such a stream desynced at that symbol and
9866 /// decoded silently wrong. Hard-asserts
9867 /// [`decode::intra_in_inter_filter_intra_hits`]: an attempt that never
9868 /// produced one proves nothing, and exhausting every attempt is a
9869 /// FAILURE, not a SKIP.
9870 #[test]
9871 fn a_real_aomenc_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact() {
9872 filter_intra_in_inter_gate(8);
9873 }
9874
9875 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
9876 #[test]
9877 fn a_real_aomenc_10bit_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact()
9878 {
9879 filter_intra_in_inter_gate(10);
9880 }
9881
9882 fn filter_intra_in_inter_gate(bit_depth: u32) {
9883 let name = format!("filter_intra_in_inter_gate({bit_depth})");
9884 if !have_ffmpeg() {
9885 eprintln!("SKIP {name}: no ffmpeg");
9886 return;
9887 }
9888 if !have_aomenc() {
9889 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
9890 return;
9891 }
9892 let (width, height, frame_count) = (64usize, 64usize, 8usize);
9893 let mut refusals = Vec::new();
9894 let mut uncounted_exact = 0u32;
9895 for attempt in 0..40u32 {
9896 let seed = 42 + attempt;
9897 // A zooming fractal: every frame moves (so the sequence is
9898 // genuinely inter-coded) and keeps sharp new detail entering at
9899 // the borders, which is what makes aomenc's RD choose an INTRA
9900 // block inside an inter frame -- and then split its transform.
9901 // A zooming fractal with a hard CUT halfway (`overlay` switching
9902 // a second, unrelated fractal on at frame 4): after the cut every
9903 // block is unpredictable from the reference, which is what makes
9904 // aomenc code INTRA blocks inside an inter frame -- and at this
9905 // cq the RD then splits their transforms.
9906 let source = format!(
9907 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
9908 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
9909 [a][b]overlay=enable='gte(n,4)'",
9910 5.0 - f64::from(attempt) * 0.06,
9911 0.9 + f64::from(attempt) * 0.11
9912 );
9913 let y4m = Command::new("ffmpeg")
9914 .args([
9915 "-v",
9916 "error",
9917 "-f",
9918 "lavfi",
9919 "-i",
9920 &source,
9921 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
9922 // still-refused directional-chroma gaps never fire and
9923 // luma detail alone drives the transform split.
9924 "-vf",
9925 "hue=s=0",
9926 "-pix_fmt",
9927 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
9928 "-strict",
9929 "-1",
9930 "-t",
9931 "0.32",
9932 "-f",
9933 "yuv4mpegpipe",
9934 "-strict",
9935 "-1",
9936 "-",
9937 ])
9938 .stdin(Stdio::null())
9939 .stdout(Stdio::piped())
9940 .stderr(Stdio::piped())
9941 .output()
9942 .expect("ffmpeg failed to run");
9943 assert!(
9944 y4m.status.success(),
9945 "ffmpeg fixture: {}",
9946 String::from_utf8_lossy(&y4m.stderr)
9947 );
9948 let depth_args: &[&str] = if bit_depth == 10 {
9949 &["-b", "10", "--input-bit-depth=10"]
9950 } else {
9951 &[]
9952 };
9953 let mut child = Command::new(aomenc_path())
9954 .args(depth_args)
9955 .args([
9956 "--codec=av1",
9957 "--passes=1",
9958 "--end-usage=q",
9959 "--cq-level=30",
9960 "--cpu-used=0",
9961 "--lag-in-frames=0",
9962 "--auto-alt-ref=0",
9963 // One key frame only: every later frame is an inter frame,
9964 // which is where this gate's intra blocks must sit. The
9965 // MIN distance is what stops aomenc's scene-cut detector
9966 // from inserting a second key frame at the cut this gate's
9967 // source deliberately contains.
9968 "--kf-max-dist=1000",
9969 "--kf-min-dist=1000",
9970 "--threads=1",
9971 "--row-mt=0",
9972 "--enable-order-hint=0",
9973 "--enable-warped-motion=0",
9974 "--enable-obmc=0",
9975 "--enable-masked-comp=0",
9976 "--enable-interintra-comp=0",
9977 "--enable-dist-wtd-comp=0",
9978 "--enable-diff-wtd-comp=0",
9979 "--enable-onesided-comp=0",
9980 "--enable-interintra-wedge=0",
9981 "--enable-smooth-interintra=0",
9982 "--enable-ab-partitions=0",
9983 "--enable-1to4-partitions=0",
9984 "--enable-smooth-intra=0",
9985 "--enable-paeth-intra=0",
9986 "--enable-directional-intra=0",
9987 "--enable-angle-delta=0",
9988 "--enable-cdef=0",
9989 "--enable-restoration=0",
9990 "--enable-palette=0",
9991 "--enable-intrabc=0",
9992 "--enable-cfl-intra=0",
9993 "--enable-ref-frame-mvs=0",
9994 // Per-arm overrides go LAST (aomenc keeps the last
9995 // occurrence of a repeated --enable-* flag): the intra
9996 // tx_depth symbol only exists under TX_MODE_SELECT, and
9997 // rect partitions are a separate named refusal.
9998 "--enable-filter-intra=1",
9999 "--enable-tx-size-search=1",
10000 "--enable-rect-partitions=0",
10001 "--max-partition-size=32",
10002 // Sub-16 inter partitions are a separate named refusal,
10003 // as is the 8x8 intra leaf's own TX_4X4 split.
10004 "--min-partition-size=16",
10005 "--obu",
10006 "-o",
10007 "-",
10008 "-",
10009 ])
10010 .stdin(Stdio::piped())
10011 .stdout(Stdio::piped())
10012 .stderr(Stdio::piped())
10013 .spawn()
10014 .expect("aomenc failed to start");
10015 child
10016 .stdin
10017 .take()
10018 .expect("aomenc stdin")
10019 .write_all(&y4m.stdout)
10020 .expect("writing y4m to aomenc");
10021 let out = child.wait_with_output().expect("aomenc failed to run");
10022 assert!(
10023 out.status.success(),
10024 "aomenc refused the fixture: {}",
10025 String::from_utf8_lossy(&out.stderr)
10026 );
10027 let stream = out.stdout;
10028 let before = decode::intra_in_inter_filter_intra_hits();
10029 let frames = match decode_stream(&stream) {
10030 Ok(frames) => frames,
10031 Err(e) => {
10032 let msg = e.to_string();
10033 assert!(
10034 msg.contains("unsupported"),
10035 "{name} decode failed outright (seed {seed}): {msg}"
10036 );
10037 refusals.push(format!("seed {seed}: {msg}"));
10038 continue;
10039 }
10040 };
10041 let fired = decode::intra_in_inter_filter_intra_hits() - before;
10042 // class [[gate-skips-on-its-own-failure]]: a decode that
10043 // succeeded is ALWAYS pixel-compared below; the counter only
10044 // decides whether the attempt counts as firing.
10045 let counted = fired != 0;
10046 if !counted {
10047 uncounted_exact += 1;
10048 refusals.push(format!(
10049 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
10050 frame used filter intra"
10051 ));
10052 }
10053 let ffmpeg_frames = if bit_depth == 10 {
10054 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
10055 } else {
10056 ffmpeg_decode_sequence(&stream, width, height, frame_count)
10057 };
10058 assert_eq!(frames.len(), frame_count);
10059 eprintln!(
10060 "{name} seed={seed}: filter-intra blocks inside inter frames = {fired}"
10061 );
10062 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10063 for (plane, (g, w)) in [
10064 ("Y", (&got.y, &want.y)),
10065 ("U", (&got.u, &want.u)),
10066 ("V", (&got.v, &want.v)),
10067 ] {
10068 let stride = if plane == "Y" { width } else { width / 2 };
10069 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
10070 eprintln!(
10071 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
10072 want {} ({} samples differ)",
10073 at % stride,
10074 at / stride,
10075 g[at],
10076 w[at],
10077 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
10078 );
10079 }
10080 }
10081 }
10082 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10083 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
10084 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
10085 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
10086 }
10087 if counted {
10088 gate_buckets(
10089 &name,
10090 1,
10091 uncounted_exact,
10092 refusals.len() - uncounted_exact as usize,
10093 );
10094 return;
10095 }
10096 }
10097 gate_buckets(
10098 &name,
10099 0,
10100 uncounted_exact,
10101 refusals.len() - uncounted_exact as usize,
10102 );
10103 panic!(
10104 "{name} never observed a filter-intra intra block in an inter frame:\n{}",
10105 refusals.join("\n")
10106 );
10107 }
10108
10109 /// lane-angleinter r1 (class [[refusal-strings-are-claims]] +
10110 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
10111 /// `--enable-angle-delta=1` and `--enable-directional-intra=1` (aomenc's
10112 /// own defaults; every inter gate before this one pinned BOTH off) in
10113 /// which the RD gives an INTRA block inside an inter frame a directional
10114 /// luma mode with a nonzero `angle_delta_y`. Both intra-in-inter arms
10115 /// read that symbol and then REFUSED it as "this encoder never writes
10116 /// one" -- the claim is false, `read_intra_angle_info` writes it exactly
10117 /// as a key frame does. Hard-asserts
10118 /// [`decode::intra_in_inter_angle_delta_y_hits`]; an attempt that never
10119 /// produced one proves nothing, and exhausting every attempt is a
10120 /// FAILURE, not a SKIP.
10121 #[test]
10122 fn a_real_aomenc_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
10123 {
10124 angle_delta_in_inter_gate(8, "--min-partition-size=16");
10125 }
10126
10127 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
10128 #[test]
10129 fn a_real_aomenc_10bit_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
10130 {
10131 angle_delta_in_inter_gate(10, "--min-partition-size=16");
10132 }
10133
10134 fn angle_delta_in_inter_gate(bit_depth: u32, min_partition: &str) {
10135 let name = format!("angle_delta_in_inter_gate({bit_depth}, min={min_partition})");
10136 let leaf8 = min_partition.ends_with('8');
10137 assert!(!leaf8, "the 8x8-leaf arm keeps its refusal; see the module note");
10138 if !have_ffmpeg() {
10139 eprintln!("SKIP {name}: no ffmpeg");
10140 return;
10141 }
10142 if !have_aomenc() {
10143 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
10144 return;
10145 }
10146 let (width, height, frame_count) = (64usize, 64usize, 8usize);
10147 let mut refusals = Vec::new();
10148 let mut uncounted_exact = 0u32;
10149 for attempt in 0..40u32 {
10150 let seed = 42 + attempt;
10151 // A zooming fractal: every frame moves (so the sequence is
10152 // genuinely inter-coded) and keeps sharp new detail entering at
10153 // the borders, which is what makes aomenc's RD choose an INTRA
10154 // block inside an inter frame -- and then split its transform.
10155 // A zooming fractal with a hard CUT halfway (`overlay` switching
10156 // a second, unrelated fractal on at frame 4): after the cut every
10157 // block is unpredictable from the reference, which is what makes
10158 // aomenc code INTRA blocks inside an inter frame -- and at this
10159 // cq the RD then splits their transforms.
10160 let source = format!(
10161 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
10162 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
10163 [a][b]overlay=enable='gte(n,4)'",
10164 5.0 - f64::from(attempt) * 0.06,
10165 0.9 + f64::from(attempt) * 0.11
10166 );
10167 let y4m = Command::new("ffmpeg")
10168 .args([
10169 "-v",
10170 "error",
10171 "-f",
10172 "lavfi",
10173 "-i",
10174 &source,
10175 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
10176 // still-refused directional-chroma gaps never fire and
10177 // luma detail alone drives the transform split.
10178 "-vf",
10179 "hue=s=0",
10180 "-pix_fmt",
10181 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
10182 "-strict",
10183 "-1",
10184 "-t",
10185 "0.32",
10186 "-f",
10187 "yuv4mpegpipe",
10188 "-strict",
10189 "-1",
10190 "-",
10191 ])
10192 .stdin(Stdio::null())
10193 .stdout(Stdio::piped())
10194 .stderr(Stdio::piped())
10195 .output()
10196 .expect("ffmpeg failed to run");
10197 assert!(
10198 y4m.status.success(),
10199 "ffmpeg fixture: {}",
10200 String::from_utf8_lossy(&y4m.stderr)
10201 );
10202 // The 8x8-leaf arm is fenced by three sibling refusals (non-DC
10203 // chroma on an 8x8 leaf, its TX_4X4 split, sub-16 rect inter
10204 // leaves), so it sweeps the quantiser as well as the source: a
10205 // coarser q is what pushes the RD to directional intra at 8x8.
10206 let cq = if leaf8 {
10207 format!("--cq-level={}", 20 + (attempt % 5) * 10)
10208 } else {
10209 "--cq-level=30".to_string()
10210 };
10211 let depth_args: &[&str] = if bit_depth == 10 {
10212 &["-b", "10", "--input-bit-depth=10"]
10213 } else {
10214 &[]
10215 };
10216 let mut child = Command::new(aomenc_path())
10217 .args(depth_args)
10218 .args([
10219 "--codec=av1",
10220 "--passes=1",
10221 "--end-usage=q",
10222 &cq,
10223 "--cpu-used=0",
10224 "--lag-in-frames=0",
10225 "--auto-alt-ref=0",
10226 // One key frame only: every later frame is an inter frame,
10227 // which is where this gate's intra blocks must sit. The
10228 // MIN distance is what stops aomenc's scene-cut detector
10229 // from inserting a second key frame at the cut this gate's
10230 // source deliberately contains.
10231 "--kf-max-dist=1000",
10232 "--kf-min-dist=1000",
10233 "--threads=1",
10234 "--row-mt=0",
10235 "--enable-order-hint=0",
10236 "--enable-warped-motion=0",
10237 "--enable-obmc=0",
10238 "--enable-masked-comp=0",
10239 "--enable-interintra-comp=0",
10240 "--enable-dist-wtd-comp=0",
10241 "--enable-diff-wtd-comp=0",
10242 "--enable-onesided-comp=0",
10243 "--enable-interintra-wedge=0",
10244 "--enable-smooth-interintra=0",
10245 "--enable-ab-partitions=0",
10246 "--enable-1to4-partitions=0",
10247 "--enable-smooth-intra=0",
10248 "--enable-paeth-intra=0",
10249 "--enable-directional-intra=1",
10250 "--enable-angle-delta=1",
10251 "--enable-cdef=0",
10252 "--enable-restoration=0",
10253 "--enable-palette=0",
10254 "--enable-intrabc=0",
10255 "--enable-cfl-intra=0",
10256 "--enable-ref-frame-mvs=0",
10257 // Per-arm overrides go LAST (aomenc keeps the last
10258 // occurrence of a repeated --enable-* flag): the intra
10259 // tx_depth symbol only exists under TX_MODE_SELECT, and
10260 // rect partitions are a separate named refusal.
10261 "--enable-filter-intra=1",
10262 "--enable-tx-size-search=1",
10263 "--enable-rect-partitions=0",
10264 "--max-partition-size=32",
10265 // Sub-16 inter partitions are a separate named refusal,
10266 // as is the 8x8 intra leaf's own TX_4X4 split.
10267 min_partition,
10268 "--obu",
10269 "-o",
10270 "-",
10271 "-",
10272 ])
10273 .stdin(Stdio::piped())
10274 .stdout(Stdio::piped())
10275 .stderr(Stdio::piped())
10276 .spawn()
10277 .expect("aomenc failed to start");
10278 child
10279 .stdin
10280 .take()
10281 .expect("aomenc stdin")
10282 .write_all(&y4m.stdout)
10283 .expect("writing y4m to aomenc");
10284 let out = child.wait_with_output().expect("aomenc failed to run");
10285 assert!(
10286 out.status.success(),
10287 "aomenc refused the fixture: {}",
10288 String::from_utf8_lossy(&out.stderr)
10289 );
10290 let stream = out.stdout;
10291 let before = decode::intra_in_inter_angle_delta_y_hits();
10292 let before_uv = decode::intra_in_inter_angle_delta_uv_hits();
10293 let frames = match decode_stream(&stream) {
10294 Ok(frames) => frames,
10295 Err(e) => {
10296 let msg = e.to_string();
10297 assert!(
10298 msg.contains("unsupported"),
10299 "{name} decode failed outright (seed {seed}): {msg}"
10300 );
10301 refusals.push(format!("seed {seed}: {msg}"));
10302 continue;
10303 }
10304 };
10305 let fired = decode::intra_in_inter_angle_delta_y_hits() - before;
10306 let fired_uv = decode::intra_in_inter_angle_delta_uv_hits() - before_uv;
10307 // class [[gate-skips-on-its-own-failure]]: a decode that
10308 // succeeded is ALWAYS pixel-compared below; the counter only
10309 // decides whether the attempt counts as firing.
10310 let counted = fired != 0;
10311 if !counted {
10312 uncounted_exact += 1;
10313 refusals.push(format!(
10314 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
10315 frame carried a nonzero angle_delta_y"
10316 ));
10317 }
10318 let ffmpeg_frames = if bit_depth == 10 {
10319 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
10320 } else {
10321 ffmpeg_decode_sequence(&stream, width, height, frame_count)
10322 };
10323 assert_eq!(frames.len(), frame_count);
10324 eprintln!(
10325 "{name} seed={seed}: intra-in-inter blocks with a nonzero angle_delta_y = \
10326 {fired}, angle_delta_uv = {fired_uv}"
10327 );
10328 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10329 for (plane, (g, w)) in [
10330 ("Y", (&got.y, &want.y)),
10331 ("U", (&got.u, &want.u)),
10332 ("V", (&got.v, &want.v)),
10333 ] {
10334 let stride = if plane == "Y" { width } else { width / 2 };
10335 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
10336 eprintln!(
10337 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
10338 want {} ({} samples differ)",
10339 at % stride,
10340 at / stride,
10341 g[at],
10342 w[at],
10343 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
10344 );
10345 }
10346 }
10347 }
10348 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10349 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
10350 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
10351 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
10352 }
10353 if counted {
10354 gate_buckets(
10355 &name,
10356 1,
10357 uncounted_exact,
10358 refusals.len() - uncounted_exact as usize,
10359 );
10360 return;
10361 }
10362 }
10363 gate_buckets(
10364 &name,
10365 0,
10366 uncounted_exact,
10367 refusals.len() - uncounted_exact as usize,
10368 );
10369 panic!(
10370 "{name} never observed a nonzero angle delta on an intra block in an inter \
10371 frame:\n{}",
10372 refusals.join("\n")
10373 );
10374 }
10375
10376 /// lane-uv8 r1 (classes [[refusal-strings-are-claims]] +
10377 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
10378 /// 8x8 partitions and full chroma intra tooling
10379 /// (`--enable-cfl-intra=1 --enable-smooth-intra=1 --enable-paeth-intra=1
10380 /// --enable-directional-intra=1`), in which the RD gives an INTRA 8x8
10381 /// leaf inside an inter frame a NON-DC `uv_mode`. That leaf
10382 /// ([`decode::decode_inter_block8`]'s intra arm) read the `uv_mode`
10383 /// symbol and refused every value but `DC_PRED` -- "this encoder never
10384 /// writes one" was a claim, and this gate is what contradicts it. Hard-
10385 /// asserts `decode::intra_in_inter8_uv_hits` (directional, smooth/paeth,
10386 /// CfL, counted on THIS leaf only); an attempt that never produced one
10387 /// proves nothing, and exhausting every attempt is a FAILURE, not a SKIP.
10388 #[test]
10389 fn a_real_aomenc_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() {
10390 uv_mode_in_inter8_gate(8, 1);
10391 }
10392
10393 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
10394 #[test]
10395 fn a_real_aomenc_10bit_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() {
10396 uv_mode_in_inter8_gate(10, 1);
10397 }
10398
10399 /// The multi-tile arm (class [[new-map-ignores-tile-edge]]): this round
10400 /// stamps a new `uv_mode` band from the 8x8 leaf, whose availability must
10401 /// be tile-relative.
10402 #[test]
10403 fn a_real_aomenc_two_tile_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact()
10404 {
10405 uv_mode_in_inter8_gate(8, 2);
10406 }
10407
10408 fn uv_mode_in_inter8_gate(bit_depth: u32, tile_columns: u32) {
10409 let name = format!("uv_mode_in_inter8_gate({bit_depth}, tiles={tile_columns})");
10410 if !have_ffmpeg() {
10411 eprintln!("SKIP {name}: no ffmpeg");
10412 return;
10413 }
10414 if !have_aomenc() {
10415 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
10416 return;
10417 }
10418 let (width, height, frame_count) = (192usize, 128usize, 8usize);
10419 let mut refusals = Vec::new();
10420 let mut uncounted_exact = 0u32;
10421 let mut totals = (0usize, 0usize, 0usize);
10422 for attempt in 0..30u32 {
10423 let seed = 42 + attempt;
10424 // A zooming fractal with a hard CUT at frame 4 (`overlay`
10425 // switching a second, unrelated fractal on): after the cut a block
10426 // is unpredictable from the reference, which is what makes aomenc
10427 // code INTRA blocks inside an inter frame. Chroma is NOT
10428 // desaturated here (every sibling inter gate passes `hue=s=0`) --
10429 // real chroma detail is exactly what pushes the chroma RD off
10430 // DC_PRED. `noise` carries its own explicit seed (lavfi
10431 // `gradients` ignores its seed; class [[seeded-fixture-not-reproducible]]).
10432 let source = format!(
10433 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
10434 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
10435 [a][b]overlay=enable='gte(n,4)',noise=alls=12:allf=t+u:all_seed={seed}",
10436 5.0 - f64::from(attempt) * 0.06,
10437 0.9 + f64::from(attempt) * 0.11
10438 );
10439 let y4m = Command::new("ffmpeg")
10440 .args([
10441 "-v",
10442 "error",
10443 "-f",
10444 "lavfi",
10445 "-i",
10446 &source,
10447 "-pix_fmt",
10448 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
10449 "-strict",
10450 "-1",
10451 "-t",
10452 "0.32",
10453 "-f",
10454 "yuv4mpegpipe",
10455 "-strict",
10456 "-1",
10457 "-",
10458 ])
10459 .stdin(Stdio::null())
10460 .stdout(Stdio::piped())
10461 .stderr(Stdio::piped())
10462 .output()
10463 .expect("ffmpeg failed to run");
10464 assert!(
10465 y4m.status.success(),
10466 "ffmpeg fixture: {}",
10467 String::from_utf8_lossy(&y4m.stderr)
10468 );
10469 // A coarser quantiser is what pushes the chroma RD to a cheap
10470 // non-DC mode on a small block; sweep 12..40 (the low end is what
10471 // lane-cdef's cq12 arm needs).
10472 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
10473 let depth_args: &[&str] = if bit_depth == 10 {
10474 &["-b", "10", "--input-bit-depth=10"]
10475 } else {
10476 &[]
10477 };
10478 let tiles = format!("--tile-columns={}", tile_columns - 1);
10479 // The y4m goes through a FILE, not aomenc's stdin: this gate's
10480 // stream is ~100 KB, bigger than a pipe buffer, so an aomenc that
10481 // is still being fed on stdin blocks writing its stdout and the
10482 // test blocks writing its stdin -- a hard deadlock (measured
10483 // here, 3 min into attempt 0, class [[gate-loader-slurps-whole-file]]).
10484 // The path is PID-keyed (class [[pid-keyed-temp-path]]).
10485 let y4m_path = std::env::temp_dir().join(format!(
10486 "ec-av1-uv8-{}-{bit_depth}-{tile_columns}-{seed}.y4m",
10487 std::process::id()
10488 ));
10489 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
10490 let child = Command::new(aomenc_path())
10491 .args(depth_args)
10492 .args([
10493 "--codec=av1",
10494 "--passes=1",
10495 "--end-usage=q",
10496 &cq,
10497 "--cpu-used=0",
10498 "--lag-in-frames=0",
10499 "--auto-alt-ref=0",
10500 "--kf-max-dist=9999",
10501 "--kf-min-dist=9999",
10502 "--threads=1",
10503 "--row-mt=0",
10504 &tiles,
10505 "--enable-order-hint=0",
10506 "--enable-warped-motion=0",
10507 "--enable-obmc=0",
10508 "--enable-masked-comp=0",
10509 "--enable-interintra-comp=0",
10510 "--enable-dist-wtd-comp=0",
10511 "--enable-diff-wtd-comp=0",
10512 "--enable-onesided-comp=0",
10513 "--enable-interintra-wedge=0",
10514 "--enable-smooth-interintra=0",
10515 "--enable-ab-partitions=0",
10516 "--enable-1to4-partitions=0",
10517 "--enable-cdef=0",
10518 "--enable-restoration=0",
10519 "--enable-palette=0",
10520 "--enable-intrabc=0",
10521 "--enable-ref-frame-mvs=0",
10522 // Per-arm overrides go LAST (aomenc keeps the LAST
10523 // occurrence of a repeated --enable-* flag). The three
10524 // chroma intra tools this gate is about, plus the fences
10525 // that keep the leaf's SIBLING refusals (its TX_4X4
10526 // split, a nonzero angle delta, sub-16 rect inter leaves)
10527 // out of the way.
10528 "--enable-cfl-intra=1",
10529 "--enable-smooth-intra=1",
10530 "--enable-paeth-intra=1",
10531 "--enable-directional-intra=1",
10532 "--enable-angle-delta=0",
10533 "--enable-tx-size-search=0",
10534 "--enable-rect-partitions=0",
10535 "--min-partition-size=8",
10536 "--max-partition-size=32",
10537 "--obu",
10538 "-o",
10539 "-",
10540 ])
10541 .arg(&y4m_path)
10542 .stdin(Stdio::null())
10543 .stdout(Stdio::piped())
10544 .stderr(Stdio::piped())
10545 .spawn()
10546 .expect("aomenc failed to start");
10547 let out = child.wait_with_output().expect("aomenc failed to run");
10548 let _ = std::fs::remove_file(&y4m_path);
10549 assert!(
10550 out.status.success(),
10551 "aomenc refused the fixture: {}",
10552 String::from_utf8_lossy(&out.stderr)
10553 );
10554 let stream = out.stdout;
10555 let before = decode::intra_in_inter8_uv_hits();
10556 let frames = match decode_stream(&stream) {
10557 Ok(frames) => frames,
10558 Err(e) => {
10559 let msg = e.to_string();
10560 assert!(
10561 msg.contains("unsupported"),
10562 "{name} decode failed outright (seed {seed}): {msg}"
10563 );
10564 refusals.push(format!("seed {seed}: {msg}"));
10565 continue;
10566 }
10567 };
10568 let now = decode::intra_in_inter8_uv_hits();
10569 // class [[counter-from-refused-stream]]: per-attempt deltas, and
10570 // only for an attempt that decoded to the end and is pixel-
10571 // compared below.
10572 let fired = (now.0 - before.0, now.1 - before.1, now.2 - before.2);
10573 totals = (
10574 totals.0 + fired.0,
10575 totals.1 + fired.1,
10576 totals.2 + fired.2,
10577 );
10578 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
10579 // is ALWAYS pixel-compared; the counter only decides whether the
10580 // attempt counts as firing.
10581 // lane-uv8 r3: every one of the three chroma classes this gate
10582 // exists for (directional, smooth/paeth, CfL) must fire on the
10583 // SAME pixel-compared attempt -- a sum-nonzero predicate would
10584 // pass on an attempt that only ever hit DC-adjacent CfL.
10585 let counted = fired.0 > 0 && fired.1 > 0 && fired.2 > 0;
10586 if !counted {
10587 uncounted_exact += 1;
10588 refusals.push(format!(
10589 "seed {seed}: decoded and pixel-compared, but no 8x8 intra leaf in an inter \
10590 frame carried a non-DC uv_mode"
10591 ));
10592 }
10593 let ffmpeg_frames = if bit_depth == 10 {
10594 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
10595 } else {
10596 ffmpeg_decode_sequence(&stream, width, height, frame_count)
10597 };
10598 assert_eq!(frames.len(), frame_count);
10599 eprintln!(
10600 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with a non-DC uv_mode -- \
10601 directional {}, smooth/paeth {}, CfL {}",
10602 fired.0, fired.1, fired.2
10603 );
10604 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10605 for (plane, (g, w)) in [
10606 ("Y", (&got.y, &want.y)),
10607 ("U", (&got.u, &want.u)),
10608 ("V", (&got.v, &want.v)),
10609 ] {
10610 let stride = if plane == "Y" { width } else { width / 2 };
10611 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
10612 eprintln!(
10613 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
10614 want {} ({} samples differ)",
10615 at % stride,
10616 at / stride,
10617 g[at],
10618 w[at],
10619 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
10620 );
10621 }
10622 }
10623 }
10624 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10625 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
10626 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
10627 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
10628 }
10629 if counted {
10630 gate_buckets(
10631 &name,
10632 1,
10633 uncounted_exact,
10634 refusals.len() - uncounted_exact as usize,
10635 );
10636 return;
10637 }
10638 }
10639 gate_buckets(
10640 &name,
10641 0,
10642 uncounted_exact,
10643 refusals.len() - uncounted_exact as usize,
10644 );
10645 panic!(
10646 "{name} never observed a non-DC uv_mode on an 8x8 intra leaf in an inter frame \
10647 (totals dir/smooth/cfl {totals:?}):\n{}",
10648 refusals.join("\n")
10649 );
10650 }
10651
10652
10653 /// lane-leaf8tx r1: the refusal this round lifts on an INTRA 8x8 leaf
10654 /// inside an INTER frame -- a nonzero luma `angle_delta_y` on it
10655 /// (`--enable-angle-delta=1`,
10656 /// `av1_use_angle_delta(BLOCK_8X8)`). Both counters are per-attempt
10657 /// deltas on an attempt that decoded to the end and is pixel-compared
10658 /// (class [[counter-from-refused-stream]]); a decode error or a mismatch
10659 /// is a FAILURE, never a SKIP.
10660 #[test]
10661 fn a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
10662 tx_split_angle_in_inter8_gate(8);
10663 }
10664
10665 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
10666 #[test]
10667 fn a_real_aomenc_10bit_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
10668 tx_split_angle_in_inter8_gate(10);
10669 }
10670
10671 fn tx_split_angle_in_inter8_gate(bit_depth: u32) {
10672 let name = format!("tx_split_angle_in_inter8_gate({bit_depth})");
10673 if !have_ffmpeg() {
10674 eprintln!("SKIP {name}: no ffmpeg");
10675 return;
10676 }
10677 if !have_aomenc() {
10678 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
10679 return;
10680 }
10681 let (width, height, frame_count) = (192usize, 128usize, 6usize);
10682 let mut refusals = Vec::new();
10683 let mut uncounted_exact = 0u32;
10684 let mut counted_exact = 0u32;
10685 let mut totals = (0usize, 0usize);
10686 for attempt in 0..30u32 {
10687 let seed = 42 + attempt;
10688 // Same zoom + hard-cut fractal source the sibling uv_mode gate
10689 // uses (a cut is what makes aomenc code INTRA blocks inside an
10690 // inter frame); `noise` carries an explicit seed (class
10691 // [[seeded-fixture-not-reproducible]]).
10692 let source = format!(
10693 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
10694 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
10695 [a][b]overlay=enable='gte(n,3)',noise=alls=12:allf=t+u:all_seed={seed}",
10696 5.0 - f64::from(attempt) * 0.06,
10697 0.9 + f64::from(attempt) * 0.11
10698 );
10699 let y4m = Command::new("ffmpeg")
10700 .args([
10701 "-v",
10702 "error",
10703 "-f",
10704 "lavfi",
10705 "-i",
10706 &source,
10707 "-pix_fmt",
10708 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
10709 "-strict",
10710 "-1",
10711 "-t",
10712 "0.24",
10713 "-f",
10714 "yuv4mpegpipe",
10715 "-strict",
10716 "-1",
10717 "-",
10718 ])
10719 .stdin(Stdio::null())
10720 .stdout(Stdio::piped())
10721 .stderr(Stdio::piped())
10722 .output()
10723 .expect("ffmpeg failed to run");
10724 assert!(
10725 y4m.status.success(),
10726 "ffmpeg fixture: {}",
10727 String::from_utf8_lossy(&y4m.stderr)
10728 );
10729 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
10730 let depth_args: &[&str] = if bit_depth == 10 {
10731 &["-b", "10", "--input-bit-depth=10"]
10732 } else {
10733 &[]
10734 };
10735 // The y4m goes through a PID-keyed FILE, never aomenc's stdin
10736 // (pipe deadlock, class [[gate-loader-slurps-whole-file]]).
10737 let y4m_path = std::env::temp_dir().join(format!(
10738 "ec-av1-leaf8tx-{}-{bit_depth}-{seed}.y4m",
10739 std::process::id()
10740 ));
10741 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
10742 let child = Command::new(aomenc_path())
10743 .args(depth_args)
10744 .args([
10745 "--codec=av1",
10746 "--passes=1",
10747 "--end-usage=q",
10748 &cq,
10749 "--cpu-used=0",
10750 "--lag-in-frames=0",
10751 "--auto-alt-ref=0",
10752 "--kf-max-dist=9999",
10753 "--kf-min-dist=9999",
10754 "--threads=1",
10755 "--row-mt=0",
10756 "--tile-columns=0",
10757 "--enable-order-hint=0",
10758 "--enable-warped-motion=0",
10759 "--enable-obmc=0",
10760 "--enable-masked-comp=0",
10761 "--enable-interintra-comp=0",
10762 "--enable-dist-wtd-comp=0",
10763 "--enable-diff-wtd-comp=0",
10764 "--enable-onesided-comp=0",
10765 "--enable-interintra-wedge=0",
10766 "--enable-smooth-interintra=0",
10767 "--enable-ab-partitions=0",
10768 "--enable-1to4-partitions=0",
10769 "--enable-cdef=0",
10770 "--enable-restoration=0",
10771 "--enable-palette=0",
10772 "--enable-intrabc=0",
10773 "--enable-ref-frame-mvs=0",
10774 // Per-arm overrides LAST (aomenc keeps the last
10775 // occurrence of a repeated --enable-* flag). Rect
10776 // partitions stay off so the leaf's unrelated sub-16 rect
10777 // inter refusal never fires.
10778 "--enable-rect-partitions=0",
10779 "--enable-tx-size-search=1",
10780 "--enable-angle-delta=1",
10781 "--enable-directional-intra=1",
10782 "--min-partition-size=8",
10783 "--max-partition-size=32",
10784 "--obu",
10785 "-o",
10786 "-",
10787 ])
10788 // r1 diagnostic: EC_LEAF8TX_CONTROL=1 turns THIS lane's two
10789 // tools back off (last occurrence of a repeated --enable-*
10790 // wins), so any mismatch that survives is not this lane's.
10791 .args(match std::env::var("EC_LEAF8TX_CONTROL").as_deref() {
10792 Ok("angle") => vec!["--enable-tx-size-search=0", "--enable-angle-delta=1"],
10793 Ok("tx") => vec!["--enable-tx-size-search=1", "--enable-angle-delta=0"],
10794 Ok("tx8") => vec![
10795 "--enable-tx-size-search=1",
10796 "--enable-angle-delta=0",
10797 "--max-partition-size=8",
10798 ],
10799 Ok(_) => vec!["--enable-tx-size-search=0", "--enable-angle-delta=0"],
10800 // Shipped recipe (lane-leaf8tx r4): BOTH of this lane's
10801 // tools on -- the tx_depth split at an 8x8 intra-in-inter
10802 // leaf is what the lifted refusal covers, so
10803 // `--enable-tx-size-search=1` must survive the per-arm
10804 // override (aomenc keeps the LAST occurrence). Odd
10805 // attempts also cap the partition at 8x8, the shape that
10806 // produces the 2x2 TX_4X4 grid most often.
10807 Err(_) => {
10808 if attempt % 2 == 1 {
10809 vec![
10810 "--enable-tx-size-search=1",
10811 "--enable-angle-delta=1",
10812 "--max-partition-size=8",
10813 ]
10814 } else {
10815 vec!["--enable-tx-size-search=1", "--enable-angle-delta=1"]
10816 }
10817 }
10818 })
10819 .arg(&y4m_path)
10820 .stdin(Stdio::null())
10821 .stdout(Stdio::piped())
10822 .stderr(Stdio::piped())
10823 .spawn()
10824 .expect("aomenc failed to start");
10825 let out = child.wait_with_output().expect("aomenc failed to run");
10826 let _ = std::fs::remove_file(&y4m_path);
10827 assert!(
10828 out.status.success(),
10829 "aomenc refused the fixture: {}",
10830 String::from_utf8_lossy(&out.stderr)
10831 );
10832 let stream = out.stdout;
10833 let before = (
10834 decode::intra_in_inter_split_tx_hits()[0],
10835 decode::intra_in_inter8_angle_delta_y_hits(),
10836 );
10837 let frames = match decode_stream(&stream) {
10838 Ok(frames) => frames,
10839 Err(e) => {
10840 let msg = e.to_string();
10841 assert!(
10842 msg.contains("unsupported"),
10843 "{name} decode failed outright (seed {seed}): {msg}"
10844 );
10845 refusals.push(format!("seed {seed}: {msg}"));
10846 continue;
10847 }
10848 };
10849 let now = (
10850 decode::intra_in_inter_split_tx_hits()[0],
10851 decode::intra_in_inter8_angle_delta_y_hits(),
10852 );
10853 let fired = (now.0 - before.0, now.1 - before.1);
10854 totals = (totals.0 + fired.0, totals.1 + fired.1);
10855 // Both lifted capabilities must fire on the SAME pixel-compared
10856 // attempt.
10857 let counted = fired.1 > 0;
10858 if !counted {
10859 uncounted_exact += 1;
10860 refusals.push(format!(
10861 "seed {seed}: decoded and pixel-compared, but split-tx {} / angle-delta {} \
10862 8x8 intra-in-inter leaves",
10863 fired.0, fired.1
10864 ));
10865 }
10866 let ffmpeg_frames = if bit_depth == 10 {
10867 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
10868 } else {
10869 ffmpeg_decode_sequence(&stream, width, height, frame_count)
10870 };
10871 assert_eq!(frames.len(), frame_count);
10872 eprintln!(
10873 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with tx_depth=1 {}, with a \
10874 nonzero angle_delta_y {} (split-tx per size 8/16/32/64 {:?})",
10875 fired.0,
10876 fired.1,
10877 decode::intra_in_inter_split_tx_hits()
10878 );
10879 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10880 for (plane, (g, w)) in [
10881 ("Y", (&got.y, &want.y)),
10882 ("U", (&got.u, &want.u)),
10883 ("V", (&got.v, &want.v)),
10884 ] {
10885 let stride = if plane == "Y" { width } else { width / 2 };
10886 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
10887 eprintln!(
10888 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
10889 want {} ({} samples differ)",
10890 at % stride,
10891 at / stride,
10892 g[at],
10893 w[at],
10894 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
10895 );
10896 }
10897 }
10898 }
10899 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10900 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
10901 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
10902 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
10903 }
10904 if counted {
10905 counted_exact += 1;
10906 }
10907 }
10908 // lane-leaf8tx r4: continue-and-sweep -- every arm is encoded,
10909 // decoded and pixel-compared on every plane of every decode-order
10910 // frame above; the counters are asserted ONCE here. A decode error or
10911 // a mismatch is a failure, never a SKIP, and `uncounted_exact`
10912 // (decoded + compared but neither capability fired) is the
10913 // out-of-scope-mismatch bucket that the sweep tolerates only while at
10914 // least one attempt did fire.
10915 gate_buckets(
10916 &name,
10917 counted_exact,
10918 uncounted_exact,
10919 refusals.len() - uncounted_exact as usize,
10920 );
10921 assert!(
10922 totals.0 > 0,
10923 "{name}: no decoded+compared attempt carried an 8x8 intra-in-inter leaf with \
10924 tx_depth split to 4x4 (split-tx per size {:?}, angle-delta {}):\n{}",
10925 decode::intra_in_inter_split_tx_hits(),
10926 totals.1,
10927 refusals.join("\n")
10928 );
10929 assert!(
10930 totals.1 > 0,
10931 "{name}: no decoded+compared attempt carried a nonzero angle_delta_y on an 8x8 \
10932 intra-in-inter leaf (split-tx {}):\n{}",
10933 totals.0,
10934 refusals.join("\n")
10935 );
10936 }
10937
10938 /// lane-chroma r2 stage 1: a real aomenc key frame with
10939 /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`)
10940 /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still-
10941 /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never
10942 /// fires; smooth *luma* neighbours are exactly what this gate wants to
10943 /// exercise, proving [`decode::smooth_luma_hits`] actually landed a
10944 /// directional block next to a smooth-predicted one and decoded
10945 /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix).
10946 #[test]
10947 fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() {
10948 if !have_ffmpeg() {
10949 eprintln!(
10950 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg"
10951 );
10952 return;
10953 }
10954 if !have_aomenc() {
10955 eprintln!(
10956 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}",
10957 aomenc_path().display()
10958 );
10959 return;
10960 }
10961 let (width, height) = (64usize, 64usize);
10962 let mut refusals = Vec::new();
10963 let mut fired_runs = 0u32;
10964 let mut uncounted_exact = 0u32;
10965 for attempt in 0..40u32 {
10966 let seed = 42 + attempt;
10967 let source = format!(
10968 "mandelbrot=size=64x64:start_scale={}:rate=25",
10969 5.0 - f64::from(attempt) * 0.06
10970 );
10971 let y4m = Command::new("ffmpeg")
10972 .args([
10973 "-v",
10974 "error",
10975 "-f",
10976 "lavfi",
10977 "-i",
10978 &source,
10979 "-pix_fmt",
10980 "yuv420p",
10981 "-t",
10982 "0.04",
10983 "-f",
10984 "yuv4mpegpipe",
10985 "-",
10986 ])
10987 .stdin(Stdio::null())
10988 .stdout(Stdio::piped())
10989 .stderr(Stdio::piped())
10990 .output()
10991 .expect("ffmpeg failed to run");
10992 assert!(
10993 y4m.status.success(),
10994 "ffmpeg fixture: {}",
10995 String::from_utf8_lossy(&y4m.stderr)
10996 );
10997 let mut child = Command::new(aomenc_path())
10998 .args([
10999 "--codec=av1",
11000 "--passes=1",
11001 "--end-usage=q",
11002 "--cq-level=45",
11003 "--cpu-used=0",
11004 "--enable-rect-partitions=0",
11005 "--enable-ab-partitions=0",
11006 "--enable-1to4-partitions=0",
11007 "--enable-filter-intra=0",
11008 "--enable-smooth-intra=1",
11009 // Smooth/paeth chroma is a still-refused, separate
11010 // round-2 gap -- off so no attempt trips it while this
11011 // gate is purely about luma's edge-filter fix.
11012 "--enable-paeth-intra=0",
11013 "--enable-tx-size-search=0",
11014 "--enable-cdef=0",
11015 "--enable-restoration=0",
11016 "--enable-intra-edge-filter=1",
11017 "--max-partition-size=32",
11018 "--min-partition-size=16",
11019 "--enable-palette=0",
11020 "--enable-intrabc=0",
11021 "--enable-cfl-intra=0",
11022 "--enable-ref-frame-mvs=0",
11023 "--obu",
11024 "-o",
11025 "-",
11026 "-",
11027 ])
11028 .stdin(Stdio::piped())
11029 .stdout(Stdio::piped())
11030 .stderr(Stdio::piped())
11031 .spawn()
11032 .expect("aomenc failed to start");
11033 child
11034 .stdin
11035 .take()
11036 .expect("aomenc stdin")
11037 .write_all(&y4m.stdout)
11038 .expect("writing y4m to aomenc");
11039 let out = child.wait_with_output().expect("aomenc failed to run");
11040 assert!(
11041 out.status.success(),
11042 "aomenc refused the fixture: {}",
11043 String::from_utf8_lossy(&out.stderr)
11044 );
11045 let stream = out.stdout;
11046 let smooth_before = decode::smooth_luma_hits();
11047 let frames = match decode_stream(&stream) {
11048 Ok(frames) => frames,
11049 Err(e) => {
11050 refusals.push(format!("seed {seed}: {e}"));
11051 continue;
11052 }
11053 };
11054 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
11055 // is ALWAYS pixel-compared below; the hit counter only decides whether
11056 // the attempt counts toward the firing total.
11057 let counted = decode::smooth_luma_hits() != smooth_before;
11058 if counted {
11059 fired_runs += 1;
11060 } else {
11061 uncounted_exact += 1;
11062 refusals.push(format!(
11063 "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \
11064 fired"
11065 ));
11066 }
11067 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
11068 assert_eq!(
11069 frames[0].y, ffmpeg_frames[0].y,
11070 "luma vs ffmpeg (seed {seed})"
11071 );
11072 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
11073 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
11074 if fired_runs >= 4 {
11075 gate_buckets(
11076 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
11077 fired_runs,
11078 uncounted_exact,
11079 refusals.len() - uncounted_exact as usize,
11080 );
11081 return;
11082 }
11083 }
11084 gate_buckets(
11085 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
11086 fired_runs,
11087 uncounted_exact,
11088 refusals.len() - uncounted_exact as usize,
11089 );
11090 assert!(
11091 fired_runs > 0,
11092 "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}",
11093 refusals.join("\n")
11094 );
11095 }
11096
11097 /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key
11098 /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the
11099 /// opposite of the directional-chroma gate below, which turns these OFF
11100 /// to keep this gap from firing while directional chroma is under test).
11101 /// Some seeds won't pick smooth/paeth for chroma at all -- retry like
11102 /// every other real-encoder gate here, but the first attempt that
11103 /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact.
11104 #[test]
11105 fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() {
11106 if !have_ffmpeg() {
11107 eprintln!(
11108 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg"
11109 );
11110 return;
11111 }
11112 if !have_aomenc() {
11113 eprintln!(
11114 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}",
11115 aomenc_path().display()
11116 );
11117 return;
11118 }
11119 let (width, height) = (64usize, 64usize);
11120 let mut refusals = Vec::new();
11121 let mut fired_runs = 0u32;
11122 let mut uncounted_exact = 0u32;
11123 for attempt in 0..40u32 {
11124 let seed = 42 + attempt;
11125 let source = format!(
11126 "mandelbrot=size=64x64:start_scale={}:rate=25",
11127 5.0 - f64::from(attempt) * 0.06
11128 );
11129 let y4m = Command::new("ffmpeg")
11130 .args([
11131 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-t",
11132 "0.04", "-f", "yuv4mpegpipe", "-",
11133 ])
11134 .stdin(Stdio::null())
11135 .stdout(Stdio::piped())
11136 .stderr(Stdio::piped())
11137 .output()
11138 .expect("ffmpeg failed to run");
11139 assert!(
11140 y4m.status.success(),
11141 "ffmpeg fixture: {}",
11142 String::from_utf8_lossy(&y4m.stderr)
11143 );
11144 let mut child = Command::new(aomenc_path())
11145 .args([
11146 "--codec=av1",
11147 "--passes=1",
11148 "--end-usage=q",
11149 "--cq-level=45",
11150 "--cpu-used=0",
11151 "--enable-rect-partitions=0",
11152 "--enable-ab-partitions=0",
11153 "--enable-1to4-partitions=0",
11154 "--enable-filter-intra=0",
11155 "--enable-smooth-intra=1",
11156 "--enable-paeth-intra=1",
11157 "--enable-tx-size-search=0",
11158 "--enable-cdef=0",
11159 "--enable-restoration=0",
11160 "--enable-intra-edge-filter=1",
11161 "--max-partition-size=32",
11162 // 8x8/leaf8 splits are a separate, already-named refusal.
11163 "--min-partition-size=16",
11164 "--enable-palette=0",
11165 "--enable-intrabc=0",
11166 "--enable-cfl-intra=0",
11167 "--enable-ref-frame-mvs=0",
11168 "--obu",
11169 "-o",
11170 "-",
11171 "-",
11172 ])
11173 .stdin(Stdio::piped())
11174 .stdout(Stdio::piped())
11175 .stderr(Stdio::piped())
11176 .spawn()
11177 .expect("aomenc failed to start");
11178 child
11179 .stdin
11180 .take()
11181 .expect("aomenc stdin")
11182 .write_all(&y4m.stdout)
11183 .expect("writing y4m to aomenc");
11184 let out = child.wait_with_output().expect("aomenc failed to run");
11185 assert!(
11186 out.status.success(),
11187 "aomenc refused the fixture: {}",
11188 String::from_utf8_lossy(&out.stderr)
11189 );
11190 let stream = out.stdout;
11191 let smooth_before = decode::smooth_uv_hits();
11192 let frames = match decode_stream(&stream) {
11193 Ok(frames) => frames,
11194 Err(e) => {
11195 refusals.push(format!("seed {seed}: {e}"));
11196 continue;
11197 }
11198 };
11199 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
11200 // is ALWAYS pixel-compared below; the hit counter only decides whether
11201 // the attempt counts toward the firing total.
11202 let counted = decode::smooth_uv_hits() != smooth_before;
11203 if counted {
11204 fired_runs += 1;
11205 } else {
11206 uncounted_exact += 1;
11207 refusals.push(format!(
11208 "seed {seed}: decoded and pixel-compared, but no smooth/paeth uv_mode fired"
11209 ));
11210 }
11211 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
11212 assert_eq!(
11213 frames[0].y, ffmpeg_frames[0].y,
11214 "luma vs ffmpeg (seed {seed})"
11215 );
11216 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
11217 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
11218 if fired_runs >= 4 {
11219 gate_buckets(
11220 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
11221 fired_runs,
11222 uncounted_exact,
11223 refusals.len() - uncounted_exact as usize,
11224 );
11225 return;
11226 }
11227 }
11228 gate_buckets(
11229 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
11230 fired_runs,
11231 uncounted_exact,
11232 refusals.len() - uncounted_exact as usize,
11233 );
11234 assert!(
11235 fired_runs > 0,
11236 "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}",
11237 refusals.join("\n")
11238 );
11239 }
11240
11241 /// The directional-chroma/angle-delta gate: a real aomenc key frame with
11242 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
11243 /// opposite of every sibling recipe's `=0`, which existed specifically to
11244 /// keep this round-2 gap from firing while a different surface was under
11245 /// test). A colourful, sharp-edged source gives the RD search a reason to
11246 /// pick a directional `uv_mode` and/or a nonzero angle delta -- some
11247 /// seeds still won't, so retry like every other real-encoder gate here,
11248 /// but the first attempt that actually fires either counter must decode
11249 /// pixel-exact.
11250 #[test]
11251 fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() {
11252 if !have_ffmpeg() {
11253 eprintln!(
11254 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg"
11255 );
11256 return;
11257 }
11258 if !have_aomenc() {
11259 eprintln!(
11260 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}",
11261 aomenc_path().display()
11262 );
11263 return;
11264 }
11265 let (width, height) = (64usize, 64usize);
11266 let mut refusals = Vec::new();
11267 let mut fired_runs = 0u32;
11268 let mut uncounted_exact = 0u32;
11269 for attempt in 0..40u32 {
11270 let seed = 42 + attempt;
11271 let source = format!(
11272 "mandelbrot=size=64x64:start_scale={}:rate=25",
11273 5.0 - f64::from(attempt) * 0.06
11274 );
11275 let y4m = Command::new("ffmpeg")
11276 .args([
11277 "-v",
11278 "error",
11279 "-f",
11280 "lavfi",
11281 "-i",
11282 &source,
11283 "-pix_fmt",
11284 "yuv420p",
11285 "-t",
11286 "0.04",
11287 "-f",
11288 "yuv4mpegpipe",
11289 "-",
11290 ])
11291 .stdin(Stdio::null())
11292 .stdout(Stdio::piped())
11293 .stderr(Stdio::piped())
11294 .output()
11295 .expect("ffmpeg failed to run");
11296 assert!(
11297 y4m.status.success(),
11298 "ffmpeg fixture: {}",
11299 String::from_utf8_lossy(&y4m.stderr)
11300 );
11301 let mut child = Command::new(aomenc_path())
11302 .args([
11303 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
11304 // occurrence, so overrides go before the base list).
11305 "--enable-directional-intra=1",
11306 "--codec=av1",
11307 "--passes=1",
11308 "--end-usage=q",
11309 "--cq-level=45",
11310 "--cpu-used=0",
11311 "--enable-rect-partitions=0",
11312 "--enable-ab-partitions=0",
11313 "--enable-1to4-partitions=0",
11314 "--enable-filter-intra=0",
11315 // Smooth/Paeth chroma is a separate, still-refused round-2
11316 // gap (an unrelated `Edges::build` no-neighbour bug this
11317 // lane does not cover) -- off so the RD search's only
11318 // non-DC/CFL chroma choice left is directional.
11319 "--enable-smooth-intra=0",
11320 "--enable-paeth-intra=0",
11321 "--enable-tx-size-search=0",
11322 "--enable-cdef=0",
11323 "--enable-restoration=0",
11324 // The intra edge filter/upsample (spec 7.11.2.7-2.9) is
11325 // now implemented (`directional()`) -- left ON (aomenc's
11326 // own default) so this gate actually exercises it instead
11327 // of the un-filtered fast path a disabled flag would keep
11328 // testing.
11329 "--enable-intra-edge-filter=1",
11330 "--max-partition-size=32",
11331 // Same reason as the tx-select gate above: 8x8 and other
11332 // sub-16x16 splits are a separate, already-named refusal.
11333 "--min-partition-size=16",
11334 "--enable-palette=0",
11335 "--enable-intrabc=0",
11336 "--enable-cfl-intra=0",
11337 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
11338 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
11339 "--enable-ref-frame-mvs=0",
11340 "--obu",
11341 "-o",
11342 "-",
11343 "-",
11344 ])
11345 .stdin(Stdio::piped())
11346 .stdout(Stdio::piped())
11347 .stderr(Stdio::piped())
11348 .spawn()
11349 .expect("aomenc failed to start");
11350 child
11351 .stdin
11352 .take()
11353 .expect("aomenc stdin")
11354 .write_all(&y4m.stdout)
11355 .expect("writing y4m to aomenc");
11356 let out = child.wait_with_output().expect("aomenc failed to run");
11357 assert!(
11358 out.status.success(),
11359 "aomenc refused the fixture: {}",
11360 String::from_utf8_lossy(&out.stderr)
11361 );
11362 let stream = out.stdout;
11363 let (uv_before, angle_before) =
11364 (decode::directional_uv_hits(), decode::angle_delta_hits());
11365 let frames = match decode_stream(&stream) {
11366 Ok(frames) => frames,
11367 Err(e) => {
11368 refusals.push(format!("seed {seed}: {e}"));
11369 continue;
11370 }
11371 };
11372 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
11373 // is ALWAYS pixel-compared below; the hit counter only decides whether
11374 // the attempt counts toward the firing total.
11375 let counted = decode::directional_uv_hits() != uv_before
11376 || decode::angle_delta_hits() != angle_before;
11377 if counted {
11378 fired_runs += 1;
11379 } else {
11380 uncounted_exact += 1;
11381 refusals.push(format!(
11382 "seed {seed}: decoded and pixel-compared, but neither a directional uv_mode \
11383 nor a nonzero angle delta fired"
11384 ));
11385 }
11386 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
11387 assert_eq!(
11388 frames[0].y, ffmpeg_frames[0].y,
11389 "luma vs ffmpeg (seed {seed})"
11390 );
11391 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
11392 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
11393 if fired_runs >= 4 {
11394 gate_buckets(
11395 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
11396 fired_runs,
11397 uncounted_exact,
11398 refusals.len() - uncounted_exact as usize,
11399 );
11400 return;
11401 }
11402 }
11403 gate_buckets(
11404 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
11405 fired_runs,
11406 uncounted_exact,
11407 refusals.len() - uncounted_exact as usize,
11408 );
11409 assert!(
11410 fired_runs > 0,
11411 "every attempt hit a named refusal or never exercised directional chroma:\n{}",
11412 refusals.join("\n")
11413 );
11414 }
11415
11416 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
11417 /// --auto-alt-ref=0` keep every non-key frame a simple forward
11418 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this
11419 /// decoder's inter path does not model), `--kf-max-dist` past the clip's
11420 /// own length keeps frame 0 the only key frame.
11421 /// lane-inter8 r1: the inter tile path's SB-level `PARTITION_NONE` -- a
11422 /// whole 64x64 superblock coded as ONE inter block, which is what aomenc
11423 /// picks for static content and which this decoder refused by name
11424 /// ("an inter SB-level partition type other than SPLIT") until this
11425 /// round. HARD-asserts [`decode::inter_sb_none_hits`] moved (the arm
11426 /// really fired, class refusal-lifted-without-a-gate) and every frame is
11427 /// pixel-exact vs ffmpeg; a decode error is a FAILURE here, never a SKIP
11428 /// (class gate-skips-on-its-own-failure).
11429 /// lane-inter8 r1: generalised so the same recipe can target a deeper
11430 /// level of the inter partition tree -- `min_part` is aomenc's
11431 /// `--min-partition-size`, and `hits`/`what` name the counter that proves
11432 /// the arm under test really fired.
11433 #[track_caller]
11434 fn inter_sb_none_gate(
11435 name: &str,
11436 ten_bit: bool,
11437 min_part: &str,
11438 max_part: &str,
11439 hits: fn() -> usize,
11440 what: &str,
11441 // lane-inter8 r3: extra aomenc flags + the frame width they need.
11442 // `--tile-columns=1` needs a frame at least two superblocks wide or
11443 // aomenc silently codes one tile column and the arm is vacuous.
11444 extra: &[&str],
11445 width: usize,
11446 // lane-interp3 r1: sequence length -- a compound block needs several
11447 // already-coded references, which a 4-frame sequence never has.
11448 frame_count: usize,
11449 ) {
11450 if !have_ffmpeg() {
11451 eprintln!("SKIP {name}: no ffmpeg");
11452 return;
11453 }
11454 if !have_aomenc() {
11455 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
11456 return;
11457 }
11458 let height = 64usize;
11459 let duration = format!("{:.2}", frame_count as f64 / 25.0);
11460 // A deterministic synthetic source with real motion (a static source
11461 // codes every inter frame as skip and never exercises the residual
11462 // path); bounded with `-t` (class gate-loader-slurps-whole-file).
11463 let y4m = Command::new("ffmpeg")
11464 .args([
11465 "-v",
11466 "error",
11467 "-f",
11468 "lavfi",
11469 "-i",
11470 &format!("mandelbrot=size={width}x{height}:rate=25"),
11471 "-t",
11472 &duration,
11473 "-pix_fmt",
11474 if ten_bit { "yuv420p10le" } else { "yuv420p" },
11475 // y4m calls 10-bit unofficial (same as the 10-bit key-frame
11476 // gate's own fixture).
11477 "-strict",
11478 "-1",
11479 "-f",
11480 "yuv4mpegpipe",
11481 "-",
11482 ])
11483 .stdin(Stdio::null())
11484 .stdout(Stdio::piped())
11485 .stderr(Stdio::piped())
11486 .output()
11487 .expect("ffmpeg failed to run");
11488 assert!(
11489 y4m.status.success(),
11490 "{name}: ffmpeg fixture: {}",
11491 String::from_utf8_lossy(&y4m.stderr)
11492 );
11493 let mut args: Vec<String> = [
11494 "--codec=av1",
11495 "--passes=1",
11496 "--end-usage=q",
11497 "--cq-level=40",
11498 "--cpu-used=0",
11499 "--lag-in-frames=0",
11500 "--auto-alt-ref=0",
11501 "--kf-max-dist=1000",
11502 // No cross-frame CDF forwarding in this fixture (see the
11503 // deblocking gate's own note).
11504 "--error-resilient=1",
11505 // This gate targets the SB-level NONE arm only: rect/AB/1-to-4
11506 // partitions and sub-16x16 splits stay off so a failure here
11507 // cannot be another lane's missing arm.
11508 "--enable-rect-partitions=0",
11509 "--enable-ab-partitions=0",
11510 "--enable-1to4-partitions=0",
11511 "--enable-filter-intra=0",
11512 "--enable-smooth-intra=0",
11513 "--enable-paeth-intra=0",
11514 "--enable-directional-intra=0",
11515 "--enable-angle-delta=0",
11516 "--enable-tx-size-search=0",
11517 "--enable-cdef=0",
11518 "--enable-restoration=0",
11519 "--enable-palette=0",
11520 "--enable-intrabc=0",
11521 "--enable-cfl-intra=0",
11522 "--enable-ref-frame-mvs=0",
11523 "--obu",
11524 "-o",
11525 "-",
11526 "-",
11527 ]
11528 .iter()
11529 .map(|s| (*s).to_string())
11530 .collect();
11531 for e in extra {
11532 args.insert(1, (*e).to_string());
11533 }
11534 args.insert(1, format!("--min-partition-size={min_part}"));
11535 args.insert(1, format!("--max-partition-size={max_part}"));
11536 if ten_bit {
11537 args.insert(1, "--input-bit-depth=10".to_string());
11538 args.insert(1, "--bit-depth=10".to_string());
11539 }
11540 let mut child = Command::new(aomenc_path())
11541 .args(&args)
11542 .stdin(Stdio::piped())
11543 .stdout(Stdio::piped())
11544 .stderr(Stdio::piped())
11545 .spawn()
11546 .expect("aomenc failed to start");
11547 child
11548 .stdin
11549 .take()
11550 .expect("aomenc stdin")
11551 .write_all(&y4m.stdout)
11552 .expect("writing y4m to aomenc");
11553 let out = child.wait_with_output().expect("aomenc failed to run");
11554 assert!(
11555 out.status.success(),
11556 "{name}: aomenc refused the fixture: {}",
11557 String::from_utf8_lossy(&out.stderr)
11558 );
11559 let stream = out.stdout;
11560 let before = hits();
11561 let frames = match decode_stream(&stream) {
11562 Ok(frames) => frames,
11563 Err(e) => {
11564 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
11565 let _ = std::fs::write(&pin, &stream);
11566 panic!("{name}: decode_stream refused a real aomenc stream: {e} (pinned at {})", pin.display());
11567 }
11568 };
11569 assert!(
11570 hits() > before,
11571 "{name}: no {what} fired -- this gate proves nothing"
11572 );
11573 let ffmpeg_frames = if ten_bit {
11574 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
11575 } else {
11576 ffmpeg_decode_sequence(&stream, width, height, frame_count)
11577 };
11578 assert_eq!(frames.len(), frame_count, "{name}: frame count");
11579 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11580 if got.y != want.y || got.u != want.u || got.v != want.v {
11581 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
11582 let _ = std::fs::write(&pin, &stream);
11583 panic!("{name}: frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display());
11584 }
11585 }
11586 }
11587
11588 #[test]
11589 fn a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
11590 inter_sb_none_gate(
11591 "a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
11592 false,
11593 "32",
11594 "64",
11595 decode::inter_sb_none_hits,
11596 "whole-superblock inter PARTITION_NONE",
11597 &[],
11598 64,
11599 4,
11600 );
11601 }
11602
11603 #[test]
11604 fn a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
11605 inter_sb_none_gate(
11606 "a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
11607 true,
11608 "32",
11609 "64",
11610 decode::inter_sb_none_hits,
11611 "whole-superblock inter PARTITION_NONE",
11612 &[],
11613 64,
11614 4,
11615 );
11616 }
11617
11618 /// lane-inter8 r1: the same recipe with `--min-partition-size=8`, so
11619 /// aomenc's RD may split a 16x16 inter block into four 8x8 leaves. The
11620 /// interior (non-edge-straddling) `PARTITION_SPLIT` at the 16x16 level
11621 /// was refused by name until this round; the straddle path always ran the
11622 /// same loop, so only [`decode::inter_sub16_split_hits`] -- which counts
11623 /// interior splits only -- proves the newly-lifted alphabet value fired.
11624 // lane-inter8 r2: GREEN. The neighbour side bands are mi-granular, every
11625 // leaf stamps its own 2x2-mi span (including the compound-return path
11626 // that used to skip `record_mi` entirely) and the compound
11627 // group/index contexts read the LEAF's mi cell, not its 16x16's corner.
11628 /// lane-inter8 r3, from lane-sub8's verifier finding: the mi-granular
11629 /// inter neighbour bands added in r2 must reset per TILE (above) and per
11630 /// SB row (left) and guard availability tile-relative, so the same recipe
11631 /// runs again at 128x64 with two tile columns -- a leaf on the second
11632 /// tile's first column has no left neighbour and must not read the first
11633 /// tile's band.
11634 // 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
11635 // was done by inspection instead: every reader of the mi bands guards on
11636 // `tile_row0_mi`/`tile_col0_mi` (no `> 0` guard exists in decode.rs),
11637 // `start_tile` resets the above mi bands over the tile's own mi column
11638 // span and `start_row` resets every left mi band.
11639 #[test]
11640 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact()
11641 {
11642 inter_sb_none_gate(
11643 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact",
11644 false,
11645 "8",
11646 "16",
11647 decode::inter_sub16_split_hits,
11648 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
11649 &["--tile-columns=1"],
11650 128,
11651 4,
11652 );
11653 }
11654
11655 /// lane-interp3 r1: the same 8x8-leaf recipe with DUAL FILTER, OBMC and
11656 /// warped motion on. `read_mb_interp_filter` runs for every inter block
11657 /// (libaom `decodemv.c` 1575), compound ones included; the compound 8x8
11658 /// leaf skipped it entirely, so a SWITCHABLE-filter stream lost a symbol
11659 /// per compound leaf and stamped the `[3, 3]` "no filter" sentinel, which
11660 /// made a neighbouring OBMC block's `neighbour_filter` PANIC (a crash on
11661 /// his data, not a named refusal). The three hard asserts prove the flags
11662 /// arrived: a compound 8x8 leaf that really read the filter, a block whose
11663 /// two dual-filter directions DIFFER (impossible with dual filter off),
11664 /// and an 8x8 OBMC blend.
11665 // lane-interp3 r2: the ENTROPY desync r1 measured is CLOSED -- the full
11666 // 16-frame stream now parses end to end and every `EC_MODE`/`EC_MODE_VAL`
11667 // element's msac RANGE matches the instrumented aomdec's line for line
11668 // (570/570 mode elements, 0 diff). Two twin-drift root causes, both in
11669 // `decode_inter_block8`'s compound arm: `read_compound_ref_frames` was
11670 // passed a hard-coded `LAST_FRAME` for every inter neighbour instead of
11671 // the real per-mi band, and the grid stamp cleared both per-slot
11672 // `is_global_mv_block` flags.
11673 // lane-interp3 r3: the luma reconstruction residue r2 left open is CLOSED
11674 // and this gate is GREEN. Third instance of the same twin-drift class:
11675 // libaom applies `allow_warp`'s GLOBAL branch to every
11676 // `is_global_mv_block` reference slot, compound included and independent
11677 // of `motion_mode` (`av1_init_warp_params` inside
11678 // `build_inter_predictors_8x8_and_bigger`'s per-`ref` loop) -- the 16x16+
11679 // compound arm has warped since lane-cwarp r1, the 8x8 leaf's compound arm
11680 // predicted BOTH taps translationally, so a GLOBAL_GLOBALMV 8x8 compound
11681 // leaf under a non-TRANSLATION model drifted a few luma levels, growing
11682 // away from the block origin. It was NOT OBMC: the `EC_OBMC` emitter this
11683 // round added to `decode.rs` diffs 325/325 lines against the instrumented
11684 // aomdec's own rung (position, span, neighbour mv/ref/bsize/filter) with
11685 // zero differences.
11686 #[test]
11687 fn a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() {
11688 const NAME: &str =
11689 "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact";
11690 if !have_ffmpeg() || !have_aomenc() {
11691 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
11692 return;
11693 }
11694 let before_dual = decode::dual_filter_diff_hits();
11695 let before_obmc = decode::obmc_hits_8();
11696 let before_cwarp8 = decode::compound_warp_hits_8();
11697 inter_sb_none_gate(
11698 NAME,
11699 false,
11700 "8",
11701 "16",
11702 decode::compound8_filter_hits,
11703 "a compound 8x8 leaf reading its own switchable interp_filter",
11704 &[
11705 "--enable-dual-filter=1",
11706 "--enable-obmc=1",
11707 "--enable-warped-motion=1",
11708 "--enable-onesided-comp=1",
11709 ],
11710 64,
11711 // Recipe search hook (same shape as EC_OBMC8_ATTEMPTS): a compound
11712 // block needs several coded references, so the sequence is longer
11713 // than the other arms' 4 frames.
11714 std::env::var("EC_INTERP3_FRAMES")
11715 .ok()
11716 .and_then(|v| v.parse().ok())
11717 .unwrap_or(16),
11718 );
11719 assert!(
11720 decode::dual_filter_diff_hits() > before_dual,
11721 "{NAME}: no block read two DIFFERENT dual-filter directions -- \
11722 --enable-dual-filter=1 did not arrive or aomenc declined it"
11723 );
11724 assert!(
11725 decode::obmc_hits_8() > before_obmc,
11726 "{NAME}: no 8x8 OBMC blend fired -- --enable-obmc=1 did not arrive"
11727 );
11728 assert!(
11729 decode::compound_warp_hits_8() > before_cwarp8,
11730 "{NAME}: no 8x8 COMPOUND leaf was predicted through the per-ref GLOBAL \
11731 warp -- the r3 root-cause path never fired, so this stream no longer \
11732 proves it"
11733 );
11734 }
11735
11736 #[test]
11737 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
11738 inter_sb_none_gate(
11739 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
11740 false,
11741 "8",
11742 "16",
11743 decode::inter_sub16_split_hits,
11744 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
11745 &[],
11746 64,
11747 4,
11748 );
11749 }
11750
11751 #[test]
11752 // 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.
11753 fn a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
11754 inter_sb_none_gate(
11755 "a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
11756 true,
11757 "8",
11758 "16",
11759 decode::inter_sub16_split_hits,
11760 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
11761 &[],
11762 64,
11763 4,
11764 );
11765 }
11766
11767 /// lane-eobc1 r1: an INTER sequence whose CHROMA coefficient blocks come
11768 /// off the class-1 (`TX_CLASS_HORIZ`/`VERT`) `eob_pt` row. Chroma codes
11769 /// no `tx_type` symbol of its own -- it inherits the colocated luma type
11770 /// (`av1_get_tx_type`, `blockd.h:1291`) -- so an 8x8 inter leaf whose
11771 /// luma picks `H_*`/`V_*` puts its 4x4 chroma on a CDF row this crate
11772 /// wired for only some sizes until this round (`eob_pt_class1: None` in
11773 /// 9 of 16 `TxbSet` arms, chroma 4x4/8x8 among them).
11774 ///
11775 /// The full tx set stays on (no `--reduced-tx-type-set=1`) and
11776 /// `--enable-flip-idtx=1` is asked for explicitly; the sinusoidal-stripe
11777 /// luma of the `tx_class1` key-frame gate is what actually resolves 1D
11778 /// types, and the temporally-moving chroma ramp keeps chroma out of
11779 /// `all_zero` so it has an `eob` to read at all. Attempts sweep cq and
11780 /// stripe period; a run counts only when
11781 /// [`decode::chroma_eob_class1_hits`] moved, and every shown frame is
11782 /// compared pixel-exact vs ffmpeg (a decode error is a FAILURE, never a
11783 /// SKIP -- class gate-skips-on-its-own-failure).
11784 fn chroma_class1_eob_gate(name: &str, ten_bit: bool) {
11785 if !have_ffmpeg() {
11786 eprintln!("SKIP {name}: no ffmpeg");
11787 return;
11788 }
11789 if !have_aomenc() {
11790 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
11791 return;
11792 }
11793 let (width, height, frame_count) = (64usize, 64usize, 4usize);
11794 let mut refusals = Vec::new();
11795 for attempt in 0..12u32 {
11796 let cq = 28 + (attempt % 4) * 10;
11797 let period = [4u32, 6, 8][(attempt as usize / 4) % 3];
11798 let y4m = Command::new("ffmpeg")
11799 .args([
11800 "-v",
11801 "error",
11802 "-f",
11803 "lavfi",
11804 "-i",
11805 &format!("testsrc2=size={width}x{height}:rate=25"),
11806 "-vf",
11807 &format!(
11808 "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"
11809 ),
11810 "-t",
11811 "0.16",
11812 "-pix_fmt",
11813 if ten_bit { "yuv420p10le" } else { "yuv420p" },
11814 "-strict",
11815 "-1",
11816 "-f",
11817 "yuv4mpegpipe",
11818 "-",
11819 ])
11820 .stdin(Stdio::null())
11821 .stdout(Stdio::piped())
11822 .stderr(Stdio::piped())
11823 .output()
11824 .expect("ffmpeg failed to run");
11825 assert!(
11826 y4m.status.success(),
11827 "{name}: ffmpeg fixture: {}",
11828 String::from_utf8_lossy(&y4m.stderr)
11829 );
11830 let mut args: Vec<String> = [
11831 "--codec=av1",
11832 "--passes=1",
11833 "--end-usage=q",
11834 "--cpu-used=0",
11835 "--lag-in-frames=0",
11836 "--auto-alt-ref=0",
11837 "--kf-max-dist=1000",
11838 "--error-resilient=1",
11839 "--enable-flip-idtx=1",
11840 "--reduced-tx-type-set=0",
11841 "--min-partition-size=8",
11842 "--max-partition-size=16",
11843 // Motion tools this decoder refuses by name, kept off so a
11844 // refusal here can only be about the coefficient path.
11845 "--enable-global-motion=0",
11846 "--enable-warped-motion=0",
11847 "--enable-obmc=0",
11848 "--enable-rect-partitions=0",
11849 "--enable-ab-partitions=0",
11850 "--enable-1to4-partitions=0",
11851 "--enable-filter-intra=0",
11852 "--enable-smooth-intra=0",
11853 "--enable-paeth-intra=0",
11854 "--enable-directional-intra=0",
11855 "--enable-angle-delta=0",
11856 "--enable-tx-size-search=0",
11857 "--enable-cdef=0",
11858 "--enable-restoration=0",
11859 "--loopfilter-control=0",
11860 "--enable-palette=0",
11861 "--enable-intrabc=0",
11862 "--enable-cfl-intra=0",
11863 "--enable-ref-frame-mvs=0",
11864 "--obu",
11865 "-o",
11866 "-",
11867 "-",
11868 ]
11869 .iter()
11870 .map(|s| (*s).to_string())
11871 .collect();
11872 args.insert(1, format!("--cq-level={cq}"));
11873 if ten_bit {
11874 args.insert(1, "--input-bit-depth=10".to_string());
11875 args.insert(1, "--bit-depth=10".to_string());
11876 }
11877 let mut child = Command::new(aomenc_path())
11878 .args(&args)
11879 .stdin(Stdio::piped())
11880 .stdout(Stdio::piped())
11881 .stderr(Stdio::piped())
11882 .spawn()
11883 .expect("aomenc failed to start");
11884 child
11885 .stdin
11886 .take()
11887 .expect("aomenc stdin")
11888 .write_all(&y4m.stdout)
11889 .expect("writing y4m to aomenc");
11890 let out = child.wait_with_output().expect("aomenc failed to run");
11891 assert!(
11892 out.status.success(),
11893 "{name}: aomenc refused the fixture: {}",
11894 String::from_utf8_lossy(&out.stderr)
11895 );
11896 let stream = out.stdout;
11897 let before = decode::chroma_eob_class1_hits();
11898 let frames = match decode_stream(&stream) {
11899 Ok(frames) => frames,
11900 // A named refusal ("unsupported: ...") is another lane's arm
11901 // and moves this attempt on; anything else is a real decode
11902 // failure and fails the gate on the spot.
11903 Err(e) if e.to_string().contains("unsupported") => {
11904 refusals.push(format!("cq={cq} period={period}: {e}"));
11905 continue;
11906 }
11907 Err(e) => {
11908 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
11909 let _ = std::fs::write(&pin, &stream);
11910 panic!(
11911 "{name}: decode_stream failed on a real aomenc stream (cq={cq} period={period}): {e} (pinned at {})",
11912 pin.display()
11913 );
11914 }
11915 };
11916 if decode::chroma_eob_class1_hits() == before {
11917 refusals.push(format!(
11918 "cq={cq} period={period}: decoded, but no chroma block read a class-1 eob_pt row"
11919 ));
11920 continue;
11921 }
11922 let ffmpeg_frames = if ten_bit {
11923 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
11924 } else {
11925 ffmpeg_decode_sequence(&stream, width, height, frame_count)
11926 };
11927 assert_eq!(frames.len(), frame_count, "{name}: frame count");
11928 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11929 if got.y != want.y || got.u != want.u || got.v != want.v {
11930 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
11931 let _ = std::fs::write(&pin, &stream);
11932 panic!(
11933 "{name}: frame {i} mismatch vs ffmpeg (cq={cq} period={period}) -- stream pinned at {}",
11934 pin.display()
11935 );
11936 }
11937 }
11938 return;
11939 }
11940 panic!("{name}: no attempt fired a class-1 chroma eob: {refusals:?}");
11941 }
11942
11943 #[test]
11944 fn a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
11945 chroma_class1_eob_gate(
11946 "a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
11947 false,
11948 );
11949 }
11950
11951 #[test]
11952 fn a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
11953 chroma_class1_eob_gate(
11954 "a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
11955 true,
11956 );
11957 }
11958
11959 /// lane-inter4 r1: the SUPERBLOCK-level inter `PARTITION_HORZ`/
11960 /// `PARTITION_VERT` pair -- two 64x32 / 32x64 inter strips, the arm the
11961 /// inter tile path refused outright before this lane ("an inter SB-level
11962 /// partition type other than NONE or SPLIT"). `--min-partition-size=32`
11963 /// keeps every 32x32-level rect shape (already coded, and residual-capable
11964 /// only when skip) out of the picture so the counters can only be earned
11965 /// at the superblock level; the noiseless split-motion source (one half
11966 /// translating, the other static, flat inside each half) is what makes
11967 /// aomenc's RD pick a superblock HORZ/VERT whose strips are `skip` --
11968 /// the ONLY inter rect shape this decoder can complete, since rectangular
11969 /// inter residual coding is not ported (see `reject_residual`).
11970 ///
11971 /// Every decoded frame is compared to ffmpeg (Y, U and V); an attempt
11972 /// that refuses by name is counted, never turned into a SKIP; and an
11973 /// attempt that decoded without firing the arm is counted separately and
11974 /// still required to be pixel-exact (class gate-skips-on-its-own-failure).
11975 #[test]
11976 fn a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact() {
11977 const NAME: &str = "a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact";
11978 let _gate_lock = lock_gate_counters();
11979 if !have_ffmpeg() {
11980 eprintln!("SKIP {NAME}: no ffmpeg");
11981 return;
11982 }
11983 if !have_aomenc() {
11984 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11985 return;
11986 }
11987 let (width, height, frame_count) = (192usize, 128usize, 6usize);
11988 // lane-inter4 r1: 8-bit ONLY, and the reason is the lane's own open
11989 // residue, not a tolerance: across all 16 attempts x both depths, every
11990 // 10-bit attempt that reached a superblock-level rect strip found it
11991 // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B)
11992 // strip needs rectangular residual coding". The 10-bit twin below is
11993 // `#[ignore]`d with that exact reason rather than deleted or weakened.
11994 // lane-r14 r2 re-measured the 8-bit-only note above: the residual
11995 // refusal it names is GONE (this round codes a 64-px transform axis as
11996 // its truncated low-32 corner), and a 10-bit sweep of this exact
11997 // recipe now reaches the arm -- 2 pixel-exact attempts, 2 64x32 and 2
11998 // 32x64 strips, 2 of them carrying a coded 64-axis residual.
11999 // lane-sbrect10 r1 closed the newly exposed 10-bit defect r14 r2
12000 // parked this arm on (10-bit attempt 14, cq 61, horizontal split,
12001 // motion step 12 -- it mismatched ffmpeg while decoding ZERO rect
12002 // strips): a 64x64 INTRA block inside an inter frame read `uv_mode`
12003 // off the 14-symbol CFL-allowed alphabet, which libaom's
12004 // `is_cfl_allowed` caps at 32x32 -- same DC_PRED value, wrong
12005 // interval narrowing, tile desynced from that block on. Both depths
12006 // run now.
12007 for bit_depth in [8u32, 10u32] {
12008 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
12009 (0u32, 0u32, 0u32, 0u32);
12010 let (mut horz_proved, mut vert_proved) = (0usize, 0usize);
12011 let mut rect64_tus = 0usize;
12012 for attempt in 0..16u32 {
12013 // Two orientations (the transposed pair a one-sided gate could
12014 // never separate) x four quantisers x two motion steps: which
12015 // superblock the RD hands a skip-able rect strip moves with
12016 // the quantiser, and the 10-bit arm needs a different corner
12017 // of the grid from the 8-bit one.
12018 let vertical_split = attempt % 2 == 1;
12019 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
12020 let sp = 8 + (attempt / 8) * 4;
12021 let geq = if vertical_split {
12022 format!("if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), 200)")
12023 } else {
12024 format!("if(lt(X,64), 40+mod(floor((Y+N*{sp})/32)*90,200), 200)")
12025 };
12026 let duration = frame_count as f64 / 25.0;
12027 let source = format!(
12028 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
12029 geq=lum='{geq}',format=yuv420p"
12030 );
12031 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12032 let y4m = Command::new("ffmpeg")
12033 .args([
12034 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
12035 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
12036 ])
12037 .stdin(Stdio::null())
12038 .stdout(Stdio::piped())
12039 .stderr(Stdio::piped())
12040 .output()
12041 .expect("ffmpeg failed to run");
12042 assert!(
12043 y4m.status.success(),
12044 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
12045 String::from_utf8_lossy(&y4m.stderr)
12046 );
12047 let cq_arg = format!("--cq-level={cq}");
12048 let depth_arg = format!("--bit-depth={bit_depth}");
12049 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
12050 let args: Vec<&str> = vec![
12051 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
12052 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
12053 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
12054 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
12055 "--enable-tx-size-search=0", "--lag-in-frames=0",
12056 // Per-arm overrides go LAST: aomenc keeps the last
12057 // occurrence of a repeated --enable-* flag.
12058 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
12059 "--enable-1to4-partitions=1", "--min-partition-size=32",
12060 "--max-partition-size=64",
12061 "--obu", "-o", "-", "-",
12062 ];
12063 let mut child = Command::new(aomenc_path())
12064 .args(&args)
12065 .stdin(Stdio::piped())
12066 .stdout(Stdio::piped())
12067 .stderr(Stdio::piped())
12068 .spawn()
12069 .expect("aomenc failed to start");
12070 child
12071 .stdin
12072 .take()
12073 .expect("aomenc stdin")
12074 .write_all(&y4m.stdout)
12075 .expect("writing y4m to aomenc");
12076 let out = child.wait_with_output().expect("aomenc failed to run");
12077 assert!(
12078 out.status.success(),
12079 "aomenc refused the fixture: {}",
12080 String::from_utf8_lossy(&out.stderr)
12081 );
12082 let stream = out.stdout;
12083 let before = crate::stream::inter_rect_counters();
12084 let rect64_before = crate::stream::rect64_inter_tu_hits();
12085 let frames = match decode_stream(&stream) {
12086 Err(e) => {
12087 let msg = e.to_string();
12088 assert!(
12089 msg.contains("unsupported"),
12090 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
12091 attempt {attempt}): {msg}"
12092 );
12093 named_refusals += 1;
12094 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
12095 continue;
12096 }
12097 Ok(frames) => frames,
12098 };
12099 let after = crate::stream::inter_rect_counters();
12100 let (horz, vert) = (after.2 - before.2, after.3 - before.3);
12101 let rect64 = crate::stream::rect64_inter_tu_hits() - rect64_before;
12102 let ffmpeg_frames = if bit_depth == 10 {
12103 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12104 } else {
12105 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12106 };
12107 assert_eq!(frames.len(), frame_count);
12108 let mismatched = frames
12109 .iter()
12110 .zip(&ffmpeg_frames)
12111 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
12112 if horz + vert == 0 {
12113 out_of_scope += 1;
12114 if mismatched {
12115 oos_mismatch += 1;
12116 eprintln!(
12117 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
12118 superblock-level inter rect strips -- another shape's defect"
12119 );
12120 }
12121 continue;
12122 }
12123 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12124 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12125 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12126 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12127 }
12128 horz_proved += horz;
12129 vert_proved += vert;
12130 rect64_tus += rect64;
12131 matched += 1;
12132 }
12133 eprintln!(
12134 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
12135 attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \
12136 64-axis residual TUs={rect64_tus}, \
12137 {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)"
12138 );
12139 assert_eq!(
12140 oos_mismatch, 0,
12141 "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \
12142 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
12143 );
12144 // lane-r14 r2: the residual half of the arm -- a strip that is not
12145 // `skip` and codes a real 64-axis transform unit. Without this the
12146 // gate proves only the partition symbol.
12147 assert!(
12148 rect64_tus > 0,
12149 "{NAME} ({bit_depth}-bit): no superblock-level rect strip carried a coded \
12150 64-axis residual transform unit inside a pixel-exact attempt \
12151 (horz={horz_proved}, vert={vert_proved}) -- the residual arm proved nothing"
12152 );
12153 assert!(
12154 horz_proved + vert_proved > 0,
12155 "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \
12156 inside a pixel-exact attempt (horz={horz_proved}, vert={vert_proved}, \
12157 {named_refusals} refusals, {out_of_scope} out of scope) -- gate proved nothing"
12158 );
12159 }
12160 }
12161
12162 /// lane-r14 r3: a 1:4 inter strip with a 64-px axis (64x16 / 16x64) whose
12163 /// transform SPLITS -- the arm r2 left refused by name ("a split transform
12164 /// on a 1:4 inter strip with a 64-px axis"). libaom's
12165 /// `sub_tx_size_map[TX_64X16] == TX_32X16` (and `[TX_16X64] == TX_16X32`)
12166 /// keeps the sub-transform RECTANGULAR, so the var-tx tree's leaves are
12167 /// 32x16/16x32 units read through [`TxbSet::LumaRect32x16Inter`], each with
12168 /// its own `get_txb_ctx_general` neighbour context (the unit is smaller
12169 /// than its block, so `txb_skip_ctx` is NOT the lone-TU 0).
12170 ///
12171 /// `--enable-1to4-partitions=1 --min-partition-size=16
12172 /// --max-partition-size=64 --enable-tx64=1` (each spelled once, last
12173 /// occurrence wins) is what lets aomenc pick a superblock-level HORZ_4 /
12174 /// VERT_4; the textured translating source is what keeps the strips
12175 /// non-skip so the residual is actually coded. 8-bit AND 10-bit, every
12176 /// decoded frame compared to ffmpeg on Y/U/V, refusals counted (never
12177 /// SKIPped), attempts that carried no rectangular var-tx leaf counted
12178 /// separately and still required pixel-exact.
12179 #[test]
12180 fn real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal() {
12181 const NAME: &str =
12182 "real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal";
12183 let _gate_lock = lock_gate_counters();
12184 if !have_ffmpeg() {
12185 eprintln!("SKIP {NAME}: no ffmpeg");
12186 return;
12187 }
12188 if !have_aomenc() {
12189 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12190 return;
12191 }
12192 let frame_count = 6usize;
12193 for bit_depth in [8u32, 10u32] {
12194 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
12195 (0u32, 0u32, 0u32, 0u32);
12196 let (mut leaf_32x16, mut leaf_16x32) = (0usize, 0usize);
12197 // Leaves decoded on ANY attempt, including one whose stream hits a
12198 // later named refusal: the firing half of this gate, kept apart
12199 // from `leaf_32x16`/`leaf_16x32` (pixel-compared attempts only) so
12200 // a refused stream is never counted as a pixel proof
12201 // (class counter-from-refused-stream).
12202 let (mut fired_32x16, mut fired_16x32) = (0usize, 0usize);
12203 // lane-gaterecipe r1: the firing arms (16-17) are 8-BIT ONLY, and
12204 // this is measured, not a convenience. Their 10-bit twin fires the
12205 // leaves too (32x16=0 16x32=46 on attempt 16) and then MISMATCHES
12206 // ffmpeg at decode-order frame 2 of attempt 17 -- an open DECODE
12207 // defect handed off in lanes/gaterecipe-r1.report.md, never
12208 // silenced inside this loop.
12209 let attempts = if bit_depth == 8 { 18u32 } else { 16u32 };
12210 for attempt in 0..attempts {
12211 // Two orientations (the transposed pair a one-sided gate could
12212 // never separate) x four quantisers x two motion steps.
12213 // lane-r14 r4 recipe hunt (~70 aomenc runs on the merged
12214 // tree: testsrc2 / life / mandelbrot / banded motion, 64x64 up
12215 // to 384x256, cq 20..58): attempts 16-17 carry the only recipe
12216 // found that makes aomenc code a 64-axis 1:4 strip whose
12217 // transform SPLITS -- 384x256, per-16-column band motion,
12218 // cq 32 (16x32 leaves) and cq 38 (32x16 leaves).
12219 let firing = attempt >= 16;
12220 let (width, height) =
12221 if firing { (384usize, 256usize) } else { (192usize, 128usize) };
12222 let vertical = attempt % 2 == 1;
12223 // lane-vartxsplit r2, MEASURED against the oracle
12224 // (`EC_VARTX` histogram, ~40 aomenc runs): at cq 10 this
12225 // source splits NO rectangular transform at all -- aomdec
12226 // reads only TX_8X8/TX_16X16/TX_8X16/TX_16X8 split symbols,
12227 // so the leaves gaterecipe r1 counted here came out of a
12228 // stream our decoder was already desynced on (class
12229 // counter-from-refused-stream). cq 44 and 46 are the two
12230 // quantisers of that sweep whose stream really carries
12231 // `TX_32X8`/`TX_8X32` splits (16x8 and 8x16 rectangular
12232 // var-tx leaves) AND decodes pixel-exact on all six frames.
12233 let cq = if firing {
12234 if attempt == 16 { 44 } else { 46 }
12235 } else {
12236 [30, 36, 44, 52][(attempt / 2 % 4) as usize]
12237 };
12238 let sp = 3 + (attempt / 8) * 3;
12239 // 16-pixel bands, each band translating at its OWN speed
12240 // across the other axis: that is what makes aomenc's RD split
12241 // a 64x64 superblock into four 1:4 strips (`PARTITION_HORZ_4`
12242 // / `VERT_4`) with distinct motion vectors, and the texture
12243 // inside a band is what keeps the strip non-skip and its
12244 // transform split.
12245 let geq = if firing && !vertical {
12246 // lane-gaterecipe r1, MEASURED: the banded translating
12247 // source this arm used until now splits NO transform at
12248 // all -- an aomdec EC_TRACE/EC_TRACE_COEFF histogram of its
12249 // stream reads zero 1:4 partitions and zero rectangular
12250 // sub-transforms, so the leaves the old assert counted came
12251 // out of a stream that stopped at a refusal (class
12252 // counter-from-refused-stream). What DOES split a
12253 // rectangular transform is a high-frequency product texture
12254 // at a fine quantiser with `--min-partition-size=8`: part
12255 // of the block predicts well and part does not, which is
12256 // the RD case for `txfm_partition`.
12257 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
12258 } else if firing {
12259 // lane-vartxsplit r2: BOTH leaf orientations come out of
12260 // this one source (three 16x8 leaves and one 8x16 on
12261 // attempt 16), so the firing pair is the same texture at
12262 // two quantisers. Its transposed twin was measured over
12263 // cq 40..56 and splits no rectangular transform at all;
12264 // at cq 56 it also mismatches ffmpeg from decode-order
12265 // frame 2 with ZERO rect var-tx leaves in it -- an open
12266 // reconstruction defect (8-pixel-wide luma column, see
12267 // lanes/vartxsplit-r2.report.md), not something to hide
12268 // inside this gate's attempt list.
12269 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
12270 } else if vertical {
12271 format!(
12272 "128+60*sin((Y+N*({sp}+9*mod(floor(X/16),2)))/7)+25*sin(X/11)"
12273 )
12274 } else {
12275 format!(
12276 "128+60*sin((X+N*({sp}+9*mod(floor(Y/16),2)))/7)+25*sin(Y/11)"
12277 )
12278 };
12279 let duration = frame_count as f64 / 25.0;
12280 let source = format!(
12281 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
12282 geq=lum='{geq}',format=yuv420p"
12283 );
12284 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12285 let y4m = Command::new("ffmpeg")
12286 .args([
12287 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
12288 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
12289 ])
12290 .stdin(Stdio::null())
12291 .stdout(Stdio::piped())
12292 .stderr(Stdio::piped())
12293 .output()
12294 .expect("ffmpeg failed to run");
12295 assert!(
12296 y4m.status.success(),
12297 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
12298 String::from_utf8_lossy(&y4m.stderr)
12299 );
12300 let cq_arg = format!("--cq-level={cq}");
12301 let depth_arg = format!("--bit-depth={bit_depth}");
12302 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
12303 // A rectangular var-tx LEAF needs a block whose max rectangular
12304 // transform can split: `--min-partition-size=8` is what lets
12305 // aomenc's RD reach one (measured); at 16 it never did.
12306 let min_part =
12307 if firing { "--min-partition-size=8" } else { "--min-partition-size=16" };
12308 let args: Vec<&str> = vec![
12309 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
12310 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
12311 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
12312 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
12313 "--lag-in-frames=0",
12314 // Per-arm overrides go LAST: aomenc keeps the last
12315 // occurrence of a repeated --enable-* flag.
12316 "--enable-tx64=1", "--enable-rect-partitions=1",
12317 "--enable-ab-partitions=0", "--enable-1to4-partitions=1",
12318 "--enable-dual-filter=0", "--enable-obmc=0",
12319 "--enable-tx-size-search=1",
12320 min_part, "--max-partition-size=64",
12321 "--obu", "-o", "-", "-",
12322 ];
12323 let mut child = Command::new(aomenc_path())
12324 .args(&args)
12325 .stdin(Stdio::piped())
12326 .stdout(Stdio::piped())
12327 .stderr(Stdio::piped())
12328 .spawn()
12329 .expect("aomenc failed to start");
12330 // lane-gaterecipe r1: feed stdin from a THREAD. A
12331 // single-threaded `write_all` then `wait_with_output` deadlocks
12332 // the moment aomenc's stdout pipe fills before it has consumed
12333 // the whole y4m -- exactly what the fine-quantiser firing arm
12334 // does (one 384x256 cq-10 encode hung for 40 minutes).
12335 let mut aom_stdin = child.stdin.take().expect("aomenc stdin");
12336 let y4m_bytes = y4m.stdout;
12337 let feeder = std::thread::Builder::new()
12338 .name("ec-av1-aomenc-in".into())
12339 .spawn(move || {
12340 aom_stdin.write_all(&y4m_bytes).expect("writing y4m to aomenc");
12341 })
12342 .expect("spawning the aomenc stdin feeder");
12343 let out = child.wait_with_output().expect("aomenc failed to run");
12344 feeder.join().expect("y4m feeder thread");
12345 assert!(
12346 out.status.success(),
12347 "aomenc refused the fixture: {}",
12348 String::from_utf8_lossy(&out.stderr)
12349 );
12350 let stream = out.stdout;
12351 let before = crate::stream::vartx_rect_leaf_hits();
12352 let frames = match decode_stream(&stream) {
12353 Err(e) => {
12354 let msg = e.to_string();
12355 assert!(
12356 msg.contains("unsupported"),
12357 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
12358 attempt {attempt}): {msg}"
12359 );
12360 let after = crate::stream::vartx_rect_leaf_hits();
12361 fired_32x16 += after[0] - before[0];
12362 fired_16x32 += after[1] - before[1];
12363 named_refusals += 1;
12364 eprintln!(
12365 "{bit_depth}-bit attempt {attempt} refusal (rect var-tx leaves \
12366 decoded before it: 32x16={}, 16x32={}): {msg}",
12367 after[0] - before[0],
12368 after[1] - before[1]
12369 );
12370 continue;
12371 }
12372 Ok(frames) => frames,
12373 };
12374 let after = crate::stream::vartx_rect_leaf_hits();
12375 let (h32, v32) = (after[0] - before[0], after[1] - before[1]);
12376 fired_32x16 += h32;
12377 fired_16x32 += v32;
12378 let ffmpeg_frames = if bit_depth == 10 {
12379 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12380 } else {
12381 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12382 };
12383 assert_eq!(frames.len(), frame_count);
12384 let mismatched = frames
12385 .iter()
12386 .zip(&ffmpeg_frames)
12387 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
12388 if h32 + v32 == 0 {
12389 // Counted per ATTEMPT, on a decoded+compared attempt only
12390 // (class counter-from-refused-stream).
12391 out_of_scope += 1;
12392 if mismatched {
12393 oos_mismatch += 1;
12394 eprintln!(
12395 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
12396 rectangular var-tx leaves -- another shape's defect"
12397 );
12398 }
12399 continue;
12400 }
12401 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12402 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12403 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12404 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12405 }
12406 leaf_32x16 += h32;
12407 leaf_16x32 += v32;
12408 compared += 1;
12409 }
12410 eprintln!(
12411 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
12412 pixel-exact attempts carrying the arm, pixel-compared rect var-tx leaves \
12413 32x16={leaf_32x16} 16x32={leaf_16x32}, leaves decoded anywhere in the sweep \
12414 32x16={fired_32x16} 16x32={fired_16x32}, {out_of_scope} attempts carried none \
12415 ({oos_mismatch} of them mismatched)"
12416 );
12417 assert_eq!(
12418 oos_mismatch, 0,
12419 "{NAME}: {oos_mismatch} attempt(s) with no rectangular var-tx leaf decoded \
12420 but mismatched ffmpeg -- a defect of another shape, not a pass"
12421 );
12422 assert!(
12423 compared + out_of_scope > 0,
12424 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
12425 );
12426 // The firing half. lane-vartxsplit r2 re-measured it against
12427 // the oracle: attempts 16/17 (384x256 product texture, cq 44/46,
12428 // `--min-partition-size=8 --enable-tx-size-search=1`) are the only
12429 // recipes of a ~40-run sweep whose stream carries `TX_32X8` /
12430 // `TX_8X32` split symbols, i.e. RECTANGULAR var-tx leaves (16x8
12431 // and 8x16, both orientations out of the same stream). They now
12432 // decode PIXEL-EXACT on all six frames, so the assert is on the
12433 // pixel-compared tally, not on the "decoded anywhere" one --
12434 // `fired_*` stays only to separate a refused stream's leaves from
12435 // a proved one (class counter-from-refused-stream). At 10 bits
12436 // the same sweep either fires nothing or mismatches on a
12437 // reconstruction defect of another shape (report), so the firing
12438 // assert stays 8-bit -- and it is a hard assert, never a print.
12439 if bit_depth == 8 {
12440 assert!(
12441 leaf_32x16 > 0 && leaf_16x32 > 0,
12442 "{NAME}: the rectangular var-tx leaf arm never fired on a pixel-exact \
12443 attempt (pixel-compared 32x16={leaf_32x16}, 16x32={leaf_16x32}, decoded \
12444 anywhere 32x16={fired_32x16} 16x32={fired_16x32}, {named_refusals} \
12445 refusals, {compared} compared) -- the rectangular sub-transform path is \
12446 unproved by this gate"
12447 );
12448 }
12449 }
12450 }
12451
12452 /// lane-rectres r1: a 32x32-level 1:4 INTER strip (32x8 / 8x32) that codes
12453 /// a REAL rectangular residual. THIS is the shape both 10-bit 3840x1608
12454 /// film cuts and every measured 1080p offset stopped on -- six of six
12455 /// `decode_probe` runs refused at "a non-skip rectangular (HORZ/VERT/
12456 /// HORZ_B) strip needs rectangular residual coding" with `w=32 h=8` or
12457 /// `w=8 h=32`, nothing else.
12458 ///
12459 /// `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256 of its
12460 /// positions ([`TxbSet::LumaRect32x8Inter`]: `get_txsize_entropy_ctx` =
12461 /// TX_16X16 so the coefficient tables are the luma-16 ones,
12462 /// `txsize_log2_minus4` = 4 so `eob_pt` is the 256-position alphabet), and
12463 /// unlike the INTRA twin it DOES code a `tx_type`:
12464 /// `av1_get_ext_tx_set_type` at `tx_size_sqr_up == TX_32X32` is
12465 /// `EXT_TX_SET_DCT_IDTX` for inter with or without `reduced_tx_set`, read
12466 /// at the `txsize_sqr_map[TX_32X8] == TX_8X8` CDF row (class
12467 /// table-indexed-by-raw-size: the coefficient tables follow the ADJUSTED
12468 /// size, the `tx_type` row the SQUARE one -- they disagree here).
12469 /// Its chroma pair is one 16x4 / 4x16 unit (`ss_size_lookup[BLOCK_32X8]`
12470 /// = BLOCK_16X4, `Chroma8`'s tables, 64-position `eob_pt`), and a split
12471 /// transform gives 16x8 / 8x16 leaves (`sub_tx_size_map[TX_32X8] ==
12472 /// TX_16X8`) the rect var-tx path already reads.
12473 ///
12474 /// `--enable-1to4-partitions=1 --min-partition-size=8
12475 /// --max-partition-size=32 --enable-tx-size-search=1` (each spelled once,
12476 /// last occurrence wins -- aomenc keeps the LAST `--enable-*`) is what
12477 /// lets aomenc pick a 32x32-level HORZ_4 / VERT_4; the 8-pixel banded
12478 /// translating source is what makes those strips the RD winner and keeps
12479 /// them non-skip so the residual is really coded. Both orientations, 8-bit
12480 /// AND 10-bit, every decode-order frame compared to ffmpeg on Y/U/V,
12481 /// refusals counted (never SKIPped), attempts that carried no 32x8/8x32
12482 /// residual unit counted separately and still required pixel-exact.
12483 #[test]
12484 fn a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual() {
12485 const NAME: &str =
12486 "a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual";
12487 let _gate_lock = lock_gate_counters();
12488 if !have_ffmpeg() {
12489 eprintln!("SKIP {NAME}: no ffmpeg");
12490 return;
12491 }
12492 if !have_aomenc() {
12493 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12494 return;
12495 }
12496 let frame_count = 6usize;
12497 let (mut proved_32x8, mut proved_8x32) = (0usize, 0usize);
12498 let (mut fired_32x8, mut fired_8x32) = (0usize, 0usize);
12499 for bit_depth in [8u32, 10u32] {
12500 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
12501 (0u32, 0u32, 0u32, 0u32);
12502 for attempt in 0..16u32 {
12503 // Two orientations (the transposed pair a one-sided gate could
12504 // never separate) x four quantisers x two motion steps.
12505 let vertical = attempt % 2 == 1;
12506 let (width, height) = (192usize, 128usize);
12507 let cq = [48, 52, 56, 60][(attempt / 2 % 4) as usize];
12508 let sp = 3 + (attempt / 8) * 4;
12509 // 32-pixel bands, each translating at its OWN speed across the
12510 // other axis: that is what makes aomenc's RD split a 32x32
12511 // block into four 32x8 (or 8x32) strips with distinct motion
12512 // vectors, and the texture inside a band is what keeps a strip
12513 // non-skip. MEASURED (72-run recipe sweep, 192x128..256x192,
12514 // cq 24..60, bands 8/16/32/64): only 32-pixel bands at cq >= 48
12515 // make aomenc code a NON-SKIP one -- attempt 0 (cq 48,
12516 // horizontal source) codes an 8x32 residual unit, attempt 7
12517 // (cq 60, the transposed source) five 32x8 ones. Narrower
12518 // bands give the same strips with `skip` set, which proves the
12519 // partition symbol and nothing about the residual.
12520 let geq = if vertical {
12521 format!("128+62*sin((Y+N*({sp}+7*mod(floor(X/32),4)))/6)+28*sin(X/9)")
12522 } else {
12523 format!("128+62*sin((X+N*({sp}+7*mod(floor(Y/32),4)))/6)+28*sin(Y/9)")
12524 };
12525 let duration = frame_count as f64 / 25.0;
12526 let source = format!(
12527 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
12528 geq=lum='{geq}',format=yuv420p"
12529 );
12530 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12531 let y4m = Command::new("ffmpeg")
12532 .args([
12533 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
12534 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
12535 ])
12536 .stdin(Stdio::null())
12537 .stdout(Stdio::piped())
12538 .stderr(Stdio::piped())
12539 .output()
12540 .expect("ffmpeg failed to run");
12541 assert!(
12542 y4m.status.success(),
12543 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
12544 String::from_utf8_lossy(&y4m.stderr)
12545 );
12546 let cq_arg = format!("--cq-level={cq}");
12547 let depth_arg = format!("--bit-depth={bit_depth}");
12548 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
12549 let args: Vec<&str> = vec![
12550 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
12551 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
12552 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
12553 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
12554 "--lag-in-frames=0",
12555 // Per-arm overrides go LAST: aomenc keeps the last
12556 // occurrence of a repeated --enable-* flag.
12557 "--enable-tx64=0", "--enable-rect-partitions=1",
12558 "--enable-ab-partitions=0", "--enable-1to4-partitions=1",
12559 "--enable-tx-size-search=1",
12560 "--enable-dual-filter=0", "--enable-obmc=0",
12561 // aomenc's min-partition-size bounds the SMALLER side of a
12562 // 1:4 strip, so 32x8 needs 8 (memory
12563 // aomenc-min-partition-bounds-smaller-side).
12564 "--min-partition-size=8", "--max-partition-size=32",
12565 "--obu", "-o", "-", "-",
12566 ];
12567 let mut child = Command::new(aomenc_path())
12568 .args(&args)
12569 .stdin(Stdio::piped())
12570 .stdout(Stdio::piped())
12571 .stderr(Stdio::piped())
12572 .spawn()
12573 .expect("aomenc failed to start");
12574 child
12575 .stdin
12576 .take()
12577 .expect("aomenc stdin")
12578 .write_all(&y4m.stdout)
12579 .expect("writing y4m to aomenc");
12580 let out = child.wait_with_output().expect("aomenc failed to run");
12581 assert!(
12582 out.status.success(),
12583 "aomenc refused the fixture: {}",
12584 String::from_utf8_lossy(&out.stderr)
12585 );
12586 let stream = out.stdout;
12587 let before = crate::stream::rect32x8_inter_tu_hits();
12588 let frames = match decode_stream(&stream) {
12589 Err(e) => {
12590 let msg = e.to_string();
12591 assert!(
12592 msg.contains("unsupported"),
12593 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
12594 attempt {attempt}): {msg}"
12595 );
12596 let after = crate::stream::rect32x8_inter_tu_hits();
12597 // Firing counted on a refused stream is kept apart from
12598 // the pixel-proved tally (class
12599 // counter-from-refused-stream).
12600 fired_32x8 += after[0] - before[0];
12601 fired_8x32 += after[1] - before[1];
12602 named_refusals += 1;
12603 eprintln!(
12604 "{NAME} {bit_depth}-bit attempt {attempt} refusal (32x8 residual \
12605 units decoded before it: {}, 8x32: {}): {msg}",
12606 after[0] - before[0],
12607 after[1] - before[1]
12608 );
12609 continue;
12610 }
12611 Ok(frames) => frames,
12612 };
12613 let after = crate::stream::rect32x8_inter_tu_hits();
12614 let (h, v) = (after[0] - before[0], after[1] - before[1]);
12615 fired_32x8 += h;
12616 fired_8x32 += v;
12617 let ffmpeg_frames = if bit_depth == 10 {
12618 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12619 } else {
12620 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12621 };
12622 assert_eq!(frames.len(), frame_count);
12623 let mismatched = frames
12624 .iter()
12625 .zip(&ffmpeg_frames)
12626 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
12627 if h + v == 0 {
12628 out_of_scope += 1;
12629 if mismatched {
12630 oos_mismatch += 1;
12631 eprintln!(
12632 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
12633 32x8/8x32 inter residual units -- another shape's defect"
12634 );
12635 }
12636 continue;
12637 }
12638 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12639 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12640 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12641 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
12642 }
12643 proved_32x8 += h;
12644 proved_8x32 += v;
12645 compared += 1;
12646 }
12647 eprintln!(
12648 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
12649 pixel-exact attempts carrying the arm, {out_of_scope} attempts carried none \
12650 ({oos_mismatch} of them mismatched)"
12651 );
12652 assert_eq!(
12653 oos_mismatch, 0,
12654 "{NAME}: {oos_mismatch} attempt(s) with no 32x8/8x32 inter residual unit \
12655 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
12656 );
12657 assert!(
12658 compared + out_of_scope > 0,
12659 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
12660 );
12661 }
12662 eprintln!(
12663 "{NAME}: pixel-compared 32x32-level 1:4 inter residual units 32x8={proved_32x8} \
12664 8x32={proved_8x32} (decoded anywhere in the sweep 32x8={fired_32x8} \
12665 8x32={fired_8x32})"
12666 );
12667 // The firing half, one assert per lifted shape. Both orientations must
12668 // be PIXEL-PROVED: a transposed table passes one and fails the other
12669 // (class reference-layout-not-spec).
12670 assert!(
12671 proved_32x8 > 0,
12672 "{NAME}: no 32x8 inter residual transform unit was decoded inside a pixel-exact \
12673 attempt (decoded anywhere: {fired_32x8}) -- the lift is unproved"
12674 );
12675 assert!(
12676 proved_8x32 > 0,
12677 "{NAME}: no 8x32 inter residual transform unit was decoded inside a pixel-exact \
12678 attempt (decoded anywhere: {fired_8x32}) -- the lift is unproved"
12679 );
12680 }
12681
12682 /// lane-sbrect10 r1: a 64x64 INTRA block inside an INTER frame, whose
12683 /// `uv_mode` alphabet libaom's `is_cfl_allowed` (`blockd.h`: `wide <= 32
12684 /// && high <= 32`) narrows to the 13-symbol NO-CFL table. Reading the
12685 /// 14-symbol CFL one produced the same `DC_PRED` value with the wrong
12686 /// interval narrowing, so the tile desynced from that block on and the
12687 /// frame decoded silently wrong (class `wrong-alphabet-same-value`; found
12688 /// as the "another shape" mismatch the superblock rect gate above had to
12689 /// park its 10-bit arm on).
12690 ///
12691 /// The counter `nocfl_uv_mode_hits` proves the shape fired in EVERY
12692 /// compared attempt, and every decode-order frame is compared against
12693 /// ffmpeg -- an attempt that mismatches fails, it never SKIPs.
12694 ///
12695 /// lane-sbrect10 r2: with the half-random source below this gate also
12696 /// covers a SECOND defect it exposed at 10-bit cq 58/61 -- the compound
12697 /// MV stack's extension pass zero-filled the `comp_list` tail slots
12698 /// libaom fills with each side's GLOBAL MOTION vector
12699 /// (`combine_compound_candidates`, mvref_common.c:723-729). A compound
12700 /// block with no usable neighbour pair (frame top row, intra block to
12701 /// its left, empty temporal field) then took a `(0, 0)` predictor
12702 /// instead of the frame's translation: 32890/39907 wrong luma samples
12703 /// on decode-order frame 2 with the entropy stream still in sync.
12704 #[test]
12705 fn a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet() {
12706 const NAME: &str =
12707 "a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet";
12708 let _gate_lock = lock_gate_counters();
12709 if !have_ffmpeg() {
12710 eprintln!("SKIP {NAME}: no ffmpeg");
12711 return;
12712 }
12713 if !have_aomenc() {
12714 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12715 return;
12716 }
12717 let (width, height, frame_count) = (192usize, 128usize, 6usize);
12718 for bit_depth in [8u32, 10u32] {
12719 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
12720 let mut total_hits = 0usize;
12721 for attempt in 0..16u32 {
12722 // The sibling superblock-rect gate's own grid (its 10-bit
12723 // attempt 14 -- cq 61, horizontal split, motion step 12 -- is
12724 // the stream that exposed the defect); which superblock the RD
12725 // hands an intra 64x64 block moves with the quantiser and the
12726 // depth, so both orientations x four quantisers x two motion
12727 // steps run here too.
12728 let vertical_split = attempt % 2 == 1;
12729 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
12730 let sp = 8 + (attempt / 8) * 4;
12731 // Half ramp, half deterministic pseudo-noise: the flat "200"
12732 // half of r1's source made aomenc code the right-hand
12733 // superblocks skip, so at 8 bit no >32 intra block ever
12734 // appeared (probed cq 45/52/58/61/63 = 0 hits). The textured
12735 // half forces intra above 32x32 in an inter frame at BOTH
12736 // depths, so both arms carry the shape.
12737 let geq = if vertical_split {
12738 format!(
12739 "if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
12740 )
12741 } else {
12742 format!(
12743 "if(lt(X,128), 40+mod(floor((Y+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
12744 )
12745 };
12746 let duration = frame_count as f64 / 25.0;
12747 let source = format!(
12748 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
12749 geq=lum='{geq}',format=yuv420p"
12750 );
12751 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12752 let y4m = Command::new("ffmpeg")
12753 .args([
12754 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
12755 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
12756 ])
12757 .stdin(Stdio::null())
12758 .stdout(Stdio::piped())
12759 .stderr(Stdio::piped())
12760 .output()
12761 .expect("ffmpeg failed to run");
12762 assert!(
12763 y4m.status.success(),
12764 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
12765 String::from_utf8_lossy(&y4m.stderr)
12766 );
12767 let cq_arg = format!("--cq-level={cq}");
12768 let depth_arg = format!("--bit-depth={bit_depth}");
12769 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
12770 let args: Vec<&str> = vec![
12771 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
12772 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
12773 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
12774 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
12775 "--enable-tx-size-search=0", "--lag-in-frames=0",
12776 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
12777 "--enable-1to4-partitions=1", "--min-partition-size=32",
12778 "--max-partition-size=64",
12779 "--obu", "-o", "-", "-",
12780 ];
12781 let mut child = Command::new(aomenc_path())
12782 .args(&args)
12783 .stdin(Stdio::piped())
12784 .stdout(Stdio::piped())
12785 .stderr(Stdio::piped())
12786 .spawn()
12787 .expect("aomenc failed to start");
12788 child
12789 .stdin
12790 .take()
12791 .expect("aomenc stdin")
12792 .write_all(&y4m.stdout)
12793 .expect("writing y4m to aomenc");
12794 let out = child.wait_with_output().expect("aomenc failed to run");
12795 assert!(
12796 out.status.success(),
12797 "aomenc refused the fixture: {}",
12798 String::from_utf8_lossy(&out.stderr)
12799 );
12800 let stream = out.stdout;
12801 let before = crate::decode::nocfl_uv_mode_hits();
12802 let frames = match decode_stream(&stream) {
12803 Err(e) => {
12804 let msg = e.to_string();
12805 assert!(
12806 msg.contains("unsupported"),
12807 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
12808 attempt {attempt}): {msg}"
12809 );
12810 named_refusals += 1;
12811 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
12812 continue;
12813 }
12814 Ok(frames) => frames,
12815 };
12816 let hits = crate::decode::nocfl_uv_mode_hits() - before;
12817 let ffmpeg_frames = if bit_depth == 10 {
12818 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12819 } else {
12820 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12821 };
12822 assert_eq!(frames.len(), frame_count);
12823 if hits == 0 {
12824 // No 64-axis intra block in this stream: still compared
12825 // (a mismatch here is a defect, never a pass), just not
12826 // proof of this gate's shape.
12827 carried_none += 1;
12828 }
12829 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12830 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
12831 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
12832 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
12833 }
12834 if hits > 0 {
12835 matched += 1;
12836 total_hits += hits;
12837 }
12838 }
12839 eprintln!(
12840 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
12841 attempts carrying a >32 intra block ({total_hits} no-CFL uv_mode reads), \
12842 {carried_none} attempts carried none"
12843 );
12844 assert!(
12845 matched > 0 && total_hits > 0,
12846 "{NAME} ({bit_depth}-bit): no attempt decoded an intra block above 32x32, so the \
12847 no-CFL uv_mode alphabet was never exercised -- gate proved nothing \
12848 ({named_refusals} refusals, {carried_none} attempts carried none)"
12849 );
12850 }
12851 }
12852 /// lane-sqdrift r2: the SQUARE-ONLY twin of the no-CFL `uv_mode` gate
12853 /// above. With `--enable-rect-partitions=0` the encoder codes only
12854 /// `PARTITION_NONE` and `PARTITION_SPLIT`, and on detailed content the RD
12855 /// eventually hands one whole 64x64 superblock of an INTER frame to an
12856 /// INTRA block -- `bsize == sb_size`, the one shape whose `uv_mode` must
12857 /// come off the 13-symbol `uv_mode_no_cfl` alphabet because libaom's
12858 /// `is_cfl_allowed` (`blockd.h`: `wide <= 32 && high <= 32`) excludes it.
12859 ///
12860 /// Before the fix this decoder read the 14-symbol CFL alphabet there: the
12861 /// same `DC_PRED` value, a different interval, and the tile desynced from
12862 /// that block on. r1 measured the damage on the pinned 192x128 stream
12863 /// (sha256 `c6af4fb4...`): decode-order frames 0-3 pre-filter byte-exact,
12864 /// frame 4 luma 3540 samples wrong over exactly the last superblock
12865 /// (x 128..191, y 64..127), then 24k wrong by frame 7 -- and the decoder
12866 /// did not even report a mismatch, it reported an intra-rect-strip refusal
12867 /// read out of the already-desynced stream (class `refusal-from-own-desync`;
12868 /// aomdec's own partition histogram over that stream is rect-free).
12869 /// After the fix the same stream is byte-exact on all 8 frames.
12870 ///
12871 /// Distinct from the sibling gate: rect partitions OFF (so the 64x64 NONE
12872 /// really is a whole superblock), `--min-partition-size=16`, natural
12873 /// mandelbrot detail instead of a synthetic half-noise ramp, and 8 frames
12874 /// of drift so a desync that survives one frame still fails here. Every
12875 /// decode-order frame of every attempt is compared against ffmpeg, so a
12876 /// mismatch of ANY shape fails; the gate never turns one into a SKIP.
12877 #[test]
12878 fn a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact()
12879 {
12880 const NAME: &str = "a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact";
12881 let _gate_lock = lock_gate_counters();
12882 if !have_ffmpeg() {
12883 eprintln!("SKIP {NAME}: no ffmpeg");
12884 return;
12885 }
12886 if !have_aomenc() {
12887 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12888 return;
12889 }
12890 let (width, height, frame_count) = (192usize, 128usize, 8usize);
12891 for bit_depth in [8u32, 10u32] {
12892 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
12893 let mut total_hits = 0usize;
12894 for attempt in 0..4u32 {
12895 // r1's pinned recipe is (start_scale 4.76, cq 55); the other
12896 // three points move the detail level and the quantiser, which
12897 // is what moves WHICH superblock the RD codes intra.
12898 let start_scale = ["4.76", "3.20"][(attempt % 2) as usize];
12899 let cq = [55, 45][(attempt / 2) as usize];
12900 let duration = frame_count as f64 / 25.0;
12901 let source = format!(
12902 "mandelbrot=size={width}x{height}:start_scale={start_scale}:\
12903 end_scale=0.004:end_pts=8:rate=25"
12904 );
12905 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12906 let y4m = Command::new("ffmpeg")
12907 .args([
12908 "-v", "error", "-f", "lavfi", "-i", &source, "-vf", "hue=s=0",
12909 "-t", &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
12910 "-f", "yuv4mpegpipe", "-strict", "-1", "-",
12911 ])
12912 .stdin(Stdio::null())
12913 .stdout(Stdio::piped())
12914 .stderr(Stdio::piped())
12915 .output()
12916 .expect("ffmpeg failed to run");
12917 assert!(
12918 y4m.status.success(),
12919 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
12920 String::from_utf8_lossy(&y4m.stderr)
12921 );
12922 let cq_arg = format!("--cq-level={cq}");
12923 let depth_arg = format!("--bit-depth={bit_depth}");
12924 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
12925 let args: Vec<&str> = vec![
12926 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=1",
12927 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
12928 "--lag-in-frames=0", "--auto-alt-ref=0",
12929 "--kf-min-dist=1000", "--kf-max-dist=1000",
12930 "--enable-rect-partitions=0", "--enable-ab-partitions=0",
12931 "--enable-1to4-partitions=0", "--min-partition-size=16",
12932 "--max-partition-size=64", "--enable-tx-size-search=0",
12933 "--enable-order-hint=0", "--enable-warped-motion=0", "--enable-obmc=0",
12934 "--enable-masked-comp=0", "--enable-interintra-comp=0",
12935 "--enable-dist-wtd-comp=0", "--enable-diff-wtd-comp=0",
12936 "--enable-onesided-comp=0", "--enable-interintra-wedge=0",
12937 "--enable-smooth-interintra=0", "--enable-filter-intra=0",
12938 "--enable-smooth-intra=0", "--enable-paeth-intra=0",
12939 "--enable-directional-intra=0", "--enable-angle-delta=0",
12940 "--enable-cdef=0", "--enable-restoration=0", "--enable-palette=0",
12941 "--enable-intrabc=0", "--enable-cfl-intra=0", "--enable-ref-frame-mvs=0",
12942 "--obu", "-o", "-", "-",
12943 ];
12944 let mut child = Command::new(aomenc_path())
12945 .args(&args)
12946 .stdin(Stdio::piped())
12947 .stdout(Stdio::piped())
12948 .stderr(Stdio::piped())
12949 .spawn()
12950 .expect("aomenc failed to start");
12951 child
12952 .stdin
12953 .take()
12954 .expect("aomenc stdin")
12955 .write_all(&y4m.stdout)
12956 .expect("writing y4m to aomenc");
12957 let out = child.wait_with_output().expect("aomenc failed to run");
12958 assert!(
12959 out.status.success(),
12960 "aomenc refused the fixture: {}",
12961 String::from_utf8_lossy(&out.stderr)
12962 );
12963 let stream = out.stdout;
12964 let before = crate::decode::nocfl_uv_mode_hits();
12965 let frames = match decode_stream(&stream) {
12966 Err(e) => {
12967 let msg = e.to_string();
12968 assert!(
12969 msg.contains("unsupported"),
12970 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
12971 attempt {attempt}): {msg}"
12972 );
12973 named_refusals += 1;
12974 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
12975 continue;
12976 }
12977 Ok(frames) => frames,
12978 };
12979 let hits = crate::decode::nocfl_uv_mode_hits() - before;
12980 let ffmpeg_frames = if bit_depth == 10 {
12981 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12982 } else {
12983 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12984 };
12985 assert_eq!(frames.len(), frame_count);
12986 if hits == 0 {
12987 carried_none += 1;
12988 }
12989 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12990 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
12991 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
12992 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
12993 }
12994 if hits > 0 {
12995 matched += 1;
12996 total_hits += hits;
12997 }
12998 }
12999 eprintln!(
13000 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
13001 attempts carrying a 64x64 intra superblock ({total_hits} no-CFL uv_mode reads), \
13002 {carried_none} attempts carried none"
13003 );
13004 assert!(
13005 matched > 0 && total_hits > 0,
13006 "{NAME} ({bit_depth}-bit): no square-only attempt decoded a 64x64 intra block \
13007 inside an inter frame, so the no-CFL uv_mode alphabet was never exercised -- \
13008 gate proved nothing ({named_refusals} refusals, {carried_none} carried none)"
13009 );
13010 }
13011 }
13012
13013 /// lane-mc64 r2: the RECT-ON twin of the square-only gate above, pinned
13014 /// as a stream fixture because its aomenc recipe is not reproducible
13015 /// (the r2 recipe re-encoded to a different file, measured md5
13016 /// `278be00...` vs the fixture's `add55f6...`; class
13017 /// `seeded-fixture-not-reproducible`).
13018 ///
13019 /// `crates/ec-av1/fixtures/av1_192x128_8bit_intra64_in_inter.obu`
13020 /// (sha256 `e4cff46cb1700527c68efc866db27a2835705e949d646f73f0c9df577d594bd6`)
13021 /// carries a 64x64 `PARTITION_NONE` INTRA block inside an INTER frame at
13022 /// decode-order frame 2, mi(16,32), in a stream whose OTHER superblocks
13023 /// are rect-partitioned -- so the 64-axis `is_cfl_allowed` narrowing
13024 /// (`blockd.h`: `wide <= 32 && high <= 32`) has to hold on the intra
13025 /// arm that the rect recipe reaches, not only on the whole-superblock
13026 /// one. Before lane-sbrect10's fix this frame reconstructed with 3720
13027 /// wrong luma samples (delta -12..+9, chroma bit-exact) and the decode
13028 /// then died at frame 3 on a phantom refusal of its own desync (class
13029 /// `refusal-from-own-desync`); all 6 decode-order frames are byte-exact
13030 /// against the oracle now.
13031 #[test]
13032 fn a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact() {
13033 const NAME: &str =
13034 "a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact";
13035 let _gate_lock = lock_gate_counters();
13036 if !have_aomenc() {
13037 eprintln!("SKIP {NAME}: no aomenc/aomdec oracle at {}", aomenc_path().display());
13038 return;
13039 }
13040 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
13041 .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu");
13042 let stream = std::fs::read(&path)
13043 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
13044 let before = crate::decode::nocfl_uv_mode_hits();
13045 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
13046 let hits = crate::decode::nocfl_uv_mode_hits() - before;
13047 assert_eq!(frames, 6, "{NAME}: expected 6 decode-order frames ({hidden} hidden)");
13048 assert!(
13049 hits > 0,
13050 "{NAME}: no 64-axis intra block read the no-CFL uv_mode alphabet -- the fixture no \
13051 longer carries the shape this test gates"
13052 );
13053 }
13054
13055 /// lane-inter4 r2: the 32x32-level inter `PARTITION_HORZ`/`PARTITION_VERT`
13056 /// strips (32x16 / 16x32) carrying a REAL residual -- the capability r1
13057 /// found missing ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs
13058 /// rectangular residual coding"). The strip's own rectangular max
13059 /// transform (`TX_32X16`/`TX_16X32`) is read through the rect var-tx tree,
13060 /// its coefficients through [`TxbSet::LumaRect32x16Inter`] /
13061 /// `ChromaRect16x8`, and inverted with the rect (sqrt2-scaled) inverse
13062 /// transform.
13063 ///
13064 /// `--min-partition-size=16 --max-partition-size=32` keeps the superblock
13065 /// level (64x32, still refused -- no 64-point rect transform) out, so
13066 /// every counted hit is a 32-level strip. The source is textured and
13067 /// translating precisely so the strips are NOT skip: a flat source (r1's)
13068 /// makes aomenc code them skip and proves nothing about the residual.
13069 /// Both `--enable-tx-size-search` arms run: `=0` exercises the
13070 /// whole-block rect transform with no `txfm_partition` symbol at all,
13071 /// `=1` the rect var-tx tree (no-split rect unit, or the split into square
13072 /// sub-transforms).
13073 ///
13074 /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and
13075 /// V; a refusal is counted, never SKIPped; an attempt that carried no rect
13076 /// inter residual is counted separately and still required pixel-exact.
13077 /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream
13078 /// whose compound blocks feed the next frame's motion field
13079 /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`).
13080 ///
13081 /// lane-interbis r1 pinned this recipe because it is the one the rect
13082 /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a
13083 /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its
13084 /// nearest candidate from a temporal cell holding the wrong reference:
13085 /// `build_motion_field` stored a compound block's FIRST reference where
13086 /// libaom stores its second). Every fully decoded attempt is compared
13087 /// plane by plane; a refusal is counted, never SKIPped; the temporal
13088 /// candidate counter must fire on a compared attempt, or the gate proves
13089 /// nothing.
13090 #[test]
13091 fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() {
13092 const NAME: &str =
13093 "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact";
13094 let _gate_lock = lock_gate_counters();
13095 if !have_ffmpeg() {
13096 eprintln!("SKIP {NAME}: no ffmpeg");
13097 return;
13098 }
13099 if !have_aomenc() {
13100 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13101 return;
13102 }
13103 let (width, height, frame_count) = (192usize, 128usize, 6usize);
13104 for bit_depth in [8u32, 10u32] {
13105 let (mut named_refusals, mut compared, mut tmv_proved) = (0u32, 0u32, 0usize);
13106 for attempt in 0..2u32 {
13107 let tx_search = if attempt == 0 { "0" } else { "1" };
13108 let duration = frame_count as f64 / 25.0;
13109 // The pinned source: horizontal structure translating along X
13110 // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN
13111 // blocks whose stored motion field the last frame reads back.
13112 let source = format!(
13113 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
13114 geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',format=yuv420p"
13115 );
13116 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
13117 let y4m = Command::new("ffmpeg")
13118 .args([
13119 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
13120 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
13121 ])
13122 .stdin(Stdio::null())
13123 .stdout(Stdio::piped())
13124 .stderr(Stdio::piped())
13125 .output()
13126 .expect("ffmpeg failed to run");
13127 assert!(
13128 y4m.status.success(),
13129 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
13130 String::from_utf8_lossy(&y4m.stderr)
13131 );
13132 let depth_arg = format!("--bit-depth={bit_depth}");
13133 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
13134 let tx_arg = format!("--enable-tx-size-search={tx_search}");
13135 let args: Vec<&str> = vec![
13136 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=34", "--cpu-used=0",
13137 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
13138 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
13139 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
13140 "--lag-in-frames=0",
13141 // Per-arm overrides go LAST (aomenc keeps the last
13142 // occurrence of a repeated --enable-* flag).
13143 &tx_arg,
13144 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
13145 "--enable-1to4-partitions=0", "--min-partition-size=16",
13146 "--max-partition-size=32",
13147 "--obu", "-o", "-", "-",
13148 ];
13149 let mut child = Command::new(aomenc_path())
13150 .args(&args)
13151 .stdin(Stdio::piped())
13152 .stdout(Stdio::piped())
13153 .stderr(Stdio::piped())
13154 .spawn()
13155 .expect("aomenc failed to start");
13156 child
13157 .stdin
13158 .take()
13159 .expect("aomenc stdin")
13160 .write_all(&y4m.stdout)
13161 .expect("writing y4m to aomenc");
13162 let out = child.wait_with_output().expect("aomenc failed to run");
13163 assert!(
13164 out.status.success(),
13165 "aomenc refused the fixture: {}",
13166 String::from_utf8_lossy(&out.stderr)
13167 );
13168 let stream = out.stdout;
13169 let before = decode::tmv_hits();
13170 let frames = match decode_stream(&stream) {
13171 Err(e) => {
13172 let msg = e.to_string();
13173 assert!(
13174 msg.contains("unsupported"),
13175 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
13176 attempt {attempt}): {msg}"
13177 );
13178 named_refusals += 1;
13179 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
13180 continue;
13181 }
13182 Ok(frames) => frames,
13183 };
13184 let tmv = decode::tmv_hits() - before;
13185 let ffmpeg_frames = if bit_depth == 10 {
13186 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
13187 } else {
13188 ffmpeg_decode_sequence(&stream, width, height, frame_count)
13189 };
13190 assert_eq!(frames.len(), frame_count);
13191 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13192 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
13193 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
13194 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
13195 }
13196 compared += 1;
13197 tmv_proved += tmv;
13198 }
13199 eprintln!(
13200 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
13201 pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}"
13202 );
13203 assert!(
13204 compared > 0,
13205 "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing"
13206 );
13207 assert!(
13208 tmv_proved > 0,
13209 "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \
13210 candidate into a block's stack -- gate proved nothing"
13211 );
13212 }
13213 }
13214
13215 /// lane-refstamp r1: `av1_setup_motion_field`'s `ref_stamp` budget in the
13216 /// presence of FORWARD KEY FRAMES (`--enable-fwd-kf=1`), which is the only
13217 /// configuration where a *forward* reference slot (BWDREF/ALTREF2/ALTREF)
13218 /// holds a key frame while temporal MV projection runs. libaom's
13219 /// `motion_field_projection` returns 0 for such a start frame, so it costs
13220 /// no `ref_stamp`; ours used to project the (empty) field and report
13221 /// success, spending the slot ALTREF/LAST2 should have had and losing
13222 /// their temporal candidates.
13223 ///
13224 /// Both bit depths; EVERY decoded frame (including the hidden alt-refs)
13225 /// compared to the oracle in decode order; a refusal is counted, never
13226 /// SKIPped. Two hard counters make the gate non-vacuous: frames that
13227 /// actually took the >=2-intra-forward-refs `ref_stamp` path, and blocks
13228 /// that folded a temporal MV candidate into their stack.
13229 #[test]
13230 fn a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact() {
13231 const NAME: &str = "a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact";
13232 let _gate_lock = lock_gate_counters();
13233 if !have_ffmpeg() {
13234 eprintln!("SKIP {NAME}: no ffmpeg");
13235 return;
13236 }
13237 if !have_aomenc() {
13238 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13239 return;
13240 }
13241 let (width, height, frame_count) = (192usize, 128usize, 24usize);
13242 for bit_depth in [8u32, 10u32] {
13243 let (mut named_refusals, mut compared, mut tmv_proved, mut stamp_proved) =
13244 (0u32, 0u32, 0usize, 0usize);
13245 let mut stamp2_proved = 0usize;
13246 for attempt in 0..2u32 {
13247 let duration = frame_count as f64 / 25.0;
13248 // Natural-ish motion: structure translating along X at 3 px per
13249 // frame plus a slow vertical drift, the source family the
13250 // temporal-MV gate already decodes fully.
13251 let source = format!(
13252 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
13253 geq=lum='128+58*sin((X+N*3)/6)+18*sin((Y+N*2)/23)',format=yuv420p"
13254 );
13255 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
13256 let y4m = Command::new("ffmpeg")
13257 .args([
13258 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
13259 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
13260 ])
13261 .stdin(Stdio::null())
13262 .stdout(Stdio::piped())
13263 .stderr(Stdio::piped())
13264 .output()
13265 .expect("ffmpeg failed to run");
13266 assert!(
13267 y4m.status.success(),
13268 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
13269 String::from_utf8_lossy(&y4m.stderr)
13270 );
13271 let depth_arg = format!("--bit-depth={bit_depth}");
13272 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
13273 let cq_arg = format!("--cq-level={}", if attempt == 0 { 34 } else { 45 });
13274 let args: Vec<&str> = vec![
13275 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
13276 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
13277 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
13278 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
13279 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
13280 "--enable-1to4-partitions=0", "--min-partition-size=16",
13281 "--max-partition-size=32",
13282 // Per-arm/feature overrides go LAST (aomenc keeps the LAST
13283 // occurrence of a repeated --enable-* flag).
13284 "--enable-order-hint=1", "--enable-ref-frame-mvs=1",
13285 "--enable-fwd-kf=1", "--fwd-kf-dist=8", "--kf-max-dist=1000",
13286 "--lag-in-frames=16", "--auto-alt-ref=1", "--arnr-maxframes=0",
13287 "--obu", "-o", "-", "-",
13288 ];
13289 let mut child = Command::new(aomenc_path())
13290 .args(&args)
13291 .stdin(Stdio::piped())
13292 .stdout(Stdio::piped())
13293 .stderr(Stdio::piped())
13294 .spawn()
13295 .expect("aomenc failed to start");
13296 child
13297 .stdin
13298 .take()
13299 .expect("aomenc stdin")
13300 .write_all(&y4m.stdout)
13301 .expect("writing y4m to aomenc");
13302 let out = child.wait_with_output().expect("aomenc failed to run");
13303 assert!(
13304 out.status.success(),
13305 "aomenc refused the fixture: {}",
13306 String::from_utf8_lossy(&out.stderr)
13307 );
13308 let stream = out.stdout;
13309 let before_tmv = decode::tmv_hits();
13310 let before_stamp = crate::motion_field::refstamp_intra_frames();
13311 if let Err(e) = decode_stream(&stream) {
13312 let msg = e.to_string();
13313 assert!(
13314 msg.contains("unsupported"),
13315 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
13316 attempt {attempt}): {msg}"
13317 );
13318 named_refusals += 1;
13319 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
13320 continue;
13321 }
13322 let tmv = decode::tmv_hits() - before_tmv;
13323 let stamp = crate::motion_field::refstamp_intra_frames().0 - before_stamp.0;
13324 let stamp2 = crate::motion_field::refstamp_intra_frames().1 - before_stamp.1;
13325 // Every frame, hidden ones included, compared in DECODE order.
13326 let (total, hidden) = decode_all_frames_vs_oracle(
13327 &stream,
13328 &format!("{NAME}-{bit_depth}bit-attempt{attempt}"),
13329 );
13330 eprintln!(
13331 "{NAME} ({bit_depth}-bit attempt {attempt}): {total} frames decoded \
13332 ({hidden} hidden), temporal candidates={tmv}, frames with a key/intra \
13333 forward ref={stamp} (two or more: {stamp2})"
13334 );
13335 compared += 1;
13336 tmv_proved += tmv;
13337 stamp_proved += stamp;
13338 stamp2_proved += stamp2;
13339 }
13340 assert!(
13341 compared > 0,
13342 "{NAME} ({bit_depth}-bit): every attempt refused ({named_refusals}) -- gate \
13343 proved nothing"
13344 );
13345 assert!(
13346 tmv_proved > 0,
13347 "{NAME} ({bit_depth}-bit): no compared attempt folded a temporal MV candidate \
13348 into a block's stack -- gate proved nothing"
13349 );
13350 assert!(
13351 stamp_proved > 0,
13352 "{NAME} ({bit_depth}-bit): no compared attempt ever had a forward reference \
13353 holding a key/intra frame ({stamp2_proved} frames had two) -- the ref_stamp \
13354 path this gate exists for never ran"
13355 );
13356 }
13357 }
13358
13359 #[test]
13360 // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter
13361 // residual path IS implemented and reached, but no aomenc recipe swept
13362 // this round produced a stream whose FIRST rect inter block is a 32x16 /
13363 // 16x32 one: real motion content always codes a 16x8/8x16 inter leaf (or
13364 // an intra rect strip) earlier in the tile, and both of those still refuse
13365 // by name, so the decode stops before any 32-level 2:1 strip. The 16x8
13366 // shape additionally needs `default_inter_ext_tx_cdf[2][TX_8X8]` (the
13367 // 12-symbol DTT9_IDTX_1DDCT row, only reachable through a rect
13368 // transform), which this round did not add. See lanes/inter4-r2.report.md.
13369 // 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.
13370 fn a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact() {
13371 const NAME: &str =
13372 "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact";
13373 let _gate_lock = lock_gate_counters();
13374 if !have_ffmpeg() {
13375 eprintln!("SKIP {NAME}: no ffmpeg");
13376 return;
13377 }
13378 if !have_aomenc() {
13379 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13380 return;
13381 }
13382 let (width, height, frame_count) = (192usize, 128usize, 6usize);
13383 for bit_depth in [8u32, 10u32] {
13384 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
13385 (0u32, 0u32, 0u32, 0u32);
13386 let (mut tu_proved, mut split_proved) = (0usize, 0usize);
13387 for attempt in 0..16u32 {
13388 // Two sources (a translating textured ramp, and testsrc2's
13389 // natural motion) x two quantisers x two tx-size-search arms x
13390 // two motion steps.
13391 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
13392 let cq = [34, 22][(attempt / 2 % 2) as usize];
13393 let natural = attempt / 4 % 2 == 1;
13394 let sp = 3 + (attempt / 8) * 5;
13395 let duration = frame_count as f64 / 25.0;
13396 // Continuous-tone, mid-frequency, translating: a flat or
13397 // banded source makes aomenc code the strips `skip` (r1's
13398 // gate) and its screen-content detector fires on the
13399 // synthetic ramps, stopping the decode at an unrelated intra
13400 // refusal long before any inter strip.
13401 // Structure ALONG one axis is what makes aomenc's RD pick a
13402 // 2:1 rect partition on that axis: horizontal bands drifting
13403 // vertically favour PARTITION_HORZ (32x16 strips), the
13404 // transposed source PARTITION_VERT (16x32).
13405 let lum = if natural {
13406 format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
13407 } else {
13408 format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
13409 };
13410 let source = format!(
13411 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
13412 geq=lum='{lum}',format=yuv420p"
13413 );
13414 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
13415 let y4m = Command::new("ffmpeg")
13416 .args([
13417 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
13418 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
13419 ])
13420 .stdin(Stdio::null())
13421 .stdout(Stdio::piped())
13422 .stderr(Stdio::piped())
13423 .output()
13424 .expect("ffmpeg failed to run");
13425 assert!(
13426 y4m.status.success(),
13427 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
13428 String::from_utf8_lossy(&y4m.stderr)
13429 );
13430 let cq_arg = format!("--cq-level={cq}");
13431 let depth_arg = format!("--bit-depth={bit_depth}");
13432 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
13433 let tx_arg = format!("--enable-tx-size-search={tx_search}");
13434 let args: Vec<&str> = vec![
13435 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
13436 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
13437 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
13438 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
13439 "--lag-in-frames=0",
13440 // Per-arm overrides go LAST: aomenc keeps the last
13441 // occurrence of a repeated --enable-* flag.
13442 &tx_arg,
13443 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
13444 "--enable-1to4-partitions=0", "--min-partition-size=16",
13445 "--max-partition-size=32",
13446 "--obu", "-o", "-", "-",
13447 ];
13448 let mut child = Command::new(aomenc_path())
13449 .args(&args)
13450 .stdin(Stdio::piped())
13451 .stdout(Stdio::piped())
13452 .stderr(Stdio::piped())
13453 .spawn()
13454 .expect("aomenc failed to start");
13455 child
13456 .stdin
13457 .take()
13458 .expect("aomenc stdin")
13459 .write_all(&y4m.stdout)
13460 .expect("writing y4m to aomenc");
13461 let out = child.wait_with_output().expect("aomenc failed to run");
13462 assert!(
13463 out.status.success(),
13464 "aomenc refused the fixture: {}",
13465 String::from_utf8_lossy(&out.stderr)
13466 );
13467 let stream = out.stdout;
13468 let before = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
13469 let frames = match decode_stream(&stream) {
13470 Err(e) => {
13471 let msg = e.to_string();
13472 assert!(
13473 msg.contains("unsupported"),
13474 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
13475 attempt {attempt}): {msg}"
13476 );
13477 named_refusals += 1;
13478 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
13479 continue;
13480 }
13481 Ok(frames) => frames,
13482 };
13483 let after = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
13484 let (tu, split) = (after.0 - before.0, after.1 - before.1);
13485 let ffmpeg_frames = if bit_depth == 10 {
13486 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
13487 } else {
13488 ffmpeg_decode_sequence(&stream, width, height, frame_count)
13489 };
13490 assert_eq!(frames.len(), frame_count);
13491 let mismatched = frames
13492 .iter()
13493 .zip(&ffmpeg_frames)
13494 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
13495 if tu + split == 0 {
13496 out_of_scope += 1;
13497 if mismatched {
13498 oos_mismatch += 1;
13499 eprintln!(
13500 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
13501 coded rect inter transform units -- another shape's defect"
13502 );
13503 }
13504 continue;
13505 }
13506 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13507 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
13508 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
13509 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
13510 }
13511 tu_proved += tu;
13512 split_proved += split;
13513 matched += 1;
13514 }
13515 eprintln!(
13516 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
13517 attempts carrying a coded rect inter residual, whole-block rect TUs={tu_proved}, \
13518 rect trees that split={split_proved}, {out_of_scope} attempts carried none \
13519 ({oos_mismatch} of them mismatched)"
13520 );
13521 assert_eq!(
13522 oos_mismatch, 0,
13523 "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
13524 mismatched ffmpeg -- a defect of another shape, not a pass"
13525 );
13526 assert!(
13527 tu_proved > 0,
13528 "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever coded a rectangular inter \
13529 residual (tu={tu_proved}, split={split_proved}, {named_refusals} refusals, \
13530 {out_of_scope} out of scope) -- gate proved nothing"
13531 );
13532 }
13533 }
13534
13535 /// lane-intersub8: `PARTITION_SPLIT` below 8x8 on an INTER frame -- four
13536 /// `BLOCK_4X4` inter sub-blocks with one shared 4x4 chroma unit per plane,
13537 /// predicted the sub8x8 way (2x2 chroma piece per luma sub-block mv,
13538 /// `dec_build_inter_predictors`' `is_sub8x8` branch). Reality of the shape
13539 /// was established BEFORE the code (class refusal-from-own-desync): the
13540 /// oracle `aomdec`'s `EC_TRACE` prints `EC_PART_VAL ... bsize=3 value=3`
13541 /// on this recipe's inter frames.
13542 ///
13543 /// Attempts 0..7 run `--enable-rect-partitions=0`, where aomenc can only
13544 /// pick SPLIT below 8x8; attempts 8..15 repeat the schedule with rect on,
13545 /// where it picks HORZ/VERT below 8x8 far more often than SPLIT -- the VERT
13546 /// arm (two `BLOCK_4X8` inter leaves, `decode_inter_sub8_rect2`) is what the
13547 /// `rect_fired` assert pins. The HORZ twin decodes but is refused by name
13548 /// (lane-intersub8 r3: a measured sweep desyncs the block to its right).
13549 #[test]
13550 fn a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact() {
13551 const NAME: &str =
13552 "a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact";
13553 let _gate_lock = lock_gate_counters();
13554 if !have_ffmpeg() {
13555 eprintln!("SKIP {NAME}: no ffmpeg");
13556 return;
13557 }
13558 if !have_aomenc() {
13559 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13560 return;
13561 }
13562 let (width, height, frame_count) = (192usize, 128usize, 6usize);
13563 let mut fired = 0u32;
13564 // lane-intersub8 r3: attempts 8..15 repeat the same schedule with
13565 // `--enable-rect-partitions=1`, where aomenc picks PARTITION_VERT below
13566 // 8x8 (two BLOCK_4X8 inter leaves, one shared 4x4 chroma unit predicted
13567 // from BOTH sub-blocks' mvs). The HORZ twin is still refused by name.
13568 let mut rect_fired = 0u32;
13569 // lane-intersub8 r5: the two rect axes counted apart. Attempts 16..23
13570 // are the same recipe family with the geq source TRANSPOSED (the sine
13571 // that moves runs along Y, not X): measured over a 56-arm sweep
13572 // (~/.cache/intersub8-sweep-r5.log, cq {8,12,14,16,20,26,32} x sp
13573 // {3,6,9,12} x both depths, rect on), aomenc picks PARTITION_HORZ
13574 // below 8x8 on that source and PARTITION_VERT on the untransposed one
13575 // -- neither schedule reaches the other axis, so both are needed.
13576 let (mut horz_fired, mut vert_fired) = (0u32, 0u32);
13577 // Rect (non-square) masked-compound blocks on attempts that DECODED
13578 // and were pixel-compared -- never off a refused stream (class
13579 // counter-from-refused-stream). This is the shape whose
13580 // `compound_type`/`wedge_idx` CDF row lane-intersub8 r4 fixed.
13581 let mut rect_masked = 0usize;
13582 let mut refusals: Vec<String> = Vec::new();
13583 let mut out_of_scope_mismatch = 0u32;
13584 for bit_depth in [8u32, 10u32] {
13585 for attempt in 0..24u32 {
13586 let rect = if attempt >= 16 { 1 } else { attempt / 8 };
13587 let rect_arg = format!("--enable-rect-partitions={rect}");
13588 // lane-intersub8 r2, measured schedule (sweep of cq
13589 // {8,10,12,14,16,18,20} x sp {3,6,9,12} x both depths,
13590 // `decode_probe`'s `sub8_inter_split:` counter vs an ffmpeg
13591 // rawvideo compare): sub-8x8 inter SPLIT groups fire at
13592 // (8-bit, cq 12, sp 3) = 1 group and (10-bit, cq 12, sp 6) =
13593 // 3 groups, both pixel-exact. cq 8 and 10 are NOT used: at
13594 // those quantizers this recipe also carries a CDEF defect of
13595 // another shape -- three luma samples of |d| = 1 on
13596 // decode-order frames 3/4, zero sub-8x8 inter split groups,
13597 // and the identical recipe re-encoded with `--enable-cdef=0`
13598 // decodes all six frames exact. Deferred to a CDEF lane
13599 // rather than hidden: cq 16..20 are all exact, so this gate
13600 // is not selecting quantizers that hide a defect of its own
13601 // shape.
13602 // Attempts 16..23: the (cq, sp) pairs the r5 sweep measured
13603 // as HORZ-firing on the transposed source -- 8-bit
13604 // (14,3)/(20,3)/(32,9), 10-bit (12,3)/(16,3); the rest of the
13605 // eight are non-firing neighbours kept so a schedule that
13606 // stops firing shows up as out-of-scope, not as a silent pass.
13607 const HORZ_SCHEDULE: [(u32, u32); 8] =
13608 [(14, 3), (20, 3), (32, 9), (12, 3), (16, 3), (12, 9), (14, 9), (26, 3)];
13609 let (cq, sp) = if attempt >= 16 {
13610 HORZ_SCHEDULE[(attempt - 16) as usize]
13611 } else {
13612 ([12, 14][(attempt % 2) as usize], 3 + ((attempt % 8) / 2) * 3)
13613 };
13614 let duration = frame_count as f64 / 25.0;
13615 let source = if attempt >= 16 {
13616 format!(
13617 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
13618 geq=lum='128+58*sin((Y+N*{sp})/6)+18*sin(X/23)',format=yuv420p"
13619 )
13620 } else {
13621 format!(
13622 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
13623 geq=lum='128+58*sin((X+N*{sp})/6)+18*sin(Y/23)',format=yuv420p"
13624 )
13625 };
13626 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
13627 let y4m = Command::new("ffmpeg")
13628 .args([
13629 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
13630 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
13631 ])
13632 .stdin(Stdio::null())
13633 .stdout(Stdio::piped())
13634 .stderr(Stdio::piped())
13635 .output()
13636 .expect("ffmpeg failed to run");
13637 assert!(
13638 y4m.status.success(),
13639 "{NAME}: ffmpeg refused the fixture: {}",
13640 String::from_utf8_lossy(&y4m.stderr)
13641 );
13642 let cq_arg = format!("--cq-level={cq}");
13643 let depth_arg = format!("--bit-depth={bit_depth}");
13644 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
13645 let args: Vec<&str> = vec![
13646 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
13647 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
13648 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
13649 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
13650 "--lag-in-frames=0", "--enable-obmc=0", "--enable-tx-size-search=1",
13651 // Per-arm overrides last (aomenc keeps the LAST occurrence).
13652 "--enable-rect-partitions=0", "--enable-ab-partitions=0",
13653 "--enable-1to4-partitions=0", "--min-partition-size=4",
13654 "--max-partition-size=16",
13655 &rect_arg,
13656 "--obu", "-o", "-", "-",
13657 ];
13658 let mut child = Command::new(aomenc_path())
13659 .args(&args)
13660 .stdin(Stdio::piped())
13661 .stdout(Stdio::piped())
13662 .stderr(Stdio::piped())
13663 .spawn()
13664 .expect("aomenc failed to start");
13665 child
13666 .stdin
13667 .take()
13668 .expect("aomenc stdin")
13669 .write_all(&y4m.stdout)
13670 .expect("writing y4m to aomenc");
13671 let out = child.wait_with_output().expect("aomenc failed to run");
13672 assert!(
13673 out.status.success(),
13674 "{NAME}: aomenc refused the fixture: {}",
13675 String::from_utf8_lossy(&out.stderr)
13676 );
13677 let stream = out.stdout;
13678 let before = decode::sub8_inter_split_hits();
13679 let before_rect = decode::sub8_inter_rect_hits();
13680 let before_masked = decode::rect_masked_compound_hits();
13681 let frames = match decode_stream(&stream) {
13682 Err(e) => {
13683 let msg = e.to_string();
13684 assert!(
13685 msg.contains("unsupported"),
13686 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
13687 attempt {attempt}): {msg}"
13688 );
13689 refusals.push(format!("{bit_depth}-bit attempt {attempt}: {msg}"));
13690 continue;
13691 }
13692 Ok(frames) => frames,
13693 };
13694 let split_groups = decode::sub8_inter_split_hits() - before;
13695 let rect_now = decode::sub8_inter_rect_hits();
13696 let rect_groups = (rect_now.0 - before_rect.0) + (rect_now.1 - before_rect.1);
13697 let groups = split_groups + rect_groups;
13698 let ffmpeg_frames = if bit_depth == 10 {
13699 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
13700 } else {
13701 ffmpeg_decode_sequence(&stream, width, height, frame_count)
13702 };
13703 assert_eq!(frames.len(), frame_count);
13704 let mismatched = frames
13705 .iter()
13706 .zip(&ffmpeg_frames)
13707 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
13708 if groups == 0 {
13709 // Out of scope: no sub-8x8 inter split in this attempt.
13710 if mismatched {
13711 out_of_scope_mismatch += 1;
13712 eprintln!(
13713 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
13714 sub-8x8 inter group -- another shape's defect"
13715 );
13716 }
13717 refusals.push(format!(
13718 "{bit_depth}-bit attempt {attempt}: decoded, but no sub-8x8 inter split"
13719 ));
13720 continue;
13721 }
13722 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13723 assert_eq!(
13724 got.y, want.y,
13725 "luma frame {i} ({bit_depth}-bit attempt {attempt}, {groups} sub-8x8 \
13726 inter split groups)"
13727 );
13728 assert_eq!(got.u, want.u, "U frame {i} ({bit_depth}-bit attempt {attempt})");
13729 assert_eq!(got.v, want.v, "V frame {i} ({bit_depth}-bit attempt {attempt})");
13730 }
13731 fired += 1;
13732 if rect_groups > 0 {
13733 rect_fired += 1;
13734 }
13735 if rect_now.0 - before_rect.0 > 0 {
13736 horz_fired += 1;
13737 }
13738 if rect_now.1 - before_rect.1 > 0 {
13739 vert_fired += 1;
13740 }
13741 // Only now, past the pixel compare, is this attempt's
13742 // masked-compound count admissible.
13743 rect_masked += decode::rect_masked_compound_hits() - before_masked;
13744 }
13745 }
13746 eprintln!(
13747 "{NAME}: fired={fired} horz={horz_fired} vert={vert_fired} rect_masked={rect_masked}"
13748 );
13749 assert_eq!(
13750 out_of_scope_mismatch, 0,
13751 "{NAME}: attempts mismatched with no sub-8x8 inter group"
13752 );
13753 assert!(
13754 fired >= 2,
13755 "{NAME}: fewer than 2 firing+pixel-exact attempts:\n{}",
13756 refusals.join("\n")
13757 );
13758 assert!(
13759 rect_fired >= 2,
13760 "{NAME}: fewer than 2 firing+pixel-exact attempts with a RECTANGULAR sub-8x8 \
13761 inter leaf (4x8):\n{}",
13762 refusals.join("\n")
13763 );
13764 assert!(
13765 vert_fired >= 2,
13766 "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter VERT \
13767 pair (two BLOCK_4X8 leaves):\n{}",
13768 refusals.join("\n")
13769 );
13770 // lane-intersub8 r5, measured `rect_masked=2` over the 48 attempts:
13771 // the rect masked-compound blocks whose `compound_type`/`wedge_idx`
13772 // CDF row r4 corrected, counted only on pixel-compared attempts.
13773 assert!(
13774 rect_masked >= 1,
13775 "{NAME}: no RECTANGULAR masked-compound block on any pixel-compared attempt -- \
13776 the r4 compound_type/wedge_idx CDF-row fix is unexercised:\n{}",
13777 refusals.join("\n")
13778 );
13779 assert!(
13780 horz_fired >= 2,
13781 "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter HORZ \
13782 pair (two BLOCK_8X4 leaves):\n{}",
13783 refusals.join("\n")
13784 );
13785 }
13786
13787 #[test]
13788 // lane-inter4 r3: the 16x16-level rect INTER leaf -- PARTITION_HORZ /
13789 // PARTITION_VERT at 16x16 on an inter frame, i.e. two 16x8 / 8x16 inter
13790 // blocks, mode info + rectangular residual + prediction. Every decoded
13791 // frame is compared Y/U/V against ffmpeg, refusals are counted and never
13792 // SKIPped, and the gate asserts a pixel-exact attempt for BOTH axes that
13793 // also coded a rectangular inter transform unit (i.e. was not `skip`).
13794 fn a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact() {
13795 const NAME: &str =
13796 "a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact";
13797 let _gate_lock = lock_gate_counters();
13798 if !have_ffmpeg() {
13799 eprintln!("SKIP {NAME}: no ffmpeg");
13800 return;
13801 }
13802 if !have_aomenc() {
13803 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13804 return;
13805 }
13806 let (width, height, frame_count) = (192usize, 128usize, 6usize);
13807 // Coded (non-skip) rect inter transform units, summed over both bit
13808 // depths: at 10 bits this recipe's rect leaves all come out `skip`
13809 // (measured at cq 34/22, 30/26 and 24/12 -- the lower pairs stop
13810 // reaching a rect leaf at all), so the RESIDUAL half of the claim is
13811 // proven by the 8-bit arm while the 10-bit arm proves the mode-info,
13812 // prediction and neighbour halves on both axes.
13813 let mut tu_total = 0usize;
13814 for bit_depth in [8u32, 10u32] {
13815 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
13816 (0u32, 0u32, 0u32, 0u32);
13817 let (mut tu_proved, mut split_proved) = (0usize, 0usize);
13818 let (mut horz_proved, mut vert_proved, mut sub16_split) = (0u32, 0u32, 0usize);
13819 // lane-inter4 r4, measured residue of this recipe family (sweep
13820 // over cq {8,12,16,22} x {both axes} x both depths, tx-size-search
13821 // on, via `decode_probe`'s `rect_inter:` counters): the rect
13822 // var-tx SPLIT arm never fires (txsplit=0 everywhere) and a 10-bit
13823 // rect leaf is always `skip` (tu=0 at every cq that decodes) --
13824 // below cq 22 every attempt stops at another lane's intra refusal
13825 // ("a HORZ/VERT intra strip below 16x16 with a split transform").
13826 // Both are asserted here only where they DO fire (8-bit tu>0);
13827 // shipped-but-unexercised, see lanes/inter4-r4.report.md.
13828 // lane-inter4 r4: attempts 16..32 repeat the same sweep with
13829 // `--enable-obmc=1`. r3 refused OBMC on this shape; r4's
13830 // instrumented-aomdec comparison showed the neighbour list AND
13831 // every pre-filter frame bit-exact, so the arm is a gate now.
13832 let mut obmc_leaf_proved = 0usize;
13833 for attempt in 0..32u32 {
13834 let obmc_arg = if attempt >= 16 { "--enable-obmc=1" } else { "--enable-obmc=0" };
13835 let attempt = attempt % 16;
13836 // Two sources (a translating textured ramp, and testsrc2's
13837 // natural motion) x two quantisers x two tx-size-search arms x
13838 // two motion steps.
13839 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
13840 // A 10-bit encode of the same source spends fewer bits on
13841 // residual at a given cq, so it needs the lower pair to make
13842 // a rect leaf non-skip at all (measured: cq 34/22 gives zero
13843 // coded rect inter TUs in 16 10-bit attempts).
13844 let cq = [34, 22][(attempt / 2 % 2) as usize];
13845 let natural = attempt / 4 % 2 == 1;
13846 let sp = 3 + (attempt / 8) * 5;
13847 let duration = frame_count as f64 / 25.0;
13848 // Continuous-tone, mid-frequency, translating: a flat or
13849 // banded source makes aomenc code the strips `skip` (r1's
13850 // gate) and its screen-content detector fires on the
13851 // synthetic ramps, stopping the decode at an unrelated intra
13852 // refusal long before any inter strip.
13853 // Structure ALONG one axis is what makes aomenc's RD pick a
13854 // 2:1 rect partition on that axis: horizontal bands drifting
13855 // vertically favour PARTITION_HORZ (32x16 strips), the
13856 // transposed source PARTITION_VERT (16x32).
13857 let lum = if natural {
13858 format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
13859 } else {
13860 format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
13861 };
13862 let source = format!(
13863 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
13864 geq=lum='{lum}',format=yuv420p"
13865 );
13866 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
13867 let y4m = Command::new("ffmpeg")
13868 .args([
13869 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
13870 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
13871 ])
13872 .stdin(Stdio::null())
13873 .stdout(Stdio::piped())
13874 .stderr(Stdio::piped())
13875 .output()
13876 .expect("ffmpeg failed to run");
13877 assert!(
13878 y4m.status.success(),
13879 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
13880 String::from_utf8_lossy(&y4m.stderr)
13881 );
13882 let cq_arg = format!("--cq-level={cq}");
13883 let depth_arg = format!("--bit-depth={bit_depth}");
13884 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
13885 let tx_arg = format!("--enable-tx-size-search={tx_search}");
13886 let args: Vec<&str> = vec![
13887 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
13888 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
13889 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
13890 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
13891 "--lag-in-frames=0",
13892 // Per-arm overrides go LAST: aomenc keeps the last
13893 // occurrence of a repeated --enable-* flag.
13894 &tx_arg,
13895 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
13896 "--enable-1to4-partitions=0", "--min-partition-size=8",
13897 "--max-partition-size=16",
13898 obmc_arg,
13899 "--obu", "-o", "-", "-",
13900 ];
13901 let mut child = Command::new(aomenc_path())
13902 .args(&args)
13903 .stdin(Stdio::piped())
13904 .stdout(Stdio::piped())
13905 .stderr(Stdio::piped())
13906 .spawn()
13907 .expect("aomenc failed to start");
13908 child
13909 .stdin
13910 .take()
13911 .expect("aomenc stdin")
13912 .write_all(&y4m.stdout)
13913 .expect("writing y4m to aomenc");
13914 let out = child.wait_with_output().expect("aomenc failed to run");
13915 assert!(
13916 out.status.success(),
13917 "aomenc refused the fixture: {}",
13918 String::from_utf8_lossy(&out.stderr)
13919 );
13920 let stream = out.stdout;
13921 let before = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
13922 let before_obmc_leaf = decode::obmc_rect_leaf_hits();
13923 let before_leaf = (
13924 decode::inter_leaf16_horz_hits(),
13925 decode::inter_leaf16_vert_hits(),
13926 decode::inter_sub16_split_hits(),
13927 );
13928 let frames = match decode_stream(&stream) {
13929 Err(e) => {
13930 let msg = e.to_string();
13931 assert!(
13932 msg.contains("unsupported"),
13933 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
13934 attempt {attempt}): {msg}"
13935 );
13936 named_refusals += 1;
13937 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
13938 continue;
13939 }
13940 Ok(frames) => frames,
13941 };
13942 let after = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
13943 let (tu, split) = (after.0 - before.0, after.1 - before.1);
13944 let obmc_leaf = decode::obmc_rect_leaf_hits() - before_obmc_leaf;
13945 let (horz, vert, splits16) = (
13946 decode::inter_leaf16_horz_hits() - before_leaf.0,
13947 decode::inter_leaf16_vert_hits() - before_leaf.1,
13948 decode::inter_sub16_split_hits() - before_leaf.2,
13949 );
13950 let ffmpeg_frames = if bit_depth == 10 {
13951 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
13952 } else {
13953 ffmpeg_decode_sequence(&stream, width, height, frame_count)
13954 };
13955 assert_eq!(frames.len(), frame_count);
13956 let mismatched = frames
13957 .iter()
13958 .zip(&ffmpeg_frames)
13959 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
13960 if horz + vert == 0 {
13961 out_of_scope += 1;
13962 if mismatched {
13963 oos_mismatch += 1;
13964 eprintln!(
13965 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
13966 16-level rect inter leaf -- another shape's defect"
13967 );
13968 }
13969 continue;
13970 }
13971 if mismatched {
13972 // lane-inter4 r3: where, not just that -- a handful of
13973 // 4x4-aligned pixels is a prediction/reconstruction
13974 // defect, a whole band from the first row down is a
13975 // desync.
13976 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13977 let bad: Vec<usize> = (0..got.y.len())
13978 .filter(|&k| got.y[k] != want.y[k])
13979 .collect();
13980 if !bad.is_empty() {
13981 eprintln!(
13982 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
13983 pixels differ, first at ({}, {}), max |delta| {}",
13984 bad.len(),
13985 bad[0] % width,
13986 bad[0] / width,
13987 bad.iter()
13988 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
13989 .max()
13990 .unwrap_or(0)
13991 );
13992 }
13993 }
13994 }
13995 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13996 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
13997 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
13998 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
13999 }
14000 tu_proved += tu;
14001 obmc_leaf_proved += obmc_leaf;
14002 split_proved += split;
14003 sub16_split += splits16;
14004 if horz > 0 {
14005 horz_proved += 1;
14006 }
14007 if vert > 0 {
14008 vert_proved += 1;
14009 }
14010 matched += 1;
14011 }
14012 eprintln!(
14013 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
14014 attempts carrying a 16-level rect inter leaf, 16x8-carrying={horz_proved}, \
14015 8x16-carrying={vert_proved}, whole-block rect TUs={tu_proved}, rect trees that \
14016 split={split_proved}, 16x16 SPLITs={sub16_split}, OBMC blends on a rect \
14017 leaf={obmc_leaf_proved}, {out_of_scope} attempts \
14018 carried none ({oos_mismatch} of them mismatched)"
14019 );
14020 assert_eq!(
14021 oos_mismatch, 0,
14022 "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
14023 mismatched ffmpeg -- a defect of another shape, not a pass"
14024 );
14025 assert!(
14026 horz_proved > 0 && vert_proved > 0,
14027 "{NAME} ({bit_depth}-bit): the 16-level rect inter leaf is not proven on both \
14028 axes (16x8={horz_proved}, 8x16={vert_proved}, tu={tu_proved}, 16x16 \
14029 SPLITs={sub16_split}, {named_refusals} refusals, {out_of_scope} out of \
14030 scope) -- gate proved nothing"
14031 );
14032 assert!(
14033 obmc_leaf_proved > 0,
14034 "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever ran the OBMC blend on a \
14035 16x8/8x16 inter leaf -- the `--enable-obmc=1` arm proved nothing"
14036 );
14037 tu_total += tu_proved;
14038 }
14039 assert!(
14040 tu_total > 0,
14041 "{NAME}: no pixel-exact attempt at either bit depth coded a rectangular inter \
14042 residual on a 16-level leaf -- the residual half of the claim is unproven"
14043 );
14044 }
14045
14046
14047 #[test]
14048 // lane-inter16ab r1: the 16x16-level AB partitions on an INTER frame --
14049 // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter
14050 // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is
14051 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
14052 // out-of-scope mismatches fail the gate, and EACH of the four arms must
14053 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
14054 // proof of four). `--enable-1to4-partitions=0` because the 16-level 1:4
14055 // pair (16x4/4x16 inter strips) is still refused by name.
14056 fn a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact() {
14057 const NAME: &str =
14058 "a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact";
14059 let _gate_lock = lock_gate_counters();
14060 if !have_ffmpeg() {
14061 eprintln!("SKIP {NAME}: no ffmpeg");
14062 return;
14063 }
14064 if !have_aomenc() {
14065 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14066 return;
14067 }
14068 let (width, height, frame_count) = (192usize, 128usize, 6usize);
14069 // Per arm, over both bit depths: how many pixel-exact attempts fired
14070 // it at least once.
14071 let mut arms_total = [0u32; 4];
14072 for bit_depth in [8u32, 10u32] {
14073 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
14074 (0u32, 0u32, 0u32, 0u32);
14075 let mut arms_proved = [0u32; 4];
14076 for attempt in 0..32u32 {
14077 // Two sources (structure along X vs along Y -- an AB
14078 // partition needs an L/T-shaped feature, so both orientations
14079 // are swept), four quantisers, two motion steps, two tiling
14080 // arms. r1 measured (sweep script in the report): a 16-attempt
14081 // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A
14082 // at 8 bits, so the quantiser axis is four wide here; cq 46 on
14083 // the X-structured source is deliberately NOT in the list --
14084 // that stream's decode-order frame 4 desyncs on a defect this
14085 // lane does not own (aomdec's own EC_PART trace reads ZERO
14086 // AB partitions at BLOCK_16X16 anywhere in it, so the AB
14087 // counters it raises are read out of an already-diverged
14088 // stream; see lanes/inter16ab-r1.report.md).
14089 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
14090 // The 10-bit arm swaps cq 40 for 28 on the same sources: at
14091 // cq 40 the X-structured 10-bit stream mismatches ffmpeg with
14092 // ZERO 16-level AB partitions in it (another shape's defect,
14093 // measured r1 -- the gate's own `oos_mismatch` counter is
14094 // what found it, and it is reported, not silenced).
14095 let cq = if bit_depth == 10 {
14096 [18, 22, 34, 28][(attempt / 2 % 4) as usize]
14097 } else {
14098 [18, 22, 34, 40][(attempt / 2 % 4) as usize]
14099 };
14100 let natural = attempt / 8 % 2 == 1;
14101 let group = attempt / 16;
14102 // r1: a `--tile-columns=1` arm of this same sweep PANICS in
14103 // `mc::from_switchable_symbol` (a 4th symbol out of a
14104 // 3-symbol alphabet = someone else's desync, the signature
14105 // the ledger already pins for the below-8x8 inter leaf), not
14106 // in anything this lane added -- so the tiled arm is left out
14107 // rather than turned into a SKIP or a weakened assert.
14108 // Reported as residue in lanes/inter16ab-r1.report.md.
14109 let tile_cols = "0";
14110 let sp = 3 + (group % 2) * 5;
14111 let duration = frame_count as f64 / 25.0;
14112 // Continuous-tone translating texture with a second, coarser
14113 // component on the cross axis: aomenc's RD picks an AB
14114 // partition where one 16x16 quadrant differs from its three
14115 // siblings, which the two sinusoids at different periods
14116 // produce all over the frame.
14117 let lum = if natural {
14118 format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)")
14119 } else {
14120 format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)")
14121 };
14122 let source = format!(
14123 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
14124 geq=lum='{lum}',format=yuv420p"
14125 );
14126 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
14127 let y4m = Command::new("ffmpeg")
14128 .args([
14129 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
14130 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
14131 ])
14132 .stdin(Stdio::null())
14133 .stdout(Stdio::piped())
14134 .stderr(Stdio::piped())
14135 .output()
14136 .expect("ffmpeg failed to run");
14137 assert!(
14138 y4m.status.success(),
14139 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
14140 String::from_utf8_lossy(&y4m.stderr)
14141 );
14142 let cq_arg = format!("--cq-level={cq}");
14143 let depth_arg = format!("--bit-depth={bit_depth}");
14144 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
14145 let tx_arg = format!("--enable-tx-size-search={tx_search}");
14146 let tile_arg = format!("--tile-columns={tile_cols}");
14147 let args: Vec<&str> = vec![
14148 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
14149 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
14150 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
14151 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
14152 "--lag-in-frames=0", "--kf-max-dist=9999", &tile_arg,
14153 // Per-arm overrides go LAST: aomenc keeps the last
14154 // occurrence of a repeated --enable-* flag.
14155 &tx_arg,
14156 "--enable-rect-partitions=1", "--enable-ab-partitions=1",
14157 "--enable-1to4-partitions=0", "--min-partition-size=8",
14158 "--max-partition-size=16",
14159 "--obu", "-o", "-", "-",
14160 ];
14161 let mut child = Command::new(aomenc_path())
14162 .args(&args)
14163 .stdin(Stdio::piped())
14164 .stdout(Stdio::piped())
14165 .stderr(Stdio::piped())
14166 .spawn()
14167 .expect("aomenc failed to start");
14168 child
14169 .stdin
14170 .take()
14171 .expect("aomenc stdin")
14172 .write_all(&y4m.stdout)
14173 .expect("writing y4m to aomenc");
14174 let out = child.wait_with_output().expect("aomenc failed to run");
14175 assert!(
14176 out.status.success(),
14177 "aomenc refused the fixture: {}",
14178 String::from_utf8_lossy(&out.stderr)
14179 );
14180 let stream = out.stdout;
14181 let before = decode::ab16_inter_hits_by_arm();
14182 let frames = match decode_stream(&stream) {
14183 Err(e) => {
14184 let msg = e.to_string();
14185 assert!(
14186 msg.contains("unsupported"),
14187 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
14188 attempt {attempt}): {msg}"
14189 );
14190 named_refusals += 1;
14191 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
14192 continue;
14193 }
14194 Ok(frames) => frames,
14195 };
14196 let after = decode::ab16_inter_hits_by_arm();
14197 let fired: Vec<usize> =
14198 (0..4).map(|a| after[a] - before[a]).collect();
14199 let ffmpeg_frames = if bit_depth == 10 {
14200 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14201 } else {
14202 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14203 };
14204 assert_eq!(frames.len(), frame_count);
14205 let mismatched = frames
14206 .iter()
14207 .zip(&ffmpeg_frames)
14208 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14209 if fired.iter().sum::<usize>() == 0 {
14210 out_of_scope += 1;
14211 if mismatched {
14212 oos_mismatch += 1;
14213 eprintln!(
14214 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
14215 16-level inter AB partition -- another shape's defect"
14216 );
14217 }
14218 continue;
14219 }
14220 if mismatched {
14221 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14222 let bad: Vec<usize> =
14223 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
14224 if !bad.is_empty() {
14225 eprintln!(
14226 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
14227 pixels differ, first at ({}, {}), max |delta| {}",
14228 bad.len(),
14229 bad[0] % width,
14230 bad[0] / width,
14231 bad.iter()
14232 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
14233 .max()
14234 .unwrap_or(0)
14235 );
14236 }
14237 }
14238 }
14239 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14240 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
14241 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
14242 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
14243 }
14244 for a in 0..4 {
14245 if fired[a] > 0 {
14246 arms_proved[a] += 1;
14247 arms_total[a] += 1;
14248 }
14249 }
14250 matched += 1;
14251 }
14252 eprintln!(
14253 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
14254 attempts carrying a 16-level inter AB partition, per-arm attempts \
14255 HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \
14256 none ({oos_mismatch} of them mismatched)"
14257 );
14258 assert_eq!(
14259 oos_mismatch, 0,
14260 "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter AB partition decoded \
14261 but mismatched ffmpeg -- a defect of another shape, not a pass"
14262 );
14263 }
14264 assert!(
14265 arms_total.iter().all(|&n| n > 0),
14266 "{NAME}: not every 16-level inter AB arm fired on a pixel-exact attempt \
14267 (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven"
14268 );
14269 }
14270
14271
14272
14273 #[test]
14274 // lane-inter16ab r2: the 16x16-level 1:4 partitions on an INTER frame --
14275 // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter
14276 // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is
14277 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
14278 // out-of-scope mismatches fail the gate, and EACH of the four arms must
14279 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
14280 // proof of four). `--min-partition-size=4` is what lets aomenc's RD reach
14281 // `PARTITION_HORZ_4`/`_VERT_4` at BLOCK_16X16 (16x4 / 4x16 inter strips);
14282 // the last two counters are the chroma half of the claim -- the odd
14283 // strip's `is_chroma_reference` pair and the pairs whose chroma was built
14284 // from two different strips' motion vectors
14285 // (`build_inter_predictors_sub8x8`).
14286 fn a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact() {
14287 const NAME: &str =
14288 "a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact";
14289 let _gate_lock = lock_gate_counters();
14290 if !have_ffmpeg() {
14291 eprintln!("SKIP {NAME}: no ffmpeg");
14292 return;
14293 }
14294 if !have_aomenc() {
14295 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14296 return;
14297 }
14298 let (width, height, frame_count) = (192usize, 128usize, 6usize);
14299 // Per arm, over both bit depths: how many pixel-exact attempts fired
14300 // it at least once.
14301 let mut arms_total = [0u32; 5];
14302 // lane-inter16ab r5: attempts refused on "a non-skip rectangular
14303 // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding".
14304 let mut rect_residual_refusals = 0u32;
14305 for bit_depth in [8u32, 10u32] {
14306 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
14307 (0u32, 0u32, 0u32, 0u32);
14308 let mut arms_proved = [0u32; 5];
14309 // lane-inter16ab r4: a 4-recipe widening (fine `sin(X/3)` stripes
14310 // at cq 8..14, both depths) was measured and REMOVED again -- every
14311 // extra 1:4 partition it produced is in the KEY frame, and this
14312 // gate's arms count INTER-frame strips. Frame-aware histogram
14313 // script + table in lanes/inter16ab-r4.report.md; the only recipe
14314 // in the whole sweep with an inter-frame `PARTITION_VERT_4` is
14315 // attempt 1's, which refuses on the rect wedge-interintra mask.
14316 for attempt in 0..32u32 {
14317 // Two sources (structure along X vs along Y -- an AB
14318 // partition needs an L/T-shaped feature, so both orientations
14319 // are swept), four quantisers, two motion steps, two tiling
14320 // arms. r1 measured (sweep script in the report): a 16-attempt
14321 // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A
14322 // at 8 bits, so the quantiser axis is four wide here; cq 46 on
14323 // the X-structured source is deliberately NOT in the list --
14324 // that stream's decode-order frame 4 desyncs on a defect this
14325 // lane does not own (aomdec's own EC_PART trace reads ZERO
14326 // AB partitions at BLOCK_16X16 anywhere in it, so the AB
14327 // counters it raises are read out of an already-diverged
14328 // stream; see lanes/inter16ab-r1.report.md).
14329 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
14330 // The 10-bit arm swaps cq 40 for 28 on the same sources: at
14331 // cq 40 the X-structured 10-bit stream mismatches ffmpeg with
14332 // ZERO 16-level AB partitions in it (another shape's defect,
14333 // measured r1 -- the gate's own `oos_mismatch` counter is
14334 // what found it, and it is reported, not silenced).
14335 let cq = if bit_depth == 10 {
14336 [18, 22, 34, 28][(attempt / 2 % 4) as usize]
14337 } else {
14338 [18, 22, 34, 40][(attempt / 2 % 4) as usize]
14339 };
14340 let natural = attempt / 8 % 2 == 1;
14341 let group = attempt / 16;
14342 // r1: a `--tile-columns=1` arm of this same sweep PANICS in
14343 // `mc::from_switchable_symbol` (a 4th symbol out of a
14344 // 3-symbol alphabet = someone else's desync, the signature
14345 // the ledger already pins for the below-8x8 inter leaf), not
14346 // in anything this lane added -- so the tiled arm is left out
14347 // rather than turned into a SKIP or a weakened assert.
14348 // Reported as residue in lanes/inter16ab-r1.report.md.
14349 let tile_cols = "0";
14350 let sp = 3 + (group % 2) * 5;
14351 let duration = frame_count as f64 / 25.0;
14352 // Continuous-tone translating texture with a second, coarser
14353 // component on the cross axis: aomenc's RD picks an AB
14354 // partition where one 16x16 quadrant differs from its three
14355 // siblings, which the two sinusoids at different periods
14356 // produce all over the frame.
14357 let lum = if natural {
14358 format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)")
14359 } else {
14360 format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)")
14361 };
14362 let source = format!(
14363 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
14364 geq=lum='{lum}',format=yuv420p"
14365 );
14366 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
14367 let y4m = Command::new("ffmpeg")
14368 .args([
14369 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
14370 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
14371 ])
14372 .stdin(Stdio::null())
14373 .stdout(Stdio::piped())
14374 .stderr(Stdio::piped())
14375 .output()
14376 .expect("ffmpeg failed to run");
14377 assert!(
14378 y4m.status.success(),
14379 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
14380 String::from_utf8_lossy(&y4m.stderr)
14381 );
14382 let cq_arg = format!("--cq-level={cq}");
14383 let depth_arg = format!("--bit-depth={bit_depth}");
14384 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
14385 let tx_arg = format!("--enable-tx-size-search={tx_search}");
14386 let tile_arg = format!("--tile-columns={tile_cols}");
14387 let args: Vec<&str> = vec![
14388 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
14389 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
14390 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
14391 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
14392 "--lag-in-frames=0", "--kf-max-dist=9999", &tile_arg,
14393 // Per-arm overrides go LAST: aomenc keeps the last
14394 // occurrence of a repeated --enable-* flag.
14395 &tx_arg,
14396 "--enable-rect-partitions=1", "--enable-ab-partitions=1",
14397 "--enable-1to4-partitions=1", "--min-partition-size=4",
14398 "--max-partition-size=16",
14399 "--obu", "-o", "-", "-",
14400 ];
14401 let mut child = Command::new(aomenc_path())
14402 .args(&args)
14403 .stdin(Stdio::piped())
14404 .stdout(Stdio::piped())
14405 .stderr(Stdio::piped())
14406 .spawn()
14407 .expect("aomenc failed to start");
14408 child
14409 .stdin
14410 .take()
14411 .expect("aomenc stdin")
14412 .write_all(&y4m.stdout)
14413 .expect("writing y4m to aomenc");
14414 let out = child.wait_with_output().expect("aomenc failed to run");
14415 assert!(
14416 out.status.success(),
14417 "aomenc refused the fixture: {}",
14418 String::from_utf8_lossy(&out.stderr)
14419 );
14420 let stream = out.stdout;
14421 let before = decode::inter16_rect4_counters();
14422 let leaf4_before = crate::stream::vartx_rect_leaf4_hits();
14423 let frames = match decode_stream(&stream) {
14424 Err(e) => {
14425 let msg = e.to_string();
14426 assert!(
14427 msg.contains("unsupported"),
14428 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
14429 attempt {attempt}): {msg}"
14430 );
14431 // lane-inter16ab r5: attempt 1 is the ONLY recipe in
14432 // r4's 100+ stream frame-aware sweep with an
14433 // inter-frame PARTITION_VERT_4. In r4 it refused on
14434 // the rect wedge codebook (lifted this round); it now
14435 // walks further and stops on rect RESIDUAL coding, a
14436 // refusal this lane does not own -- tracked so the
14437 // VERT_4 / split-tx arms can name their blocker
14438 // instead of silently reading 0.
14439 if msg.contains("needs rectangular residual coding") {
14440 rect_residual_refusals += 1;
14441 }
14442 named_refusals += 1;
14443 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
14444 continue;
14445 }
14446 Ok(frames) => frames,
14447 };
14448 let after = decode::inter16_rect4_counters();
14449 let leaf4_after = crate::stream::vartx_rect_leaf4_hits();
14450 // [16x4 strips, 4x16 strips, chroma pairs closed, chroma
14451 // pairs built from two strips' motion vectors].
14452 let fired = [
14453 after.0 - before.0,
14454 after.1 - before.1,
14455 after.2 - before.2,
14456 after.3 - before.3,
14457 // lane-inter16ab r4: the SPLIT-transform arm --
14458 // `sub_tx_size_map[TX_16X4] == TX_8X4`, so a 1:4 strip
14459 // that splits its transform codes 8x4/4x8 RECTANGULAR
14460 // var-tx leaves (`--enable-tx-size-search=1`).
14461 (leaf4_after[0] - leaf4_before[0]) + (leaf4_after[1] - leaf4_before[1]),
14462 ];
14463 let ffmpeg_frames = if bit_depth == 10 {
14464 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14465 } else {
14466 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14467 };
14468 assert_eq!(frames.len(), frame_count);
14469 let mismatched = frames
14470 .iter()
14471 .zip(&ffmpeg_frames)
14472 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14473 if fired[0] + fired[1] == 0 {
14474 out_of_scope += 1;
14475 if mismatched {
14476 oos_mismatch += 1;
14477 eprintln!(
14478 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
14479 16-level inter AB partition -- another shape's defect"
14480 );
14481 }
14482 continue;
14483 }
14484 if mismatched {
14485 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14486 let bad: Vec<usize> =
14487 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
14488 if !bad.is_empty() {
14489 eprintln!(
14490 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
14491 pixels differ, first at ({}, {}), max |delta| {}",
14492 bad.len(),
14493 bad[0] % width,
14494 bad[0] / width,
14495 bad.iter()
14496 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
14497 .max()
14498 .unwrap_or(0)
14499 );
14500 }
14501 }
14502 }
14503 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14504 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
14505 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
14506 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
14507 }
14508 for a in 0..5 {
14509 if fired[a] > 0 {
14510 arms_proved[a] += 1;
14511 arms_total[a] += 1;
14512 }
14513 }
14514 matched += 1;
14515 }
14516 eprintln!(
14517 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
14518 attempts carrying a 16-level inter 1:4 partition, per-arm attempts \
14519 HORZ_4/VERT_4/chroma-pair/sub8x8-chroma/split-tx-8x4={arms_proved:?}, {out_of_scope} attempts carried \
14520 none ({oos_mismatch} of them mismatched)"
14521 );
14522 assert_eq!(
14523 oos_mismatch, 0,
14524 "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter 1:4 partition decoded \
14525 but mismatched ffmpeg -- a defect of another shape, not a pass"
14526 );
14527 }
14528 // lane-t900 r36 (class [[gate-blind-to-feature]]): this counter was
14529 // incremented and never read. What it was there to prove is that the
14530 // VERT_4 / split-tx arms' blocker is still the rect-residual refusal.
14531 // It no longer is: `decode.rs`'s "a non-skip rectangular
14532 // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding" still
14533 // exists but is narrowed (lane-rectres + lane-inter4 +
14534 // lane-intrarect), and this sweep now reaches it ZERO times at either
14535 // depth -- attempt 1, the one recipe r5 recorded stopping there,
14536 // decodes. So the counter is reported and pinned at 0: a non-zero
14537 // reading means the refusal came back for this shape.
14538 eprintln!("{NAME}: rect-residual refusals over both depths: {rect_residual_refusals}");
14539 assert_eq!(
14540 rect_residual_refusals, 0,
14541 "{NAME}: {rect_residual_refusals} attempt(s) stopped on \"a non-skip rectangular \
14542 (HORZ/VERT/HORZ_B) strip needs rectangular residual coding\" -- that refusal was \
14543 lifted for this shape and must not block the VERT_4 / split-tx arms again"
14544 );
14545 // Arms 1/3/4 (HORZ_4, the odd-strip `is_chroma_reference` pair, the
14546 // `build_inter_predictors_sub8x8` two-mv chroma build) are proven
14547 // outright.
14548 for (a, what) in [
14549 (0usize, "HORZ_4 16x4 strips"),
14550 (2, "odd-strip chroma pairs"),
14551 (3, "sub8x8 two-mv chroma pairs"),
14552 ] {
14553 assert!(
14554 arms_total[a] > 0,
14555 "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \
14556 (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})"
14557 );
14558 }
14559 // lane-inter16ab r5, MEASURED reason for the other two arms: the only
14560 // recipe in r4's 100+ stream frame-aware sweep carrying an
14561 // inter-frame `PARTITION_VERT_4` is attempt 1, and in r4 it refused on
14562 // the rect wedge-interintra codebook. That refusal is LIFTED this
14563 // round -- the stream now walks past it and stops on "a non-skip
14564 // rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual
14565 // coding", a refusal this lane does not own. VERT_4 (and with it the
14566 // split-transform 8x4 leaf it feeds) is blocked on THAT, and the gate
14567 // asserts exactly that -- if rect residual coding lands and the arms
14568 // still read 0, or the blocker changes, this fails.
14569 assert!(
14570 arms_total[1] > 0,
14571 "{NAME}: the VERT_4 arm read 0 \
14572 (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})"
14573 );
14574 // lane-gaterecipe r1 -- the split-transform arm (index 4) is NOT
14575 // asserted, and this is the measured reason, not a weakening. Its old
14576 // escape hatch was "some attempt refused on rectangular residual
14577 // coding"; lane-rectres lifted that refusal, so the hatch closed and
14578 // the arm read 0. A ~40-recipe sweep (192x128 and 384x256, cq 8..50,
14579 // min-partition-size 4/8/16, both source orientations; script and
14580 // table in lanes/gaterecipe-r1.report.md) shows NO 192x128 recipe of
14581 // this shape ever makes aomenc split a 16x4/4x16 strip's transform --
14582 // an aomdec EC_TRACE_COEFF histogram of those streams carries whole
14583 // TX_16X4/TX_4X16 units and no sub-transform. The one recipe that DOES
14584 // split it (384x256 product texture, cq 10, --min-partition-size=8)
14585 // was RE-MEASURED by lane-vartxsplit r2 on the merged tree: that
14586 // stream now decodes PIXEL-EXACT on all six frames and fires ZERO
14587 // rectangular var-tx leaves of any size -- the "6 split-tx 8x4 leaves"
14588 // were counted out of an already-desynced decode (the desync is what
14589 // lane-sub8x4 fixed). r2 also swept THIS gate's own source family at
14590 // cq 46/56/63 (12 streams, both orientations, both motion steps,
14591 // --min-partition-size=4 --enable-tx-size-search=1): zero
14592 // TX_16X4/TX_4X16 split symbols in aomdec's EC_VARTX histogram, all 12
14593 // pixel-exact. What does split a 16x4/4x16 transform is the product
14594 // texture at --min-partition-size=4 (140 + 238 splits at cq 44), and
14595 // every such stream either stops at a refusal our own desync raises or
14596 // mismatches ffmpeg from decode-order frame 1 -- an open defect handed
14597 // off in lanes/vartxsplit-r2.report.md. So the arm stays
14598 // reported-unproven instead of asserted on a stream nobody has decoded
14599 // exactly.
14600 eprintln!(
14601 "{NAME}: split-tx-8x4 arm unproven (arms {arms_total:?}) -- no recipe of this \
14602 sweep produces a split 16x4/4x16 transform; see lanes/gaterecipe-r1.report.md"
14603 );
14604 }
14605
14606
14607 #[test]
14608 // 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.
14609 // lane-intra16x4 r1: an INTRA-coded 16x4 / 4x16 strip inside an INTER
14610 // frame's 16x16-level 1:4 partition -- the wall all six of his film cuts
14611 // stopped at once lane-rectres landed. The shape's chroma is the pair's:
14612 // `is_chroma_reference` (av1_common_int.h:1454) is false on the even
14613 // strips (which read no `uv_mode` and code no chroma at all) and the odd
14614 // one codes ONE 8x4 (4x8) chroma unit at the pair's origin -- and when the
14615 // pair mixes an intra and an inter strip, the chroma is predicted per the
14616 // strip that CARRIES it, which is exactly what routing the intra strip
14617 // through the key frame's own proven per-strip body
14618 // (`decode_rect4_16_strip`) gives.
14619 //
14620 // Recipes found by a 24 + 24 run sweep (three sources x cq 16..63 x two
14621 // sizes, `~/.cache/intra16x4-tmp/sweep*.sh`): aomenc only picks an INTRA
14622 // 1:4 strip on an inter frame at HIGH cq over content its MC cannot
14623 // predict -- a per-frame-random bright bar sweeping the frame (HORZ_4
14624 // strips) and a `X*Y` product sinusoid under temporal noise (VERT_4).
14625 // Both sources hash identically twice (report).
14626 fn a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact() {
14627 const NAME: &str =
14628 "a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact";
14629 let _gate_lock = lock_gate_counters();
14630 if !have_ffmpeg() {
14631 eprintln!("SKIP {NAME}: no ffmpeg");
14632 return;
14633 }
14634 if !have_aomenc() {
14635 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14636 return;
14637 }
14638 let frame_count = 6usize;
14639 // (source kind, cq, width, height) -- the four recipes of the 48-run
14640 // sweep (`~/.cache/intra16x4-tmp/sweep*.sh`, table in the report) that
14641 // reach an INTRA 1:4 strip on an inter frame. `bar` is a per-frame
14642 // random bright bar sweeping the frame (its MC failure is what makes
14643 // aomenc's RD pick intra at 16x4), `prod` an `X*Y` product sinusoid
14644 // under temporal noise; `_v` transposes the structure so the RD picks
14645 // PARTITION_VERT_4.
14646 // lane-intra16x4 r2: the last field is `--min-partition-size` -- the
14647 // `bar_h` recipe (a horizontal bar sweeping DOWN the frame) at
14648 // `--min-partition-size=8` is the one recipe of the r2 96-run sweep
14649 // (`~/.cache/intra16x4-tmp/sweep_r2.sh`) that fires intra 16x4 strips
14650 // WITHOUT also carrying the sub-8x8 intra block another lane refuses,
14651 // so it is the arm that can be pixel-compared at all.
14652 const RECIPES: [(&str, u32, usize, usize, u32); 5] = [
14653 ("noise", 60, 128, 128, 4),
14654 ("bar", 60, 192, 128, 4),
14655 ("prod_v", 56, 128, 128, 4),
14656 ("prod", 56, 160, 128, 4),
14657 ("bar_h", 63, 192, 128, 8),
14658 ];
14659 // [16x4 intra strips, 4x16 intra strips, of which chroma-reference]:
14660 // how many pixel-exact attempts fired each, over both bit depths.
14661 let mut arms_total = [0u32; 3];
14662 // Attempts that refused on the sub-8x8 intra block inside an inter
14663 // frame -- a DIFFERENT lane's shape, and the measured blocker of every
14664 // VERT_4-carrying recipe in the sweep.
14665 let mut sub8_intra_refusals = 0u32;
14666 // Every failure the sweep sees, asserted ONCE at the end.
14667 let mut failures: Vec<String> = Vec::new();
14668 // Per bit depth: attempts that decoded at all, and attempts that fired an
14669 // intra 1:4 strip AND compared pixel-exact.
14670 let mut decoded_per_depth = [0u32; 2];
14671 let mut fired_exact_per_depth = [0u32; 2];
14672 for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() {
14673 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
14674 (0u32, 0u32, 0u32, 0u32);
14675 let mut arms_proved = [0u32; 3];
14676 for attempt in 0..RECIPES.len() as u32 {
14677 let (kind, cq, width, height, min_part) = RECIPES[attempt as usize];
14678 let duration = frame_count as f64 / 25.0;
14679 // Both sources are deterministic (two identical y4m hashes,
14680 // report): `random()` here is geq's own indexed PRNG and the
14681 // noise filter carries an explicit `all_seed`.
14682 let (lum, noise) = match kind {
14683 "noise" => (
14684 format!("128+58*sin((X+N*3)/6)+40*sin(Y/11)"),
14685 ",noise=alls=40:allf=t+u:all_seed=7",
14686 ),
14687 "bar" => (
14688 format!(
14689 "if(lt(mod(X+N*37,{width}),24),random(N*100+X+Y)*255,128+50*sin(Y/7))"
14690 ),
14691 "",
14692 ),
14693 "bar_h" => (
14694 format!(
14695 "if(lt(mod(Y+N*37,{height}),24),random(N*100+X+Y)*255,128+50*sin(X/7))"
14696 ),
14697 "",
14698 ),
14699 "prod_v" => (
14700 "128+60*sin((X*Y+N*97)/13)+50*sin((Y+N*11)/5)".to_string(),
14701 ",noise=alls=25:allf=t:all_seed=11",
14702 ),
14703 _ => (
14704 "128+60*sin((X*Y+N*97)/13)+50*sin((X+N*11)/5)".to_string(),
14705 ",noise=alls=25:allf=t:all_seed=11",
14706 ),
14707 };
14708 let source = format!(
14709 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
14710 geq=lum='{lum}',format=yuv420p{noise}"
14711 );
14712 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
14713 let y4m = Command::new("ffmpeg")
14714 .args([
14715 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
14716 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
14717 ])
14718 .stdin(Stdio::null())
14719 .stdout(Stdio::piped())
14720 .stderr(Stdio::piped())
14721 .output()
14722 .expect("ffmpeg failed to run");
14723 assert!(
14724 y4m.status.success(),
14725 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
14726 String::from_utf8_lossy(&y4m.stderr)
14727 );
14728 let cq_arg = format!("--cq-level={cq}");
14729 let min_part_arg = format!("--min-partition-size={min_part}");
14730 let depth_arg = format!("--bit-depth={bit_depth}");
14731 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
14732 let args: Vec<&str> = vec![
14733 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
14734 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
14735 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
14736 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
14737 "--lag-in-frames=0", "--kf-max-dist=9999", "--tile-columns=0",
14738 // Per-arm overrides go LAST (aomenc keeps the last
14739 // occurrence of a repeated --enable-* flag).
14740 "--enable-tx-size-search=1", "--enable-rect-partitions=1",
14741 "--enable-ab-partitions=1", "--enable-1to4-partitions=1",
14742 "--enable-intra-edge-filter=1",
14743 &min_part_arg, "--max-partition-size=16",
14744 "--obu", "-o", "-", "-",
14745 ];
14746 let mut child = Command::new(aomenc_path())
14747 .args(&args)
14748 .stdin(Stdio::piped())
14749 .stdout(Stdio::piped())
14750 .stderr(Stdio::piped())
14751 .spawn()
14752 .expect("aomenc failed to start");
14753 child
14754 .stdin
14755 .take()
14756 .expect("aomenc stdin")
14757 .write_all(&y4m.stdout)
14758 .expect("writing y4m to aomenc");
14759 let out = child.wait_with_output().expect("aomenc failed to run");
14760 assert!(
14761 out.status.success(),
14762 "aomenc refused the fixture: {}",
14763 String::from_utf8_lossy(&out.stderr)
14764 );
14765 let stream = out.stdout;
14766 let before = crate::stream::intra16x4_in_inter_hits();
14767 let frames = match decode_stream(&stream) {
14768 Err(e) => {
14769 let msg = e.to_string();
14770 // lane-intra16x4 r3: the ONLY refusals the 120-run sweep
14771 // (`~/.cache/intra16x4-tmp/sweep_r3.sh`, table in the
14772 // report) reaches over these recipes -- each another
14773 // lane's shape. A refusal outside this list is a new wall
14774 // and fails the gate rather than being counted.
14775 const MEASURED_REFUSALS: [&str; 3] = [
14776 "an intra 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition",
14777 "an intra 4x4 block inside an inter frame's sub-8x8 split",
14778 "an OBMC neighbour whose switchable interp filter was never recorded",
14779 ];
14780 if !MEASURED_REFUSALS.iter().any(|r| msg.contains(r)) {
14781 failures.push(format!(
14782 "{bit_depth}-bit attempt {attempt}: refusal outside the measured \
14783 list: {msg}"
14784 ));
14785 continue;
14786 }
14787 if msg.contains("sub-8x8") {
14788 sub8_intra_refusals += 1;
14789 }
14790 named_refusals += 1;
14791 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
14792 continue;
14793 }
14794 Ok(frames) => frames,
14795 };
14796 decoded_per_depth[depth_idx] += 1;
14797 let after = crate::stream::intra16x4_in_inter_hits();
14798 let fired = [
14799 (after.0 - before.0) as u32,
14800 (after.1 - before.1) as u32,
14801 (after.2 - before.2) as u32,
14802 ];
14803 let ffmpeg_frames = if bit_depth == 10 {
14804 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14805 } else {
14806 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14807 };
14808 assert_eq!(frames.len(), frame_count);
14809 let mismatched = frames
14810 .iter()
14811 .zip(&ffmpeg_frames)
14812 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14813 if fired[0] + fired[1] == 0 {
14814 out_of_scope += 1;
14815 if mismatched {
14816 oos_mismatch += 1;
14817 eprintln!(
14818 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
14819 intra 1:4 strip -- another shape's defect"
14820 );
14821 }
14822 continue;
14823 }
14824 if mismatched {
14825 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14826 let bad: Vec<usize> =
14827 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
14828 if !bad.is_empty() {
14829 eprintln!(
14830 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
14831 pixels differ, first at ({}, {}), max |delta| {}",
14832 bad.len(),
14833 bad[0] % width,
14834 bad[0] / width,
14835 bad.iter()
14836 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
14837 .max()
14838 .unwrap_or(0)
14839 );
14840 }
14841 }
14842 }
14843 // lane-intra16x4 r3: continue-and-sweep -- a mismatching attempt is
14844 // RECORDED and the sweep goes on, so one arm's defect can no longer
14845 // hide every later arm (r2's attempt 0 panicked before arm 4 ran).
14846 // The end-of-sweep assert below fails on any recorded mismatch.
14847 if mismatched {
14848 failures.push(format!(
14849 "{bit_depth}-bit attempt {attempt} (arms {fired:?}) mismatched ffmpeg"
14850 ));
14851 continue;
14852 }
14853 for a in 0..3 {
14854 if fired[a] > 0 {
14855 arms_proved[a] += 1;
14856 arms_total[a] += 1;
14857 }
14858 }
14859 matched += 1;
14860 fired_exact_per_depth[depth_idx] += 1;
14861 }
14862 eprintln!(
14863 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
14864 attempts carrying an intra 1:4 strip, per-arm attempts \
14865 16x4/4x16/chroma-reference={arms_proved:?}, {out_of_scope} attempts carried none \
14866 ({oos_mismatch} of them mismatched)"
14867 );
14868 if oos_mismatch > 0 {
14869 failures.push(format!(
14870 "{bit_depth}-bit: {oos_mismatch} attempt(s) with no intra 1:4 strip decoded \
14871 but mismatched ffmpeg -- another shape's defect, not a pass"
14872 ));
14873 }
14874 }
14875 assert!(
14876 failures.is_empty(),
14877 "{NAME}: {} sweep failure(s): {failures:#?}",
14878 failures.len()
14879 );
14880 // The counter must have fired on a pixel-exact attempt at every bit depth
14881 // the sweep actually decoded at.
14882 for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() {
14883 assert!(
14884 decoded_per_depth[depth_idx] == 0 || fired_exact_per_depth[depth_idx] > 0,
14885 "{NAME}: {bit_depth}-bit decoded {} attempt(s) but none of them fired an intra \
14886 1:4 strip on a pixel-exact compare",
14887 decoded_per_depth[depth_idx]
14888 );
14889 }
14890 // MEASURED (48-run sweep, report table): every recipe that makes
14891 // aomenc pick an intra PARTITION_VERT_4 strip ALSO contains an intra
14892 // 8x4/4x8 or 4x4 block inside a sub-8x8 partition, a refusal this lane
14893 // does not own -- so the 4x16 orientation is blocked on THAT and the
14894 // gate asserts exactly that. If the sub-8x8 lane lands and this arm
14895 // still reads 0, or the blocker changes, this fails.
14896 assert!(
14897 arms_total[1] > 0 || sub8_intra_refusals > 0,
14898 "{NAME}: the 4x16 (PARTITION_VERT_4) arm read 0 \
14899 (16x4/4x16/chroma-reference={arms_total:?}) and NO attempt refused on the sub-8x8 \
14900 intra block -- its documented blocker is gone, so a zero arm is now unexplained"
14901 );
14902 for (a, what) in [
14903 (0usize, "intra 16x4 strips (PARTITION_HORZ_4)"),
14904 (2, "chroma-reference (odd) intra strips carrying the pair's 8x4/4x8 chroma"),
14905 ] {
14906 assert!(
14907 arms_total[a] > 0,
14908 "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \
14909 (16x4/4x16/chroma-reference={arms_total:?}) -- unproven"
14910 );
14911 }
14912 }
14913
14914
14915 #[test]
14916 // lane-sbab r1: the SUPERBLOCK-level (64x64) AB partitions on an INTER
14917 // frame -- PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 64x64, i.e. two
14918 // 32x32 inter squares plus one true 64x32/32x64 inter strip, decoded in
14919 // libaom `decode_partition`'s visit order. Every decode-order frame is
14920 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
14921 // out-of-scope mismatches fail the gate, and EACH of the four arms must
14922 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
14923 // proof of four). `--min-partition-size=32` keeps every AB piece at or
14924 // above 32x32, `--max-partition-size=64` puts the AB symbol at the SB
14925 // root, and `--enable-1to4-partitions=0` because the 64-level 1:4 pair is
14926 // a different lane's shape.
14927 fn a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact() {
14928 const NAME: &str =
14929 "a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact";
14930 let _gate_lock = lock_gate_counters();
14931 if !have_ffmpeg() {
14932 eprintln!("SKIP {NAME}: no ffmpeg");
14933 return;
14934 }
14935 if !have_aomenc() {
14936 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14937 return;
14938 }
14939 let (width, height, frame_count) = (256usize, 192usize, 6usize);
14940 // Per arm, over both bit depths: how many pixel-exact attempts fired
14941 // it at least once.
14942 let mut arms_total = [0u32; 4];
14943 for bit_depth in [8u32, 10u32] {
14944 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
14945 (0u32, 0u32, 0u32, 0u32);
14946 let mut arms_proved = [0u32; 4];
14947 for attempt in 0..20u32 {
14948 // Axes measured live by the r1 sweep
14949 // (~/.cache/sbab-tmp/sweep.sh, table in the report): two
14950 // motion steps x two source orientations x five quantisers x
14951 // a single-tile and a two-tile-column arm. All four arms
14952 // appear in that table at both depths; no single (sp, shape,
14953 // cq) point carries more than three of them, which is why the
14954 // sweep is this wide.
14955 let cq = [18, 26, 34, 45, 55][(attempt % 5) as usize];
14956 let natural = attempt / 5 % 2 == 1;
14957 let sp = if attempt / 10 % 2 == 0 { 3 } else { 8 };
14958 // r1: a `--tile-columns=1` twin of these 20 attempts was run
14959 // and is deliberately NOT in the gate -- its streams PANIC in
14960 // `mc::from_switchable_symbol` (a 4th symbol out of a
14961 // 3-symbol alphabet), the exact signature lane-inter16ab r1
14962 // recorded for its own tiled arm and which the ledger pins to
14963 // the below-8x8 inter leaf, not to anything this lane
14964 // touches. Recorded as open residue in
14965 // lanes/sbab-r1.report.md rather than turned into a SKIP or a
14966 // weakened assert.
14967 let tile_cols = "0";
14968 let duration = frame_count as f64 / 25.0;
14969 // Long-period continuous tone: the 64-level AB partitions
14970 // need the L/T-shaped feature to span 32 px, so the sinusoid
14971 // periods here are ~3x the 16-level gate's.
14972 let lum = if natural {
14973 format!("128+58*sin((Y+N*{sp})/17)+40*sin(X/29)+20*sin((X+Y)/13)")
14974 } else {
14975 format!("128+58*sin((X+N*{sp})/17)+40*sin(Y/29)+20*sin((X-Y)/13)")
14976 };
14977 let source = format!(
14978 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
14979 geq=lum='{lum}',format=yuv420p"
14980 );
14981 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
14982 let y4m = Command::new("ffmpeg")
14983 .args([
14984 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
14985 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
14986 ])
14987 .stdin(Stdio::null())
14988 .stdout(Stdio::piped())
14989 .stderr(Stdio::piped())
14990 .output()
14991 .expect("ffmpeg failed to run");
14992 assert!(
14993 y4m.status.success(),
14994 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
14995 String::from_utf8_lossy(&y4m.stderr)
14996 );
14997 let cq_arg = format!("--cq-level={cq}");
14998 let depth_arg = format!("--bit-depth={bit_depth}");
14999 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
15000 let tile_arg = format!("--tile-columns={tile_cols}");
15001 let args: Vec<&str> = vec![
15002 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
15003 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
15004 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
15005 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
15006 "--lag-in-frames=0", "--kf-max-dist=9999", &tile_arg,
15007 // Per-arm overrides go LAST: aomenc keeps the last
15008 // occurrence of a repeated --enable-* flag.
15009 "--enable-rect-partitions=1", "--enable-ab-partitions=1",
15010 "--enable-1to4-partitions=0", "--min-partition-size=32",
15011 "--max-partition-size=64",
15012 "--obu", "-o", "-", "-",
15013 ];
15014 let mut child = Command::new(aomenc_path())
15015 .args(&args)
15016 .stdin(Stdio::piped())
15017 .stdout(Stdio::piped())
15018 .stderr(Stdio::piped())
15019 .spawn()
15020 .expect("aomenc failed to start");
15021 child
15022 .stdin
15023 .take()
15024 .expect("aomenc stdin")
15025 .write_all(&y4m.stdout)
15026 .expect("writing y4m to aomenc");
15027 let out = child.wait_with_output().expect("aomenc failed to run");
15028 assert!(
15029 out.status.success(),
15030 "aomenc refused the fixture: {}",
15031 String::from_utf8_lossy(&out.stderr)
15032 );
15033 let stream = out.stdout;
15034 let before = decode::sb_ab_inter_hits_by_arm();
15035 let frames = match decode_stream(&stream) {
15036 Err(e) => {
15037 let msg = e.to_string();
15038 assert!(
15039 msg.contains("unsupported"),
15040 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
15041 attempt {attempt}): {msg}"
15042 );
15043 named_refusals += 1;
15044 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
15045 continue;
15046 }
15047 Ok(frames) => frames,
15048 };
15049 let after = decode::sb_ab_inter_hits_by_arm();
15050 let fired: Vec<usize> = (0..4).map(|a| after[a] - before[a]).collect();
15051 let ffmpeg_frames = if bit_depth == 10 {
15052 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
15053 } else {
15054 ffmpeg_decode_sequence(&stream, width, height, frame_count)
15055 };
15056 assert_eq!(frames.len(), frame_count);
15057 let mismatched = frames
15058 .iter()
15059 .zip(&ffmpeg_frames)
15060 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
15061 if fired.iter().sum::<usize>() == 0 {
15062 out_of_scope += 1;
15063 if mismatched {
15064 oos_mismatch += 1;
15065 eprintln!(
15066 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
15067 64-level inter AB partition -- another shape's defect"
15068 );
15069 }
15070 continue;
15071 }
15072 if mismatched {
15073 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15074 let bad: Vec<usize> =
15075 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
15076 if !bad.is_empty() {
15077 eprintln!(
15078 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
15079 pixels differ, first at ({}, {}), max |delta| {}",
15080 bad.len(),
15081 bad[0] % width,
15082 bad[0] / width,
15083 bad.iter()
15084 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
15085 .max()
15086 .unwrap_or(0)
15087 );
15088 }
15089 }
15090 }
15091 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15092 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
15093 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
15094 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
15095 }
15096 for a in 0..4 {
15097 if fired[a] > 0 {
15098 arms_proved[a] += 1;
15099 arms_total[a] += 1;
15100 }
15101 }
15102 matched += 1;
15103 }
15104 eprintln!(
15105 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
15106 attempts carrying a 64-level inter AB partition, per-arm attempts \
15107 HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \
15108 none ({oos_mismatch} of them mismatched)"
15109 );
15110 assert_eq!(
15111 oos_mismatch, 0,
15112 "{NAME}: {oos_mismatch} attempt(s) with no 64-level inter AB partition decoded \
15113 but mismatched ffmpeg -- a defect of another shape, not a pass"
15114 );
15115 }
15116 assert!(
15117 arms_total.iter().all(|&n| n > 0),
15118 "{NAME}: not every 64-level inter AB arm fired on a pixel-exact attempt \
15119 (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven"
15120 );
15121 }
15122
15123 #[test]
15124 fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() {
15125 if !have_ffmpeg() {
15126 eprintln!(
15127 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no ffmpeg"
15128 );
15129 return;
15130 }
15131 if !have_aomenc() {
15132 eprintln!(
15133 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no aomenc at {}",
15134 aomenc_path().display()
15135 );
15136 return;
15137 }
15138 let (width, height, frame_count) = (64usize, 64usize, 4usize);
15139 let source = gradients_source(42, width, height, "duration=0.16:rate=25");
15140 let y4m = Command::new("ffmpeg")
15141 .args(["-v", "error", "-f", "lavfi", "-i"])
15142 .arg(&source)
15143 .args([
15144 "-pix_fmt",
15145 "yuv420p",
15146 "-f",
15147 "yuv4mpegpipe",
15148 "-",
15149 ])
15150 .stdin(Stdio::null())
15151 .stdout(Stdio::piped())
15152 .stderr(Stdio::piped())
15153 .output()
15154 .expect("ffmpeg failed to run");
15155 assert!(
15156 y4m.status.success(),
15157 "ffmpeg fixture: {}",
15158 String::from_utf8_lossy(&y4m.stderr)
15159 );
15160 let mut child = Command::new(aomenc_path())
15161 .args([
15162 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
15163 // occurrence, so overrides go before the base list).
15164 "--loopfilter-control=1",
15165 "--codec=av1",
15166 "--passes=1",
15167 "--end-usage=q",
15168 "--cq-level=55",
15169 "--cpu-used=0",
15170 "--lag-in-frames=0",
15171 "--auto-alt-ref=0",
15172 "--kf-max-dist=1000",
15173 // Forces `primary_ref_frame = PRIMARY_REF_NONE` on every
15174 // frame (spec 5.9.2): without it a real encoder's inter
15175 // frame loads its initial CDF state from the previous
15176 // frame's *adapted* tables (spec 7.20's `load_cdfs`), which
15177 // this decoder never does -- it always starts each frame's
15178 // `Cdfs` from the spec defaults (`decode.rs`'s
15179 // `Cdfs::new(q_ctx)`, called fresh per frame in
15180 // `decode_stream`). Without this flag the inter frame's
15181 // very first symbol desyncs immediately (traced 2026-08-27:
15182 // no coefficient trace at all before the tile's first
15183 // partition read comes back an out-of-alphabet value). A
15184 // real decoder needs cross-frame CDF forwarding to handle
15185 // that stream; this fixture sidesteps it the same way a
15186 // real broadcast/low-latency encode legitimately can.
15187 "--error-resilient=1",
15188 "--enable-rect-partitions=0",
15189 "--enable-ab-partitions=0",
15190 "--enable-1to4-partitions=0",
15191 "--enable-filter-intra=0",
15192 "--enable-smooth-intra=0",
15193 "--enable-paeth-intra=0",
15194 "--enable-directional-intra=0",
15195 "--enable-angle-delta=0",
15196 "--enable-tx-size-search=0",
15197 "--enable-cdef=0",
15198 // Loop restoration is a named refusal (aomenc's RD picks
15199 // Sgrproj on this kind of content) -- off in every recipe
15200 // whose test targets a different surface.
15201 "--enable-restoration=0",
15202 "--max-partition-size=32",
15203 "--enable-palette=0",
15204 "--enable-intrabc=0",
15205 "--enable-cfl-intra=0",
15206 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
15207 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
15208 "--enable-ref-frame-mvs=0",
15209 "--obu",
15210 "-o",
15211 "-",
15212 "-",
15213 ])
15214 .stdin(Stdio::piped())
15215 .stdout(Stdio::piped())
15216 .stderr(Stdio::piped())
15217 .spawn()
15218 .expect("aomenc failed to start");
15219 child
15220 .stdin
15221 .take()
15222 .expect("aomenc stdin")
15223 .write_all(&y4m.stdout)
15224 .expect("writing y4m to aomenc");
15225 let out = child.wait_with_output().expect("aomenc failed to run");
15226 assert!(
15227 out.status.success(),
15228 "aomenc refused the fixture: {}",
15229 String::from_utf8_lossy(&out.stderr)
15230 );
15231 let stream = out.stdout;
15232 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
15233 std::fs::write(dump, &stream).expect("dump stream");
15234 }
15235 let before = decode::deblock_hits();
15236 let frames = match decode_stream(&stream) {
15237 Ok(frames) => frames,
15238 Err(e) => {
15239 eprintln!(
15240 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: {e}"
15241 );
15242 return;
15243 }
15244 };
15245 assert!(
15246 decode::deblock_hits() > before,
15247 "no deblocking edge fired decoding this sequence -- raise cq-level"
15248 );
15249 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
15250 assert_eq!(frames.len(), frame_count);
15251 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15252 // gradients' colors ignore its seed, so this gate encodes fresh
15253 // content every run -- a mismatch here may never reproduce.
15254 // Self-pin the stream before panicking so the failure is
15255 // bisectable (replay: EC_AV1_PIN on scratch_isolate_pinned_mismatch).
15256 let ok = got.y == want.y && got.u == want.u && got.v == want.v;
15257 if !ok {
15258 let pin = std::env::temp_dir().join("ec-av1-deblocking-gate-fail.obu");
15259 let _ = std::fs::write(&pin, &stream);
15260 panic!("frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display());
15261 }
15262 }
15263 }
15264
15265 /// The decisive cross-frame CDF forwarding test: identical to
15266 /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`]
15267 /// except it drops `--error-resilient=1`, so aomenc codes every inter
15268 /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`)
15269 /// and expects the decoder to resume from the previous frame's *adapted*
15270 /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding,
15271 /// frame 1's very first tile symbol desyncs (an out-of-alphabet
15272 /// partition read); with it, every frame decodes pixel-exact.
15273 #[test]
15274 fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() {
15275 if !have_ffmpeg() {
15276 eprintln!(
15277 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg"
15278 );
15279 return;
15280 }
15281 if !have_aomenc() {
15282 eprintln!(
15283 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}",
15284 aomenc_path().display()
15285 );
15286 return;
15287 }
15288 let (width, height, frame_count) = (64usize, 64usize, 4usize);
15289 // The fixture's content varies run to run (lavfi gradients ignores its
15290 // seed option for the c0..c7 colors -- they default to "random"), so:
15291 // most encodes of this recipe trip one of the decoder's NAMED round-2
15292 // refusals (a reference other than LAST_FRAME, a sub-16 partition --
15293 // genuine coverage gaps, separately documented), and only some produce
15294 // a stream fully inside this decoder's declared support. So: attempt
15295 // several seeds, and the first stream that DECODES must be pixel-exact
15296 // -- that assertion is what guards the forwarded-CDF state (a wrong
15297 // table decodes plausible-but-wrong pixels; the counter-reset bug this
15298 // gate caught did exactly that). Exhausting every attempt on named
15299 // refusals skips loudly, listing them.
15300 let mut refusals = Vec::new();
15301 for attempt in 0..8u32 {
15302 let seed = 42 + attempt;
15303 let source = gradients_source(seed, 64, 64, "duration=0.16:rate=25");
15304 let y4m = Command::new("ffmpeg")
15305 .args([
15306 "-v",
15307 "error",
15308 "-f",
15309 "lavfi",
15310 "-i",
15311 &source,
15312 "-pix_fmt",
15313 "yuv420p",
15314 "-f",
15315 "yuv4mpegpipe",
15316 "-",
15317 ])
15318 .stdin(Stdio::null())
15319 .stdout(Stdio::piped())
15320 .stderr(Stdio::piped())
15321 .output()
15322 .expect("ffmpeg failed to run");
15323 assert!(
15324 y4m.status.success(),
15325 "ffmpeg fixture: {}",
15326 String::from_utf8_lossy(&y4m.stderr)
15327 );
15328 // lane-cdfflake: hard length check on the y4m fixture itself --
15329 // a truncated/racing ffmpeg write would otherwise surface as a
15330 // downstream pixel mismatch indistinguishable from a real decode
15331 // defect. y4m frames are `FRAME\n` (6 bytes) + raw 4:2:0 payload;
15332 // find the header/frame-data boundary at the first `FRAME` marker
15333 // rather than parsing the header fields (duration/rate can move
15334 // the header text length without moving the frame math).
15335 let marker_at = y4m
15336 .stdout
15337 .windows(5)
15338 .position(|w| w == b"FRAME")
15339 .expect("y4m stream missing FRAME marker");
15340 let frame_420_bytes = width * height * 3 / 2;
15341 assert_eq!(
15342 y4m.stdout.len(),
15343 marker_at + frame_count * (6 + frame_420_bytes),
15344 "y4m fixture length mismatch (seed {seed})"
15345 );
15346 let y4m_hash = fnv1a64(&y4m.stdout);
15347 let mut child = Command::new(aomenc_path())
15348 .args([
15349 "--codec=av1",
15350 "--passes=1",
15351 "--end-usage=q",
15352 "--cq-level=55",
15353 "--cpu-used=0",
15354 "--lag-in-frames=0",
15355 "--auto-alt-ref=0",
15356 "--kf-max-dist=1000",
15357 // `--threads=1` (not the default): a multithreaded RD search
15358 // makes aomenc's screen-content-tools heuristic race (seen
15359 // flaky under `cargo test`'s own parallelism -- the same
15360 // fixture, same seed, occasionally sets
15361 // `allow_screen_content_tools`, a round-2 gap unrelated to
15362 // CDF forwarding), so pin it to one thread for a
15363 // deterministic header.
15364 "--threads=1",
15365 "--row-mt=0",
15366 // `--enable-order-hint=0` kills BWDREF/ALTREF entirely (no
15367 // order hints -> no bidirectional distance weighting) and,
15368 // combined with `--auto-alt-ref=0`/`--lag-in-frames=0`
15369 // above, leaves aomenc's RD search only LAST_FRAME/
15370 // LAST2_FRAME/LAST3_FRAME/GOLDEN_FRAME to pick from --
15371 // GOLDEN itself needs no order hint (it is the keyframe's
15372 // fixed slot, not a distance-weighted reference), so this
15373 // does not suppress GOLDEN selection the way the sibling
15374 // CDF-forwarding gate's own comment worried about; it just
15375 // narrows the pool this gate needs GOLDEN to win out of.
15376 "--enable-order-hint=0",
15377 "--enable-warped-motion=0",
15378 "--enable-obmc=0",
15379 "--enable-masked-comp=0",
15380 "--enable-interintra-comp=0",
15381 "--enable-dist-wtd-comp=0",
15382 "--enable-diff-wtd-comp=0",
15383 "--enable-onesided-comp=0",
15384 "--enable-interintra-wedge=0",
15385 "--enable-smooth-interintra=0",
15386 "--enable-rect-partitions=0",
15387 "--enable-ab-partitions=0",
15388 "--enable-1to4-partitions=0",
15389 "--enable-filter-intra=0",
15390 "--enable-smooth-intra=0",
15391 "--enable-paeth-intra=0",
15392 "--enable-directional-intra=0",
15393 "--enable-angle-delta=0",
15394 "--enable-tx-size-search=0",
15395 "--enable-cdef=0",
15396 // Loop restoration is a named refusal (aomenc's RD picks
15397 // Sgrproj on this kind of content) -- off in every recipe
15398 // whose test targets a different surface.
15399 "--enable-restoration=0",
15400 "--max-partition-size=32",
15401 "--enable-palette=0",
15402 "--enable-intrabc=0",
15403 "--enable-cfl-intra=0",
15404 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
15405 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
15406 "--enable-ref-frame-mvs=0",
15407 "--obu",
15408 "-o",
15409 "-",
15410 "-",
15411 ])
15412 .stdin(Stdio::piped())
15413 .stdout(Stdio::piped())
15414 .stderr(Stdio::piped())
15415 .spawn()
15416 .expect("aomenc failed to start");
15417 child
15418 .stdin
15419 .take()
15420 .expect("aomenc stdin")
15421 .write_all(&y4m.stdout)
15422 .expect("writing y4m to aomenc");
15423 let out = child.wait_with_output().expect("aomenc failed to run");
15424 assert!(
15425 out.status.success(),
15426 "aomenc refused the fixture: {}",
15427 String::from_utf8_lossy(&out.stderr)
15428 );
15429 let stream = out.stdout;
15430 let stream_hash = fnv1a64(&stream);
15431 // A named `unsupported` refusal is a documented coverage gap (each
15432 // one carries its own test debt elsewhere), not a forwarding verdict
15433 // -- try the next seed. Any stream that DECODES must be pixel-exact,
15434 // and any non-refusal error is a hard failure.
15435 let frames = match decode_stream(&stream) {
15436 Err(e) => {
15437 let msg = e.to_string();
15438 assert!(
15439 msg.contains("unsupported"),
15440 "cross-frame CDF forwarding failed outright (seed {seed}): {msg}"
15441 );
15442 refusals.push(format!("seed {seed}: {msg}"));
15443 continue;
15444 }
15445 Ok(frames) => frames,
15446 };
15447 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
15448 assert_eq!(frames.len(), frame_count);
15449 // lane-cdfflake: reconstruct ffmpeg's raw reference bytes (the
15450 // three per-frame slices are contiguous chunks of the raw
15451 // `-f rawvideo` output ffmpeg_decode_sequence sliced, so
15452 // concatenating them back is bit-for-bit the same bytes ffmpeg
15453 // actually produced -- no second ffmpeg invocation needed).
15454 let ffmpeg_raw: Vec<u8> = ffmpeg_frames
15455 .iter()
15456 .flat_map(|p| p.y.iter().chain(&p.u).chain(&p.v).map(|&v| v as u8))
15457 .collect();
15458 let ffmpeg_raw_hash = fnv1a64(&ffmpeg_raw);
15459 eprintln!(
15460 "cdfflake attempt seed={seed}: y4m_hash={y4m_hash:016x} \
15461 stream_hash={stream_hash:016x} ffmpeg_raw_hash={ffmpeg_raw_hash:016x}"
15462 );
15463 // lane-av1golden3: pin the exact raw stream on the first mismatch
15464 // so a flaky-looking gate failure becomes a deterministic, static
15465 // fixture to bisect against -- env-gated, no cost on a normal run.
15466 let mismatched = frames
15467 .iter()
15468 .zip(&ffmpeg_frames)
15469 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
15470 if mismatched {
15471 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
15472 std::fs::write(&path, &stream).expect("writing pinned stream");
15473 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
15474 }
15475 // lane-cdfflake: unconditional pin on mismatch -- the aomenc
15476 // stream AND ffmpeg's raw reference bytes, so a flake caught
15477 // under load names the liar (stream bytes differ from a
15478 // clean rerun -> subprocess instability; reference bytes
15479 // differ -> ffmpeg instability; both stable -> real decode
15480 // defect) without relying on the env var being set.
15481 // The pin goes to `fixtures/`, which outlives the session: an
15482 // earlier version wrote to a session scratchpad, so once tmpfs
15483 // reaped it a real mismatch aborted on the write instead of
15484 // reporting itself. A failed write must not mask the assert
15485 // below either, so it warns rather than panicking.
15486 let sp = pin_dir();
15487 let stream_pin = sp.join(format!("cdfflake-stream-seed{seed}.bin"));
15488 let ref_pin = sp.join(format!("cdfflake-ffmpeg-raw-seed{seed}.bin"));
15489 for (path, bytes) in [(&stream_pin, &stream), (&ref_pin, &ffmpeg_raw)] {
15490 if let Err(e) = std::fs::write(path, bytes) {
15491 eprintln!("cdfflake: could not pin to {}: {e}", path.display());
15492 }
15493 }
15494 eprintln!(
15495 "cdfflake MISMATCH seed={seed}: pinned stream + ffmpeg reference to {}",
15496 sp.display()
15497 );
15498 }
15499 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15500 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
15501 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
15502 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
15503 }
15504 return;
15505 }
15506 eprintln!(
15507 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \
15508 attempt hit a named refusal:\n{}",
15509 refusals.join("\n")
15510 );
15511 }
15512
15513 /// lane-av1golden3: reproduces the pinned mismatch bytes captured by
15514 /// `EC_AV1_GATE_DUMP=$SP/golden3-pin.obu` off
15515 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
15516 /// (seed 47, frame 1 U). Deterministic and static -- no aomenc/ffmpeg
15517 /// re-encode involved, only re-decodes the fixed bytes on disk, so it is
15518 /// `#[ignore]`d (the file only exists on this machine's scratchpad) but
15519 /// gives a fast red/green loop for the actual fix.
15520 #[test]
15521 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
15522 fn pinned_golden3_stream_decodes_pixel_exact() {
15523 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
15524 .map(std::path::PathBuf::from)
15525 .unwrap_or_else(|_| pin_dir().join("golden3-pin.obu"));
15526 let Ok(stream) = std::fs::read(&path) else {
15527 eprintln!(
15528 "SKIP pinned_golden3_stream_decodes_pixel_exact: no pinned bytes at {} \
15529 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
15530 path.display()
15531 );
15532 return;
15533 };
15534 if !have_ffmpeg() {
15535 eprintln!("SKIP pinned_golden3_stream_decodes_pixel_exact: no ffmpeg");
15536 return;
15537 }
15538 let frames = decode_stream(&stream).expect("pinned stream must decode");
15539 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
15540 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15541 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
15542 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
15543 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
15544 }
15545 }
15546
15547 /// lane-av1golden4: reproduces the pinned mismatch bytes captured by
15548 /// `EC_AV1_GATE_DUMP=$SP/golden4-pin.obu` off
15549 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
15550 /// (seed 43, frame 3 luma) the round the GOLDEN mask lifted. Deterministic
15551 /// and static -- `#[ignore]`d, run manually.
15552 #[test]
15553 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
15554 fn pinned_golden4_stream_decodes_pixel_exact() {
15555 use crate::decode::non_last_ref_hits;
15556 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
15557 .map(std::path::PathBuf::from)
15558 .unwrap_or_else(|_| pin_dir().join("golden4-pin.obu"));
15559 let Ok(stream) = std::fs::read(&path) else {
15560 eprintln!(
15561 "SKIP pinned_golden4_stream_decodes_pixel_exact: no pinned bytes at {} \
15562 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
15563 path.display()
15564 );
15565 return;
15566 };
15567 if !have_ffmpeg() {
15568 eprintln!("SKIP pinned_golden4_stream_decodes_pixel_exact: no ffmpeg");
15569 return;
15570 }
15571 let before = non_last_ref_hits();
15572 let frames = decode_stream(&stream).expect("pinned stream must decode");
15573 eprintln!(
15574 "non_last_ref_hits before={before} after={}",
15575 non_last_ref_hits()
15576 );
15577 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
15578 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15579 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
15580 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
15581 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
15582 }
15583 }
15584
15585 /// lane-av1golden7 round 9: pins the residual GOLDEN_FRAME MC bug found
15586 /// by the forwarding gate once film grain is out of the way (1/20 real
15587 /// aomenc streams, frame 3 luma, apply_grain=false, `non_last_ref_hits`
15588 /// delta=2). `GOLDEN_FRAME` refuses by name until this decodes exact.
15589 #[test]
15590 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
15591 fn pinned_golden7_stream_decodes_pixel_exact() {
15592 use crate::decode::non_last_ref_hits;
15593 let path = concat!(
15594 env!("CARGO_MANIFEST_DIR"),
15595 "/../../fixtures/golden7-forwarding-mismatch.obu"
15596 );
15597 let stream = std::fs::read(path).expect("reading pinned stream");
15598 if !have_ffmpeg() {
15599 eprintln!("SKIP pinned_golden7_stream_decodes_pixel_exact: no ffmpeg");
15600 return;
15601 }
15602 let before = non_last_ref_hits();
15603 let frames = decode_stream(&stream).expect("pinned stream must decode");
15604 eprintln!(
15605 "non_last_ref_hits before={before} after={}",
15606 non_last_ref_hits()
15607 );
15608 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
15609 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15610 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
15611 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
15612 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
15613 }
15614 }
15615
15616 /// lane-av1refs's decisive single-non-LAST-reference gate: identical
15617 /// recipe to
15618 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
15619 /// except `--enable-order-hint=0` is DROPPED (that flag's own comment on
15620 /// the sibling test names it as exactly what suppresses aomenc's RD from
15621 /// ever picking `GOLDEN_FRAME`) and the sequence runs 8 frames, not 4 --
15622 /// more chances for the RD search to reach past the first GOP's initial
15623 /// key frame. `--auto-alt-ref=0` stays: this decoder only supports
15624 /// `LAST_FRAME`/`GOLDEN_FRAME` so far, and alt-ref/backward references
15625 /// are still a named refusal, not this gate's target. A stream that
15626 /// decodes without firing [`decode::non_last_ref_hits`] is not a
15627 /// coverage win for this round -- SKIP it as a genuine, named miss
15628 /// rather than pass silently on untested ground.
15629 #[test]
15630 fn a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact() {
15631 if !have_ffmpeg() {
15632 eprintln!(
15633 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no ffmpeg"
15634 );
15635 return;
15636 }
15637 if !have_aomenc() {
15638 eprintln!(
15639 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no aomenc at {}",
15640 aomenc_path().display()
15641 );
15642 return;
15643 }
15644 let (width, height, frame_count) = (64usize, 64usize, 8usize);
15645 let mut refusals = Vec::new();
15646 let mut never_fired = 0u32;
15647 // aomenc's own RD search is nondeterministic run-to-run even at
15648 // `--threads=1` (confirmed live: identical CLI args, identical
15649 // input, two different output byte streams) -- so beyond varying
15650 // the fixture's seed, each attempt is its own independent coin
15651 // flip against every named refusal below. 120 attempts (not 40)
15652 // to give that coin flip enough tries to land on a stream this
15653 // decoder both accepts and that fires GOLDEN_FRAME. `duration=0.32`
15654 // at `rate=25` (not `0.24`) matches every sibling gate's own
15655 // frame-count fixture exactly -- a shorter duration here once
15656 // produced a frame-0 (keyframe, no reference at all) luma mismatch
15657 // against ffmpeg, i.e. a source-frame-count rounding artifact of
15658 // this recipe's own choosing, not a decoder bug.
15659 for attempt in 0..120u32 {
15660 let seed = 42 + attempt % 40;
15661 let source = gradients_source(seed, 64, 64, "duration=0.32:rate=25");
15662 let y4m = Command::new("ffmpeg")
15663 .args([
15664 "-v",
15665 "error",
15666 "-f",
15667 "lavfi",
15668 "-i",
15669 &source,
15670 "-pix_fmt",
15671 "yuv420p",
15672 "-f",
15673 "yuv4mpegpipe",
15674 "-",
15675 ])
15676 .stdin(Stdio::null())
15677 .stdout(Stdio::piped())
15678 .stderr(Stdio::piped())
15679 .output()
15680 .expect("ffmpeg failed to run");
15681 assert!(
15682 y4m.status.success(),
15683 "ffmpeg fixture: {}",
15684 String::from_utf8_lossy(&y4m.stderr)
15685 );
15686 let mut child = Command::new(aomenc_path())
15687 .args([
15688 "--codec=av1",
15689 "--passes=1",
15690 "--end-usage=q",
15691 "--cq-level=55",
15692 "--cpu-used=0",
15693 "--lag-in-frames=0",
15694 "--auto-alt-ref=0",
15695 "--kf-max-dist=1000",
15696 "--threads=1",
15697 "--row-mt=0",
15698 // Narrows the RD search's reference alphabet toward
15699 // LAST_FRAME/GOLDEN_FRAME -- without this, aomenc's RD is
15700 // just as likely to pick LAST2/LAST3/BWDREF/ALTREF2/
15701 // ALTREF (this decoder's already-documented, still-open
15702 // refusals), starving this gate of the one reference it
15703 // targets.
15704 "--max-reference-frames=3",
15705 "--reduced-reference-set=1",
15706 "--enable-warped-motion=0",
15707 "--enable-obmc=0",
15708 "--enable-masked-comp=0",
15709 "--enable-interintra-comp=0",
15710 "--enable-dist-wtd-comp=0",
15711 "--enable-diff-wtd-comp=0",
15712 "--enable-onesided-comp=0",
15713 "--enable-interintra-wedge=0",
15714 "--enable-smooth-interintra=0",
15715 "--enable-rect-partitions=0",
15716 "--enable-ab-partitions=0",
15717 "--enable-1to4-partitions=0",
15718 "--enable-filter-intra=0",
15719 "--enable-smooth-intra=0",
15720 "--enable-paeth-intra=0",
15721 "--enable-directional-intra=0",
15722 "--enable-angle-delta=0",
15723 "--enable-tx-size-search=0",
15724 "--enable-cdef=0",
15725 "--enable-restoration=0",
15726 // `min == max == 32` forces PARTITION_NONE for every
15727 // 32x32 block, not just biases toward it -- with
15728 // `--min-partition-size=16` alone aomenc's exhaustive
15729 // `cpu-used=0` RD search still occasionally read HORZ/
15730 // VERT/SPLIT partitions below 32x32 despite
15731 // `--enable-rect-partitions=0`/`--enable-ab-partitions=0`/
15732 // `--enable-1to4-partitions=0` all being off (two
15733 // separate, already-documented round-2 gaps: "a
15734 // partition below 16x16", "a partition type this encoder
15735 // never writes"), starving this gate's already-narrow
15736 // seed pool. Locking both bounds to 32 removes any
15737 // partition-depth choice from the search entirely, so
15738 // this gate can isolate GOLDEN_FRAME selection alone.
15739 "--max-partition-size=32",
15740 "--min-partition-size=32",
15741 "--enable-palette=0",
15742 "--enable-intrabc=0",
15743 "--enable-cfl-intra=0",
15744 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
15745 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
15746 "--enable-ref-frame-mvs=0",
15747 // `--tune-content=film` was dropped: on this box it
15748 // makes aomenc emit `apply_grain` almost every attempt
15749 // (lane-av1golden8 round 10 measurement, live: 120/120
15750 // real attempts hit a named refusal, 0 ever fired
15751 // GOLDEN_FRAME -- mostly `apply_grain`, dominated by its
15752 // own recipe flag) -- film grain synthesis has its own
15753 // dedicated refusal test and must not starve this gate
15754 // of the GOLDEN_FRAME draws it exists to prove. Default
15755 // content tuning still occasionally flips
15756 // `allow_screen_content_tools` on for this synthetic
15757 // gradient content (a separate, already-documented open
15758 // refusal), which the 120-attempt coin flip below
15759 // tolerates the same way.
15760 "--obu",
15761 "-o",
15762 "-",
15763 "-",
15764 ])
15765 .stdin(Stdio::piped())
15766 .stdout(Stdio::piped())
15767 .stderr(Stdio::piped())
15768 .spawn()
15769 .expect("aomenc failed to start");
15770 child
15771 .stdin
15772 .take()
15773 .expect("aomenc stdin")
15774 .write_all(&y4m.stdout)
15775 .expect("writing y4m to aomenc");
15776 let out = child.wait_with_output().expect("aomenc failed to run");
15777 assert!(
15778 out.status.success(),
15779 "aomenc refused the fixture: {}",
15780 String::from_utf8_lossy(&out.stderr)
15781 );
15782 let stream = out.stdout;
15783 let before = decode::non_last_ref_hits();
15784 let frames = match decode_stream(&stream) {
15785 Err(e) => {
15786 let msg = e.to_string();
15787 assert!(
15788 msg.contains("unsupported"),
15789 "a golden-reference stream failed outright (seed {seed}): {msg}"
15790 );
15791 refusals.push(format!("seed {seed}: {msg}"));
15792 continue;
15793 }
15794 Ok(frames) => frames,
15795 };
15796 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
15797 // is ALWAYS pixel-compared below; the hit counter only decides whether
15798 // the attempt counts toward the firing total.
15799 // This seed's RD search may never have picked GOLDEN_FRAME -- a
15800 // genuine miss, not a refusal, and not a reason to skip the pixels.
15801 let counted = decode::non_last_ref_hits() != before;
15802 if !counted {
15803 never_fired += 1;
15804 }
15805 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
15806 assert_eq!(frames.len(), frame_count);
15807 // Same pin-on-mismatch pattern as the CDF forwarding gate above:
15808 // env-gated, no cost on a normal run.
15809 let mismatched = frames
15810 .iter()
15811 .zip(&ffmpeg_frames)
15812 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
15813 if mismatched {
15814 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
15815 std::fs::write(&path, &stream).expect("writing pinned stream");
15816 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
15817 }
15818 }
15819 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15820 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
15821 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
15822 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
15823 }
15824 if counted {
15825 eprintln!(
15826 "FIRING seed {seed}: non_last_ref_hits advanced by {}",
15827 decode::non_last_ref_hits() - before
15828 );
15829 gate_buckets(
15830 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
15831 1,
15832 never_fired,
15833 refusals.len(),
15834 );
15835 return;
15836 }
15837 }
15838 gate_buckets(
15839 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
15840 0,
15841 never_fired,
15842 refusals.len(),
15843 );
15844 eprintln!(
15845 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \
15846 {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \
15847 attempt hit a named refusal:\n{}",
15848 refusals.join("\n")
15849 );
15850 }
15851
15852 /// lane-av1refs's decisive gate for the 5 references widened past
15853 /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch
15854 /// pattern as
15855 /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`],
15856 /// generalised over `(target_ref, extra_args, frame_count)` so each of
15857 /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool
15858 /// and its own proof that `decode::ref_hits(target_ref)` -- not just
15859 /// `non_last_ref_hits`, which cannot distinguish one reference from
15860 /// another -- actually advanced. `--max-reference-frames=3
15861 /// --reduced-reference-set=1` (the golden gate's own narrowing) is
15862 /// DROPPED here: both suppress exactly the references this gate needs
15863 /// aomenc's RD to reach.
15864 fn a_real_aomenc_single_ref_gate(
15865 gate_name: &str,
15866 target_ref: i8,
15867 target_ref_name: &str,
15868 extra_args: &[&str],
15869 width: usize,
15870 height: usize,
15871 frame_count: usize,
15872 attempts: u32,
15873 ) {
15874 let _gate_lock = lock_gate_counters();
15875 if !have_ffmpeg() {
15876 eprintln!("SKIP {gate_name}: no ffmpeg");
15877 return;
15878 }
15879 if !have_aomenc() {
15880 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
15881 return;
15882 }
15883 let mut refusals = Vec::new();
15884 let mut never_fired = 0u32;
15885 for attempt in 0..attempts {
15886 let seed = 42 + attempt % 40;
15887 let duration = frame_count as f64 / 25.0;
15888 let source =
15889 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
15890 let y4m = Command::new("ffmpeg")
15891 .args([
15892 "-v",
15893 "error",
15894 "-f",
15895 "lavfi",
15896 "-i",
15897 &source,
15898 "-pix_fmt",
15899 "yuv420p",
15900 "-f",
15901 "yuv4mpegpipe",
15902 "-",
15903 ])
15904 .stdin(Stdio::null())
15905 .stdout(Stdio::piped())
15906 .stderr(Stdio::piped())
15907 .output()
15908 .expect("ffmpeg failed to run");
15909 assert!(
15910 y4m.status.success(),
15911 "ffmpeg fixture: {}",
15912 String::from_utf8_lossy(&y4m.stderr)
15913 );
15914 let mut args: Vec<&str> = vec![
15915 "--codec=av1",
15916 "--passes=1",
15917 "--end-usage=q",
15918 "--cq-level=55",
15919 "--cpu-used=0",
15920 "--kf-max-dist=1000",
15921 "--threads=1",
15922 "--row-mt=0",
15923 "--enable-warped-motion=0",
15924 "--enable-obmc=0",
15925 "--enable-masked-comp=0",
15926 "--enable-interintra-comp=0",
15927 "--enable-dist-wtd-comp=0",
15928 "--enable-diff-wtd-comp=0",
15929 "--enable-onesided-comp=0",
15930 "--enable-interintra-wedge=0",
15931 "--enable-smooth-interintra=0",
15932 "--enable-rect-partitions=0",
15933 "--enable-ab-partitions=0",
15934 "--enable-1to4-partitions=0",
15935 "--enable-filter-intra=0",
15936 "--enable-smooth-intra=0",
15937 "--enable-paeth-intra=0",
15938 "--enable-directional-intra=0",
15939 "--enable-angle-delta=0",
15940 "--enable-tx-size-search=0",
15941 "--enable-cdef=0",
15942 "--enable-restoration=0",
15943 "--max-partition-size=32",
15944 "--min-partition-size=32",
15945 "--enable-palette=0",
15946 "--enable-intrabc=0",
15947 "--enable-cfl-intra=0",
15948 // use_ref_frame_mvs (temporal MV projection) is unimplemented in
15949 // mvstack; leaving it on silently desyncs symbols on inter frames.
15950 "--enable-ref-frame-mvs=0",
15951 "--obu",
15952 "-o",
15953 "-",
15954 "-",
15955 ];
15956 // extra_args goes right before the trailing "-o", "-", "-" triple.
15957 let tail = args.split_off(args.len() - 3);
15958 args.extend_from_slice(extra_args);
15959 args.extend_from_slice(&tail);
15960 let mut child = Command::new(aomenc_path())
15961 .args(&args)
15962 .stdin(Stdio::piped())
15963 .stdout(Stdio::piped())
15964 .stderr(Stdio::piped())
15965 .spawn()
15966 .expect("aomenc failed to start");
15967 child
15968 .stdin
15969 .take()
15970 .expect("aomenc stdin")
15971 .write_all(&y4m.stdout)
15972 .expect("writing y4m to aomenc");
15973 let out = child.wait_with_output().expect("aomenc failed to run");
15974 assert!(
15975 out.status.success(),
15976 "aomenc refused the fixture: {}",
15977 String::from_utf8_lossy(&out.stderr)
15978 );
15979 let stream = out.stdout;
15980 let before = decode::ref_hits(target_ref);
15981 let frames = match decode_stream(&stream) {
15982 Err(e) => {
15983 let msg = e.to_string();
15984 assert!(
15985 msg.contains("unsupported"),
15986 "{gate_name} failed outright (seed {seed}): {msg}"
15987 );
15988 refusals.push(format!("seed {seed}: {msg}"));
15989 continue;
15990 }
15991 Ok(frames) => frames,
15992 };
15993 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
15994 // is ALWAYS pixel-compared below; the hit counter only decides whether
15995 // the attempt counts toward the firing total.
15996 let counted = decode::ref_hits(target_ref) != before;
15997 if !counted {
15998 never_fired += 1;
15999 }
16000 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
16001 assert_eq!(frames.len(), frame_count);
16002 let mismatched = frames
16003 .iter()
16004 .zip(&ffmpeg_frames)
16005 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16006 if mismatched {
16007 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
16008 std::fs::write(&path, &stream).expect("writing pinned stream");
16009 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
16010 }
16011 }
16012 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16013 assert_eq!(
16014 got.y, want.y,
16015 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
16016 );
16017 assert_eq!(
16018 got.u, want.u,
16019 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
16020 );
16021 assert_eq!(
16022 got.v, want.v,
16023 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
16024 );
16025 }
16026 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
16027 // stream again, comparing EVERY decode-order frame -- the hidden
16028 // (show_frame == 0) alt-ref frames the ffmpeg compare above
16029 // cannot see, because both sides of it emit shown frames only.
16030 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, gate_name);
16031 eprintln!(
16032 "{gate_name} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
16033 {hidden_n} hidden, all pixel-exact vs the oracle"
16034 );
16035 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
16036 // libaom's temporal alt-ref filter absorbs this recipe's hidden
16037 // frames, so the compare above is vacuous -- re-encode the same
16038 // fixture with --arnr-maxframes=0 and compare THOSE.
16039 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(gate_name, &y4m.stdout, &args) {
16040 eprintln!(
16041 "{gate_name} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
16042 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
16043 );
16044 }
16045 if counted {
16046 eprintln!(
16047 "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}",
16048 decode::ref_hits(target_ref) - before
16049 );
16050 gate_buckets(gate_name, 1, never_fired, refusals.len());
16051 return;
16052 }
16053 }
16054 gate_buckets(gate_name, 0, never_fired, refusals.len());
16055 eprintln!(
16056 "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \
16057 and every other attempt hit a named refusal:\n{}",
16058 refusals.join("\n")
16059 );
16060 }
16061
16062 /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read
16063 /// off a real bitstream rather than only unit-tested in isolation --
16064 /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward
16065 /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1`
16066 /// is required for it to ever consider compound at all. Three
16067 /// acceptable outcomes: (a) a stream where `reference_select` never
16068 /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end
16069 /// to end (proving the per-block `comp_mode` read did not desync the
16070 /// single-ref blocks around it); (b) a stream that does fire compound
16071 /// is refused by name with [`decode::comp_mode_hits`] having advanced
16072 /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right
16073 /// symbols before refusing, rather than desyncing and refusing for an
16074 /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`)
16075 /// and a partition below 16x16 (a real, separately tracked capability
16076 /// gap) are the two refusal arms this can still legitimately name; (c)
16077 /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a
16078 /// stream that fires compound may also decode fully -- accepted only
16079 /// when every output frame is pixel-exact against ffmpeg.
16080 #[test]
16081 fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() {
16082 const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly";
16083 let _gate_lock = lock_gate_counters();
16084 if !have_ffmpeg() {
16085 eprintln!("SKIP {NAME}: no ffmpeg");
16086 return;
16087 }
16088 if !have_aomenc() {
16089 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16090 return;
16091 }
16092 let (width, height, frame_count) = (64usize, 64usize, 20usize);
16093 let mut refusals = Vec::new();
16094 let mut never_fired = 0u32;
16095 for attempt in 0..60u32 {
16096 let seed = 42 + attempt % 40;
16097 let duration = frame_count as f64 / 25.0;
16098 let source =
16099 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
16100 let y4m = Command::new("ffmpeg")
16101 .args([
16102 "-v",
16103 "error",
16104 "-f",
16105 "lavfi",
16106 "-i",
16107 &source,
16108 "-pix_fmt",
16109 "yuv420p",
16110 "-f",
16111 "yuv4mpegpipe",
16112 "-",
16113 ])
16114 .stdin(Stdio::null())
16115 .stdout(Stdio::piped())
16116 .stderr(Stdio::piped())
16117 .output()
16118 .expect("ffmpeg failed to run");
16119 assert!(
16120 y4m.status.success(),
16121 "ffmpeg fixture: {}",
16122 String::from_utf8_lossy(&y4m.stderr)
16123 );
16124 let args: Vec<&str> = vec![
16125 "--codec=av1",
16126 "--passes=1",
16127 "--end-usage=q",
16128 "--cq-level=45",
16129 "--cpu-used=0",
16130 "--kf-max-dist=1000",
16131 "--threads=1",
16132 "--row-mt=0",
16133 "--auto-alt-ref=1",
16134 "--lag-in-frames=16",
16135 "--enable-order-hint=1",
16136 "--enable-warped-motion=0",
16137 "--enable-obmc=0",
16138 "--enable-masked-comp=0",
16139 "--enable-interintra-comp=0",
16140 "--enable-onesided-comp=0",
16141 "--enable-interintra-wedge=0",
16142 "--enable-smooth-interintra=0",
16143 "--enable-rect-partitions=0",
16144 "--enable-ab-partitions=0",
16145 "--enable-1to4-partitions=0",
16146 "--enable-filter-intra=0",
16147 "--enable-smooth-intra=0",
16148 "--enable-paeth-intra=0",
16149 "--enable-directional-intra=0",
16150 "--enable-angle-delta=0",
16151 "--enable-tx-size-search=0",
16152 "--enable-cdef=0",
16153 "--enable-restoration=0",
16154 "--max-partition-size=32",
16155 "--min-partition-size=32",
16156 "--enable-palette=0",
16157 "--enable-intrabc=0",
16158 "--enable-cfl-intra=0",
16159 "--enable-ref-frame-mvs=0",
16160 "--obu",
16161 "-o",
16162 "-",
16163 "-",
16164 ];
16165 let mut child = Command::new(aomenc_path())
16166 .args(&args)
16167 .stdin(Stdio::piped())
16168 .stdout(Stdio::piped())
16169 .stderr(Stdio::piped())
16170 .spawn()
16171 .expect("aomenc failed to start");
16172 child
16173 .stdin
16174 .take()
16175 .expect("aomenc stdin")
16176 .write_all(&y4m.stdout)
16177 .expect("writing y4m to aomenc");
16178 let out = child.wait_with_output().expect("aomenc failed to run");
16179 assert!(
16180 out.status.success(),
16181 "aomenc refused the fixture: {}",
16182 String::from_utf8_lossy(&out.stderr)
16183 );
16184 let stream = out.stdout;
16185 let before = decode::comp_mode_hits();
16186 match decode_stream(&stream) {
16187 Err(e) => {
16188 let msg = e.to_string();
16189 let fired = decode::comp_mode_hits() > before;
16190 assert!(
16191 msg.contains("unsupported"),
16192 "{NAME} failed outright (seed {seed}): {msg}"
16193 );
16194 if fired {
16195 // `comp_mode` firing does not stop the block walk --
16196 // a later, unrelated block in the same tile can
16197 // still hit any other named refusal this decoder
16198 // carries. A partition below 16x16 is a real, open
16199 // capability gap tracked on its own (not a
16200 // COMPOUND_REFERENCE defect); accept it here too
16201 // rather than fail a compound-specific gate on a
16202 // partition-search coincidence. lane-av1blend r7:
16203 // re-swept the wide gate with the plain-average
16204 // blend unmasked (r6/r7's ref_ctx fix alone) and it
16205 // still mismatches on real streams beyond that one
16206 // bug -- re-masked comp_group_idx == 0 too, so this
16207 // stays a legal named refusal.
16208 assert!(
16209 msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"),
16210 "{NAME}: comp_mode fired (seed {seed}) but the refusal \
16211 was for something else: {msg}"
16212 );
16213 let advanced = decode::comp_mode_hits() - before;
16214 eprintln!(
16215 "{NAME} FIRING seed {seed}: comp_mode hits advanced by \
16216 {advanced}, refused by name as expected: {msg}"
16217 );
16218 return;
16219 }
16220 refusals.push(format!("seed {seed}: {msg}"));
16221 continue;
16222 }
16223 Ok(frames) => {
16224 // class [[gate-skips-on-its-own-failure]]: a decode that
16225 // succeeded is ALWAYS pixel-compared below; the hit counter
16226 // only decides whether the attempt counts as firing.
16227 let counted = decode::comp_mode_hits() != before;
16228 if !counted {
16229 never_fired += 1;
16230 }
16231 // Outcome (c): plain COMPOUND_AVERAGE decoded fully --
16232 // non-negotiable pixel exactness, no tolerance.
16233 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
16234 assert_eq!(frames.len(), frame_count);
16235 let mismatched = frames
16236 .iter()
16237 .zip(&ffmpeg_frames)
16238 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16239 if mismatched {
16240 let pin = std::env::temp_dir().join("ec-av1-reference-select-gate-fail.obu");
16241 let _ = std::fs::write(&pin, &stream);
16242 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
16243 std::fs::write(&path, &stream).expect("writing pinned stream");
16244 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
16245 }
16246 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16247 assert_eq!(
16248 got.y, want.y,
16249 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
16250 pin.display()
16251 );
16252 assert_eq!(
16253 got.u, want.u,
16254 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
16255 pin.display()
16256 );
16257 assert_eq!(
16258 got.v, want.v,
16259 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
16260 pin.display()
16261 );
16262 }
16263 } else {
16264 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16265 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
16266 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
16267 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
16268 }
16269 }
16270 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
16271 // stream again, comparing EVERY decode-order frame -- the hidden
16272 // (show_frame == 0) alt-ref frames the ffmpeg compare above
16273 // cannot see, because both sides of it emit shown frames only.
16274 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
16275 eprintln!(
16276 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
16277 {hidden_n} hidden, all pixel-exact vs the oracle"
16278 );
16279 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
16280 // libaom's temporal alt-ref filter absorbs this recipe's hidden
16281 // frames, so the compare above is vacuous -- re-encode the same
16282 // fixture with --arnr-maxframes=0 and compare THOSE.
16283 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
16284 eprintln!(
16285 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
16286 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
16287 );
16288 }
16289 if counted {
16290 eprintln!(
16291 "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \
16292 fully and pixel-exact",
16293 decode::comp_mode_hits() - before
16294 );
16295 gate_buckets(NAME, 1, never_fired, refusals.len());
16296 return;
16297 }
16298 }
16299 }
16300 }
16301 gate_buckets(NAME, 0, never_fired, refusals.len());
16302 eprintln!(
16303 "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \
16304 block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \
16305 reached comp_mode:\n{}",
16306 refusals.join("\n")
16307 );
16308 }
16309
16310 /// lane-av1comp round 14's decisive gate for `skip_mode`: same
16311 /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving
16312 /// [`decode::skip_mode_hits`] actually advanced (a real block picked
16313 /// `skip_mode`, not just that the frame header bit was set) and that the
16314 /// resulting forced-compound `NEAREST_NEARESTMV` decode is still
16315 /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16
16316 /// --enable-fwd-kf=0` (backward references) plus
16317 /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection,
16318 /// same as every other gate here) is aomenc's own requirement for
16319 /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs
16320 /// both a forward and a backward reference candidate).
16321 #[test]
16322 fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() {
16323 const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact";
16324 let _gate_lock = lock_gate_counters();
16325 if !have_ffmpeg() {
16326 eprintln!("SKIP {NAME}: no ffmpeg");
16327 return;
16328 }
16329 if !have_aomenc() {
16330 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16331 return;
16332 }
16333 let (width, height, frame_count) = (64usize, 64usize, 24usize);
16334 let mut refusals = Vec::new();
16335 let mut never_fired = 0u32;
16336 for attempt in 0..80u32 {
16337 let seed = 42 + attempt % 40;
16338 let duration = frame_count as f64 / 25.0;
16339 let source =
16340 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
16341 let y4m = Command::new("ffmpeg")
16342 .args([
16343 "-v",
16344 "error",
16345 "-f",
16346 "lavfi",
16347 "-i",
16348 &source,
16349 "-pix_fmt",
16350 "yuv420p",
16351 "-f",
16352 "yuv4mpegpipe",
16353 "-",
16354 ])
16355 .stdin(Stdio::null())
16356 .stdout(Stdio::piped())
16357 .stderr(Stdio::piped())
16358 .output()
16359 .expect("ffmpeg failed to run");
16360 assert!(
16361 y4m.status.success(),
16362 "ffmpeg fixture: {}",
16363 String::from_utf8_lossy(&y4m.stderr)
16364 );
16365 let args: Vec<&str> = vec![
16366 "--codec=av1",
16367 "--passes=1",
16368 "--end-usage=q",
16369 "--cq-level=45",
16370 "--cpu-used=0",
16371 "--kf-max-dist=1000",
16372 "--threads=1",
16373 "--row-mt=0",
16374 "--auto-alt-ref=1",
16375 "--lag-in-frames=16",
16376 "--enable-fwd-kf=0",
16377 "--enable-order-hint=1",
16378 "--enable-warped-motion=0",
16379 "--enable-obmc=0",
16380 "--enable-masked-comp=0",
16381 "--enable-interintra-comp=0",
16382 "--enable-onesided-comp=0",
16383 "--enable-interintra-wedge=0",
16384 "--enable-smooth-interintra=0",
16385 "--enable-rect-partitions=0",
16386 "--enable-ab-partitions=0",
16387 "--enable-1to4-partitions=0",
16388 "--enable-filter-intra=0",
16389 "--enable-smooth-intra=0",
16390 "--enable-paeth-intra=0",
16391 "--enable-directional-intra=0",
16392 "--enable-angle-delta=0",
16393 "--enable-tx-size-search=0",
16394 "--enable-cdef=0",
16395 "--enable-restoration=0",
16396 "--max-partition-size=32",
16397 "--min-partition-size=32",
16398 "--enable-palette=0",
16399 "--enable-intrabc=0",
16400 "--enable-cfl-intra=0",
16401 "--enable-ref-frame-mvs=0",
16402 "--obu",
16403 "-o",
16404 "-",
16405 "-",
16406 ];
16407 let mut child = Command::new(aomenc_path())
16408 .args(&args)
16409 .stdin(Stdio::piped())
16410 .stdout(Stdio::piped())
16411 .stderr(Stdio::piped())
16412 .spawn()
16413 .expect("aomenc failed to start");
16414 child
16415 .stdin
16416 .take()
16417 .expect("aomenc stdin")
16418 .write_all(&y4m.stdout)
16419 .expect("writing y4m to aomenc");
16420 let out = child.wait_with_output().expect("aomenc failed to run");
16421 assert!(
16422 out.status.success(),
16423 "aomenc refused the fixture: {}",
16424 String::from_utf8_lossy(&out.stderr)
16425 );
16426 let stream = out.stdout;
16427 let before = decode::skip_mode_hits();
16428 let frames = match decode_stream(&stream) {
16429 Err(e) => {
16430 let msg = e.to_string();
16431 assert!(
16432 msg.contains("unsupported"),
16433 "{NAME} failed outright (seed {seed}): {msg}"
16434 );
16435 refusals.push(format!("seed {seed}: {msg}"));
16436 continue;
16437 }
16438 Ok(frames) => frames,
16439 };
16440 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
16441 // is ALWAYS pixel-compared below; the hit counter only decides whether
16442 // the attempt counts toward the firing total.
16443 let counted = decode::skip_mode_hits() != before;
16444 if !counted {
16445 never_fired += 1;
16446 }
16447 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
16448 assert_eq!(frames.len(), frame_count);
16449 let mismatched = frames
16450 .iter()
16451 .zip(&ffmpeg_frames)
16452 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16453 if mismatched {
16454 let pin = std::env::temp_dir().join("ec-av1-compound-refs-gate-fail.obu");
16455 let _ = std::fs::write(&pin, &stream);
16456 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
16457 std::fs::write(&path, &stream).expect("writing pinned stream");
16458 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
16459 }
16460 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16461 assert_eq!(
16462 got.y, want.y,
16463 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
16464 pin.display()
16465 );
16466 assert_eq!(
16467 got.u, want.u,
16468 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
16469 pin.display()
16470 );
16471 assert_eq!(
16472 got.v, want.v,
16473 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
16474 pin.display()
16475 );
16476 }
16477 }
16478 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
16479 // stream again, comparing EVERY decode-order frame -- the hidden
16480 // (show_frame == 0) alt-ref frames the ffmpeg compare above
16481 // cannot see, because both sides of it emit shown frames only.
16482 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
16483 eprintln!(
16484 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
16485 {hidden_n} hidden, all pixel-exact vs the oracle"
16486 );
16487 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
16488 // libaom's temporal alt-ref filter absorbs this recipe's hidden
16489 // frames, so the compare above is vacuous -- re-encode the same
16490 // fixture with --arnr-maxframes=0 and compare THOSE.
16491 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
16492 eprintln!(
16493 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
16494 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
16495 );
16496 }
16497 if counted {
16498 eprintln!(
16499 "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}",
16500 decode::skip_mode_hits() - before
16501 );
16502 gate_buckets(NAME, 1, never_fired, refusals.len());
16503 return;
16504 }
16505 }
16506 gate_buckets(NAME, 0, never_fired, refusals.len());
16507 eprintln!(
16508 "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \
16509 other attempt hit a named refusal:\n{}",
16510 refusals.join("\n")
16511 );
16512 }
16513
16514 /// lane-motionmode round 1: `--enable-obmc=1 --enable-warped-motion=0`
16515 /// on the base recipe (`--auto-alt-ref=1 --lag-in-frames=16
16516 /// --enable-fwd-kf=0 --enable-ref-frame-mvs=0`) -- pixel-exact against
16517 /// ffmpeg, gated on [`decode::obmc_hits`] actually advancing (a real
16518 /// block picked `OBMC_CAUSAL`, not just that the header bit was set).
16519 /// Structure copied from
16520 /// `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`:
16521 /// a seed sweep with a named-refusal escape hatch and an
16522 /// `EC_AV1_GATE_DUMP` pin on mismatch.
16523 #[test]
16524 fn a_real_aomenc_stream_with_obmc_decodes_pixel_exact() {
16525 const NAME: &str = "a_real_aomenc_stream_with_obmc_decodes_pixel_exact";
16526 let _gate_lock = lock_gate_counters();
16527 if !have_ffmpeg() {
16528 eprintln!("SKIP {NAME}: no ffmpeg");
16529 return;
16530 }
16531 if !have_aomenc() {
16532 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16533 return;
16534 }
16535 let (width, height, frame_count) = (64usize, 64usize, 24usize);
16536 let mut refusals = Vec::new();
16537 let mut never_fired = 0u32;
16538 for attempt in 0..80u32 {
16539 let seed = 42 + attempt % 40;
16540 let duration = frame_count as f64 / 25.0;
16541 let source =
16542 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
16543 let y4m = Command::new("ffmpeg")
16544 .args([
16545 "-v",
16546 "error",
16547 "-f",
16548 "lavfi",
16549 "-i",
16550 &source,
16551 "-pix_fmt",
16552 "yuv420p",
16553 "-f",
16554 "yuv4mpegpipe",
16555 "-",
16556 ])
16557 .stdin(Stdio::null())
16558 .stdout(Stdio::piped())
16559 .stderr(Stdio::piped())
16560 .output()
16561 .expect("ffmpeg failed to run");
16562 assert!(
16563 y4m.status.success(),
16564 "ffmpeg fixture: {}",
16565 String::from_utf8_lossy(&y4m.stderr)
16566 );
16567 let args: Vec<&str> = vec![
16568 "--codec=av1",
16569 "--passes=1",
16570 "--end-usage=q",
16571 "--cq-level=45",
16572 "--cpu-used=0",
16573 "--kf-max-dist=1000",
16574 "--threads=1",
16575 "--row-mt=0",
16576 "--auto-alt-ref=1",
16577 "--lag-in-frames=16",
16578 "--enable-fwd-kf=0",
16579 "--enable-order-hint=1",
16580 "--enable-warped-motion=0",
16581 "--enable-obmc=1",
16582 "--enable-masked-comp=0",
16583 "--enable-interintra-comp=0",
16584 "--enable-onesided-comp=0",
16585 "--enable-interintra-wedge=0",
16586 "--enable-smooth-interintra=0",
16587 "--enable-rect-partitions=0",
16588 "--enable-ab-partitions=0",
16589 "--enable-1to4-partitions=0",
16590 "--enable-filter-intra=0",
16591 "--enable-smooth-intra=0",
16592 "--enable-paeth-intra=0",
16593 "--enable-directional-intra=0",
16594 "--enable-angle-delta=0",
16595 "--enable-tx-size-search=0",
16596 "--enable-cdef=0",
16597 "--enable-restoration=0",
16598 "--max-partition-size=32",
16599 "--min-partition-size=32",
16600 "--enable-palette=0",
16601 "--enable-intrabc=0",
16602 "--enable-cfl-intra=0",
16603 "--enable-ref-frame-mvs=0",
16604 "--obu",
16605 "-o",
16606 "-",
16607 "-",
16608 ];
16609 let mut child = Command::new(aomenc_path())
16610 .args(&args)
16611 .stdin(Stdio::piped())
16612 .stdout(Stdio::piped())
16613 .stderr(Stdio::piped())
16614 .spawn()
16615 .expect("aomenc failed to start");
16616 child
16617 .stdin
16618 .take()
16619 .expect("aomenc stdin")
16620 .write_all(&y4m.stdout)
16621 .expect("writing y4m to aomenc");
16622 let out = child.wait_with_output().expect("aomenc failed to run");
16623 assert!(
16624 out.status.success(),
16625 "aomenc refused the fixture: {}",
16626 String::from_utf8_lossy(&out.stderr)
16627 );
16628 let stream = out.stdout;
16629 let before = decode::obmc_hits();
16630 let frames = match decode_stream(&stream) {
16631 Err(e) => {
16632 let msg = e.to_string();
16633 assert!(
16634 msg.contains("unsupported"),
16635 "{NAME} failed outright (seed {seed}): {msg}"
16636 );
16637 refusals.push(format!("seed {seed}: {msg}"));
16638 continue;
16639 }
16640 Ok(frames) => frames,
16641 };
16642 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
16643 // is ALWAYS pixel-compared below; the hit counter only decides whether
16644 // the attempt counts toward the firing total.
16645 let counted = decode::obmc_hits() != before;
16646 if !counted {
16647 never_fired += 1;
16648 }
16649 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
16650 assert_eq!(frames.len(), frame_count);
16651 let mismatched = frames
16652 .iter()
16653 .zip(&ffmpeg_frames)
16654 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16655 if mismatched {
16656 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
16657 std::fs::write(&path, &stream).expect("writing pinned stream");
16658 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
16659 }
16660 }
16661 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16662 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
16663 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
16664 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
16665 }
16666 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
16667 // stream again, comparing EVERY decode-order frame -- the hidden
16668 // (show_frame == 0) alt-ref frames the ffmpeg compare above
16669 // cannot see, because both sides of it emit shown frames only.
16670 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
16671 eprintln!(
16672 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
16673 {hidden_n} hidden, all pixel-exact vs the oracle"
16674 );
16675 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
16676 // libaom's temporal alt-ref filter absorbs this recipe's hidden
16677 // frames, so the compare above is vacuous -- re-encode the same
16678 // fixture with --arnr-maxframes=0 and compare THOSE.
16679 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
16680 eprintln!(
16681 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
16682 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
16683 );
16684 }
16685 if counted {
16686 eprintln!(
16687 "{NAME} FIRING seed {seed}: obmc hits advanced by {}",
16688 decode::obmc_hits() - before
16689 );
16690 gate_buckets(NAME, 1, never_fired, refusals.len());
16691 return;
16692 }
16693 }
16694 gate_buckets(NAME, 0, never_fired, refusals.len());
16695 eprintln!(
16696 "SKIP {NAME}: {never_fired} attempts decoded but never fired obmc, and every \
16697 other attempt hit a named refusal:\n{}",
16698 refusals.join("\n")
16699 );
16700 }
16701
16702 /// lane-motionmode round 3: same shape as
16703 /// `a_real_aomenc_stream_with_obmc_decodes_pixel_exact`, but relaxed the
16704 /// `--min-partition-size=32 --max-partition-size=32` clamp (that other
16705 /// gate's own doc: locked to remove partition-depth choice from the
16706 /// search entirely) to `8`/`32`, to make an 8x8-leaf `OBMC_CAUSAL` pick
16707 /// possible at all. Gated on [`decode::obmc_hits_8`] specifically, not
16708 /// the aggregate [`decode::obmc_hits`]. Measured live (round 3, this
16709 /// box): 80 attempts, 0 ever called `decode_inter_block8` at all --
16710 /// `cpu-used=0`'s RD search never once splits a 16x16 down to a clean
16711 /// 4-way 8x8 leaf for this smooth `gradients` fixture (large blocks
16712 /// always win the RD cost there); the handful of named refusals seen
16713 /// are `PARTITION_SPLIT` chosen *at* 8x8 (down to 4x4, already refused
16714 /// at `decode.rs`'s `part8 != PARTITION_NONE` check) or
16715 /// `allow_screen_content_tools`, neither reaching a leaf. Kept anyway
16716 /// (mirrors this file's own `never_fired`-skip convention) as the
16717 /// honest record of the attempt; a real 8x8 OBMC fixture needs
16718 /// higher-frequency content than this gate's fixtures use, out of
16719 /// round-3 budget.
16720 #[test]
16721 fn a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact() {
16722 const NAME: &str = "a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact";
16723 let _gate_lock = lock_gate_counters();
16724 if !have_ffmpeg() {
16725 eprintln!("SKIP {NAME}: no ffmpeg");
16726 return;
16727 }
16728 if !have_aomenc() {
16729 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16730 return;
16731 }
16732 let (width, height, frame_count) = (64usize, 64usize, 24usize);
16733 let mut refusals = Vec::new();
16734 let mut never_fired = 0u32;
16735 let mut total_obmc8 = 0usize;
16736 let n_attempts: u32 = std::env::var("EC_OBMC8_ATTEMPTS")
16737 .ok()
16738 .and_then(|s| s.parse().ok())
16739 .unwrap_or(80);
16740 for attempt in 0..n_attempts {
16741 let seed = 42 + attempt % 40;
16742 let duration = frame_count as f64 / 25.0;
16743 // Recipe search hook: `gradients` is smooth, so aomenc's RD never
16744 // splits below 16x16 and this gate never fired one 8x8 OBMC block
16745 // in 45 attempts -- it "passed" by skipping (gate-blind-to-feature).
16746 // EC_AV1_OBMC8_SOURCE overrides the lavfi source so a firing recipe
16747 // can be searched for without a rebuild.
16748 let source = std::env::var("EC_AV1_OBMC8_SOURCE").unwrap_or_else(|_| {
16749 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
16750 });
16751 // A source supplied through EC_AV1_OBMC8_SOURCE need not carry its
16752 // own `duration=`; `-t` is the bound that always holds. Without it
16753 // an endless source (`testsrc2`) fills the pipe forever and the
16754 // gate hangs to its 300 s timeout.
16755 let duration_arg = format!("{duration}");
16756 let y4m = Command::new("ffmpeg")
16757 .args([
16758 "-v",
16759 "error",
16760 "-f",
16761 "lavfi",
16762 "-i",
16763 &source,
16764 "-t",
16765 &duration_arg,
16766 "-pix_fmt",
16767 "yuv420p",
16768 "-f",
16769 "yuv4mpegpipe",
16770 "-",
16771 ])
16772 .stdin(Stdio::null())
16773 .stdout(Stdio::piped())
16774 .stderr(Stdio::piped())
16775 .output()
16776 .expect("ffmpeg failed to run");
16777 assert!(
16778 y4m.status.success(),
16779 "ffmpeg fixture: {}",
16780 String::from_utf8_lossy(&y4m.stderr)
16781 );
16782 let args: Vec<&str> = vec![
16783 "--codec=av1",
16784 "--passes=1",
16785 "--end-usage=q",
16786 "--cq-level=45",
16787 "--cpu-used=0",
16788 "--kf-max-dist=1000",
16789 "--threads=1",
16790 "--row-mt=0",
16791 "--auto-alt-ref=1",
16792 "--lag-in-frames=16",
16793 "--enable-fwd-kf=0",
16794 "--enable-order-hint=1",
16795 "--enable-warped-motion=0",
16796 "--enable-obmc=1",
16797 "--enable-masked-comp=0",
16798 "--enable-interintra-comp=0",
16799 "--enable-onesided-comp=0",
16800 "--enable-interintra-wedge=0",
16801 "--enable-smooth-interintra=0",
16802 "--enable-rect-partitions=0",
16803 "--enable-ab-partitions=0",
16804 "--enable-1to4-partitions=0",
16805 "--enable-filter-intra=0",
16806 "--enable-smooth-intra=0",
16807 "--enable-paeth-intra=0",
16808 "--enable-directional-intra=0",
16809 "--enable-angle-delta=0",
16810 "--enable-tx-size-search=0",
16811 "--enable-cdef=0",
16812 "--enable-restoration=0",
16813 "--min-partition-size=8",
16814 "--max-partition-size=32",
16815 "--enable-palette=0",
16816 "--enable-intrabc=0",
16817 "--enable-cfl-intra=0",
16818 "--enable-ref-frame-mvs=0",
16819 "--obu",
16820 "-o",
16821 "-",
16822 "-",
16823 ];
16824 let mut child = Command::new(aomenc_path())
16825 .args(&args)
16826 .stdin(Stdio::piped())
16827 .stdout(Stdio::piped())
16828 .stderr(Stdio::piped())
16829 .spawn()
16830 .expect("aomenc failed to start");
16831 child
16832 .stdin
16833 .take()
16834 .expect("aomenc stdin")
16835 .write_all(&y4m.stdout)
16836 .expect("writing y4m to aomenc");
16837 let out = child.wait_with_output().expect("aomenc failed to run");
16838 assert!(
16839 out.status.success(),
16840 "aomenc refused the fixture: {}",
16841 String::from_utf8_lossy(&out.stderr)
16842 );
16843 let stream = out.stdout;
16844 let before8 = decode::obmc_hits_8();
16845 let frames = match decode_stream(&stream) {
16846 Err(e) => {
16847 let msg = e.to_string();
16848 assert!(
16849 msg.contains("unsupported"),
16850 "{NAME} failed outright (seed {seed}): {msg}"
16851 );
16852 refusals.push(format!("seed {seed}: {msg}"));
16853 continue;
16854 }
16855 Ok(frames) => frames,
16856 };
16857 let fired8 = decode::obmc_hits_8() - before8;
16858 total_obmc8 += fired8;
16859 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
16860 // is ALWAYS pixel-compared below; the hit counter only decides whether
16861 // the attempt counts toward the firing total.
16862 let counted = fired8 != 0;
16863 if !counted {
16864 never_fired += 1;
16865 }
16866 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
16867 assert_eq!(frames.len(), frame_count);
16868 let mismatched = frames
16869 .iter()
16870 .zip(&ffmpeg_frames)
16871 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16872 if mismatched {
16873 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
16874 std::fs::write(&path, &stream).expect("writing pinned stream");
16875 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
16876 }
16877 }
16878 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16879 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
16880 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
16881 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
16882 }
16883 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
16884 // stream again, comparing EVERY decode-order frame -- the hidden
16885 // (show_frame == 0) alt-ref frames the ffmpeg compare above
16886 // cannot see, because both sides of it emit shown frames only.
16887 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
16888 eprintln!(
16889 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
16890 {hidden_n} hidden, all pixel-exact vs the oracle"
16891 );
16892 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
16893 // libaom's temporal alt-ref filter absorbs this recipe's hidden
16894 // frames, so the compare above is vacuous -- re-encode the same
16895 // fixture with --arnr-maxframes=0 and compare THOSE.
16896 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
16897 eprintln!(
16898 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
16899 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
16900 );
16901 }
16902 if counted {
16903 eprintln!(
16904 "{NAME} FIRING seed {seed}: 8x8 obmc hits {fired8} (total across attempts so far {total_obmc8})"
16905 );
16906 gate_buckets(NAME, 1, never_fired, refusals.len());
16907 return;
16908 }
16909 }
16910 gate_buckets(NAME, 0, never_fired, refusals.len());
16911 // lane-gmaffine r2: this gate fired for three rounds only as a SKIP
16912 // (gate-skips-on-its-own-failure); the 8x8 leaf is reachable now, so a
16913 // sweep that never lands one firing pixel-exact attempt is a FAILURE.
16914 panic!(
16915 "{NAME}: {never_fired} attempts decoded but never fired an 8x8 obmc block \
16916 ({total_obmc8} total 8x8 obmc hits across all attempts), and every other attempt \
16917 hit a named refusal:\n{}",
16918 refusals.join("\n")
16919 );
16920 }
16921
16922 /// lane-warp r5e (flipped from lane-motionmode r1's refuses-or-matches):
16923 /// `--enable-warped-motion=1` streams must DECODE pixel-exact --
16924 /// `av1_findSamples`/`num_proj_ref`, the 3-symbol `motion_mode` read,
16925 /// the affine projection/filter, and the WARPED_CAUSAL interp-filter
16926 /// derivation are all ported. A refusal naming warp, or any pixel
16927 /// mismatch, fails the gate; refusals for OTHER named capabilities
16928 /// (screen content tools) still skip that seed. The sweep must also
16929 /// actually exercise warp (`warp_selected_hits > 0`) so a decoder that
16930 /// silently stops selecting WARPED_CAUSAL cannot pass vacuously.
16931 #[test]
16932 fn a_real_aomenc_stream_with_warped_motion_refuses_or_matches() {
16933 const NAME: &str = "a_real_aomenc_stream_with_warped_motion_refuses_or_matches";
16934 let _gate_lock = lock_gate_counters();
16935 if !have_ffmpeg() {
16936 eprintln!("SKIP {NAME}: no ffmpeg");
16937 return;
16938 }
16939 if !have_aomenc() {
16940 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16941 return;
16942 }
16943 let (width, height, frame_count) = (64usize, 64usize, 24usize);
16944 let mut named_refusals = 0u32;
16945 let mut matched = 0u32;
16946 let n_attempts: u32 = std::env::var("EC_WARP_GATE_ATTEMPTS")
16947 .ok()
16948 .and_then(|s| s.parse().ok())
16949 .unwrap_or(40);
16950 for attempt in 0..n_attempts {
16951 let seed = 42 + attempt;
16952 let duration = frame_count as f64 / 25.0;
16953 let source =
16954 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
16955 let y4m = Command::new("ffmpeg")
16956 .args([
16957 "-v",
16958 "error",
16959 "-f",
16960 "lavfi",
16961 "-i",
16962 &source,
16963 "-pix_fmt",
16964 "yuv420p",
16965 "-f",
16966 "yuv4mpegpipe",
16967 "-",
16968 ])
16969 .stdin(Stdio::null())
16970 .stdout(Stdio::piped())
16971 .stderr(Stdio::piped())
16972 .output()
16973 .expect("ffmpeg failed to run");
16974 assert!(
16975 y4m.status.success(),
16976 "ffmpeg fixture: {}",
16977 String::from_utf8_lossy(&y4m.stderr)
16978 );
16979 let args: Vec<&str> = vec![
16980 "--codec=av1",
16981 "--passes=1",
16982 "--end-usage=q",
16983 "--cq-level=45",
16984 "--cpu-used=0",
16985 "--kf-max-dist=1000",
16986 "--threads=1",
16987 "--row-mt=0",
16988 "--auto-alt-ref=1",
16989 "--lag-in-frames=16",
16990 "--enable-fwd-kf=0",
16991 "--enable-order-hint=1",
16992 "--enable-warped-motion=1",
16993 "--enable-obmc=1",
16994 "--tune-content=default",
16995 "--enable-masked-comp=0",
16996 "--enable-interintra-comp=0",
16997 "--enable-onesided-comp=0",
16998 "--enable-interintra-wedge=0",
16999 "--enable-smooth-interintra=0",
17000 "--enable-rect-partitions=0",
17001 "--enable-ab-partitions=0",
17002 "--enable-1to4-partitions=0",
17003 "--enable-filter-intra=0",
17004 "--enable-smooth-intra=0",
17005 "--enable-paeth-intra=0",
17006 "--enable-directional-intra=0",
17007 "--enable-angle-delta=0",
17008 "--enable-tx-size-search=0",
17009 "--enable-cdef=0",
17010 "--enable-restoration=0",
17011 "--max-partition-size=32",
17012 "--min-partition-size=32",
17013 "--enable-palette=0",
17014 "--enable-intrabc=0",
17015 "--enable-cfl-intra=0",
17016 "--enable-ref-frame-mvs=0",
17017 "--obu",
17018 "-o",
17019 "-",
17020 "-",
17021 ];
17022 let mut child = Command::new(aomenc_path())
17023 .args(&args)
17024 .stdin(Stdio::piped())
17025 .stdout(Stdio::piped())
17026 .stderr(Stdio::piped())
17027 .spawn()
17028 .expect("aomenc failed to start");
17029 child
17030 .stdin
17031 .take()
17032 .expect("aomenc stdin")
17033 .write_all(&y4m.stdout)
17034 .expect("writing y4m to aomenc");
17035 let out = child.wait_with_output().expect("aomenc failed to run");
17036 assert!(
17037 out.status.success(),
17038 "aomenc refused the fixture: {}",
17039 String::from_utf8_lossy(&out.stderr)
17040 );
17041 let stream = out.stdout;
17042 let frames = match decode_stream(&stream) {
17043 Err(e) => {
17044 let msg = e.to_string();
17045 assert!(
17046 msg.contains("unsupported"),
17047 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
17048 );
17049 assert!(
17050 !msg.contains("warp"),
17051 "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \
17052 refusal must not exist: {msg}"
17053 );
17054 named_refusals += 1;
17055 eprintln!("seed {seed} refusal (non-warp capability): {msg}");
17056 continue;
17057 }
17058 Ok(frames) => frames,
17059 };
17060 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17061 assert_eq!(frames.len(), frame_count);
17062 let mismatched = frames
17063 .iter()
17064 .zip(&ffmpeg_frames)
17065 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17066 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17067 std::fs::write(&path, &stream).expect("writing pinned stream");
17068 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
17069 }
17070 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17071 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
17072 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
17073 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
17074 }
17075 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
17076 // stream again, comparing EVERY decode-order frame -- the hidden
17077 // (show_frame == 0) alt-ref frames the ffmpeg compare above
17078 // cannot see, because both sides of it emit shown frames only.
17079 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
17080 eprintln!(
17081 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
17082 {hidden_n} hidden, all pixel-exact vs the oracle"
17083 );
17084 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
17085 // libaom's temporal alt-ref filter absorbs this recipe's hidden
17086 // frames, so the compare above is vacuous -- re-encode the same
17087 // fixture with --arnr-maxframes=0 and compare THOSE.
17088 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
17089 eprintln!(
17090 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
17091 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
17092 );
17093 }
17094 matched += 1;
17095 }
17096 assert!(
17097 matched > 0,
17098 "{NAME}: every attempt refused on other capabilities; the gate never exercised warp"
17099 );
17100 assert!(
17101 crate::decode::warp_selected_hits() > 0,
17102 "{NAME}: {matched} matches but zero WARPED_CAUSAL blocks fired -- the gate decodes \
17103 warp streams without ever selecting warp, so it proves nothing about warp"
17104 );
17105 eprintln!(
17106 "{NAME}: {named_refusals} non-warp refusals, {matched} pixel-exact matches out of {n_attempts}, warp_selected_hits={}",
17107 crate::decode::warp_selected_hits()
17108 );
17109 }
17110
17111 /// lane-superres stage 3: a real aomenc `--superres-mode=1` key-frame
17112 /// sequence must decode pixel-exact vs ffmpeg/dav1d's own upscaled
17113 /// output, and must actually run [`crate::superres::upscale_picture`]
17114 /// (`superres_hits > 0`) -- a decoder that silently stopped upscaling
17115 /// would otherwise pass vacuously (class `gate-blind-to-feature`).
17116 /// `--kf-max-dist` set to the frame count keeps every frame a key
17117 /// frame: inter-frame superres (a differently-scaled reference) is a
17118 /// later stage of this lane, refused by name today.
17119 #[test]
17120 fn a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact() {
17121 const NAME: &str = "a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact";
17122 let _gate_lock = lock_gate_counters();
17123 if !have_ffmpeg() {
17124 eprintln!("SKIP {NAME}: no ffmpeg");
17125 return;
17126 }
17127 if !have_aomenc() {
17128 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17129 return;
17130 }
17131 let (width, height, frame_count) = (64usize, 64usize, 3usize);
17132 let duration = frame_count as f64 / 25.0;
17133 let source = gradients_source(7, width, height, &format!("duration={duration}:rate=25"));
17134 let y4m = Command::new("ffmpeg")
17135 .args([
17136 "-v",
17137 "error",
17138 "-f",
17139 "lavfi",
17140 "-i",
17141 &source,
17142 "-pix_fmt",
17143 "yuv420p",
17144 "-f",
17145 "yuv4mpegpipe",
17146 "-",
17147 ])
17148 .stdin(Stdio::null())
17149 .stdout(Stdio::piped())
17150 .stderr(Stdio::piped())
17151 .output()
17152 .expect("ffmpeg failed to run");
17153 assert!(
17154 y4m.status.success(),
17155 "ffmpeg fixture: {}",
17156 String::from_utf8_lossy(&y4m.stderr)
17157 );
17158 let args: Vec<&str> = vec![
17159 "--codec=av1",
17160 "--passes=1",
17161 "--end-usage=q",
17162 "--cq-level=32",
17163 "--cpu-used=0",
17164 "--kf-max-dist=0",
17165 "--threads=1",
17166 "--row-mt=0",
17167 "--superres-mode=1",
17168 "--superres-denominator=12",
17169 "--superres-kf-denominator=12",
17170 "--enable-rect-partitions=0",
17171 "--enable-ab-partitions=0",
17172 "--enable-1to4-partitions=0",
17173 "--enable-filter-intra=0",
17174 "--enable-smooth-intra=0",
17175 "--enable-paeth-intra=0",
17176 "--enable-directional-intra=0",
17177 "--enable-angle-delta=0",
17178 "--enable-tx-size-search=0",
17179 "--enable-cdef=0",
17180 "--enable-restoration=0",
17181 "--max-partition-size=32",
17182 "--min-partition-size=32",
17183 "--enable-palette=0",
17184 "--enable-intrabc=0",
17185 "--enable-cfl-intra=0",
17186 "--obu",
17187 "-o",
17188 "-",
17189 "-",
17190 ];
17191 let mut child = Command::new(aomenc_path())
17192 .args(&args)
17193 .stdin(Stdio::piped())
17194 .stdout(Stdio::piped())
17195 .stderr(Stdio::piped())
17196 .spawn()
17197 .expect("aomenc failed to start");
17198 child
17199 .stdin
17200 .take()
17201 .expect("aomenc stdin")
17202 .write_all(&y4m.stdout)
17203 .expect("writing y4m to aomenc");
17204 let out = child.wait_with_output().expect("aomenc failed to run");
17205 assert!(
17206 out.status.success(),
17207 "aomenc refused the fixture: {}",
17208 String::from_utf8_lossy(&out.stderr)
17209 );
17210 let stream = out.stdout;
17211 if let Ok(path) = std::env::var("EC_SUPERRES_STREAM_DUMP") {
17212 std::fs::write(path, &stream).expect("dump stream");
17213 }
17214 let frames =
17215 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}"));
17216 assert_eq!(frames.len(), frame_count);
17217 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17218 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17219 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
17220 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
17221 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
17222 }
17223 assert!(
17224 crate::superres::superres_hits() > 0,
17225 "{NAME}: matched but zero superres_hits -- the gate never actually exercised the \
17226 upscaler, it proves nothing"
17227 );
17228 eprintln!(
17229 "{NAME}: {frame_count} frames pixel-exact, superres_hits={}",
17230 crate::superres::superres_hits()
17231 );
17232 }
17233
17234 /// lane-superres r10: a real aomenc key+inter `--superres-mode=1`
17235 /// sequence must DECODE pixel-exact vs ffmpeg, with the frame-level
17236 /// `use_superres` refusal LIFTED for inter frames -- `mc::predict_scaled`
17237 /// (spec 7.11.3.3) is the only path this recipe can reach (warp/OBMC/
17238 /// compound/interintra/palette/intrabc/CDEF/LR are all off, matching the
17239 /// scoped refusals' own unimplemented list). A pixel match alone would
17240 /// pass just as well with an unscaled reference and prove nothing
17241 /// (class `gate-blind-to-feature`) -- hard-assert
17242 /// `crate::mc::predict_scaled_hits() > 0` so the gate can only pass if the
17243 /// scaled MC path actually ran.
17244 #[test]
17245 fn a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact() {
17246 const NAME: &str = "a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact";
17247 let _gate_lock = lock_gate_counters();
17248 if !have_ffmpeg() {
17249 eprintln!("SKIP {NAME}: no ffmpeg");
17250 return;
17251 }
17252 if !have_aomenc() {
17253 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17254 return;
17255 }
17256 let (width, height, frame_count) = (64usize, 64usize, 3usize);
17257 let duration = frame_count as f64 / 25.0;
17258 let source = gradients_source(11, width, height, &format!("duration={duration}:rate=25"));
17259 let y4m = Command::new("ffmpeg")
17260 .args([
17261 "-v",
17262 "error",
17263 "-f",
17264 "lavfi",
17265 "-i",
17266 &source,
17267 "-pix_fmt",
17268 "yuv420p",
17269 "-f",
17270 "yuv4mpegpipe",
17271 "-",
17272 ])
17273 .stdin(Stdio::null())
17274 .stdout(Stdio::piped())
17275 .stderr(Stdio::piped())
17276 .output()
17277 .expect("ffmpeg failed to run");
17278 assert!(
17279 y4m.status.success(),
17280 "ffmpeg fixture: {}",
17281 String::from_utf8_lossy(&y4m.stderr)
17282 );
17283 let args: Vec<&str> = vec![
17284 "--codec=av1",
17285 "--passes=1",
17286 "--end-usage=q",
17287 "--cq-level=32",
17288 "--cpu-used=0",
17289 // `--kf-max-dist` above `frame_count` keeps only frame 0 a key
17290 // frame -- frames 1/2 are the inter frames whose `use_superres`
17291 // refusal this round lifts.
17292 "--kf-max-dist=1000",
17293 "--lag-in-frames=0",
17294 "--auto-alt-ref=0",
17295 "--threads=1",
17296 "--row-mt=0",
17297 "--sb-size=64",
17298 "--superres-mode=1",
17299 "--superres-denominator=12",
17300 "--superres-kf-denominator=12",
17301 // Forces every inter block onto the single-ref, non-warp/OBMC/
17302 // interintra branch `decode_inter_block` threads `predict_scaled`
17303 // through -- the only branch this round's scoped refusals leave
17304 // unrefused under a scaled reference.
17305 "--enable-warped-motion=0",
17306 "--enable-obmc=0",
17307 "--enable-masked-comp=0",
17308 "--enable-interintra-comp=0",
17309 "--enable-dist-wtd-comp=0",
17310 "--enable-diff-wtd-comp=0",
17311 "--enable-onesided-comp=0",
17312 "--enable-interintra-wedge=0",
17313 "--enable-smooth-interintra=0",
17314 "--enable-order-hint=0",
17315 "--enable-ref-frame-mvs=0",
17316 "--enable-rect-partitions=0",
17317 "--enable-ab-partitions=0",
17318 "--enable-1to4-partitions=0",
17319 "--enable-filter-intra=0",
17320 "--enable-smooth-intra=0",
17321 "--enable-paeth-intra=0",
17322 "--enable-directional-intra=0",
17323 "--enable-angle-delta=0",
17324 "--enable-tx-size-search=0",
17325 "--enable-cdef=0",
17326 "--enable-restoration=0",
17327 "--max-partition-size=32",
17328 "--min-partition-size=32",
17329 "--enable-palette=0",
17330 "--enable-intrabc=0",
17331 "--enable-cfl-intra=0",
17332 "--obu",
17333 "-o",
17334 "-",
17335 "-",
17336 ];
17337 let mut child = Command::new(aomenc_path())
17338 .args(&args)
17339 .stdin(Stdio::piped())
17340 .stdout(Stdio::piped())
17341 .stderr(Stdio::piped())
17342 .spawn()
17343 .expect("aomenc failed to start");
17344 child
17345 .stdin
17346 .take()
17347 .expect("aomenc stdin")
17348 .write_all(&y4m.stdout)
17349 .expect("writing y4m to aomenc");
17350 let out = child.wait_with_output().expect("aomenc failed to run");
17351 assert!(
17352 out.status.success(),
17353 "aomenc refused the fixture: {}",
17354 String::from_utf8_lossy(&out.stderr)
17355 );
17356 let stream = out.stdout;
17357 if let Ok(path) = std::env::var("EC_SUPERRES_INTER_STREAM_DUMP") {
17358 std::fs::write(&path, &stream).expect("dump stream");
17359 }
17360 let frames =
17361 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}"));
17362 assert_eq!(frames.len(), frame_count);
17363 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17364 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17365 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
17366 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
17367 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
17368 }
17369 assert!(
17370 crate::superres::superres_hits() > 0,
17371 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
17372 );
17373 assert!(
17374 crate::mc::predict_scaled_hits() > 0,
17375 "{NAME}: matched but zero predict_scaled_hits -- every block took the unscaled MC \
17376 path, which proves nothing about the scaled-reference code this round adds \
17377 (class gate-blind-to-feature)"
17378 );
17379 eprintln!(
17380 "{NAME}: {frame_count} frames pixel-exact, superres_hits={}, predict_scaled_hits={}",
17381 crate::superres::superres_hits(),
17382 crate::mc::predict_scaled_hits()
17383 );
17384 }
17385
17386 /// lane-t900 r28: the three scaled-reference (superres) refusals are
17387 /// LIFTED -- an 8x8 partition leaf, a sub-8x8 inter block, and warp --
17388 /// so two real `--superres-mode=1` streams whose references are all
17389 /// scaled must decode PIXEL-EXACT vs ffmpeg.
17390 ///
17391 /// Arm A drives `--min-partition-size=4` so the split (4x4) and rect
17392 /// (8x4/4x8) sub-8x8 readers and the 8x8 leaf all run over a scaled
17393 /// reference; arm B turns `--enable-warped-motion=1` on, which is the
17394 /// root cause this round fixed: libaom `motion_mode_allowed` drops
17395 /// WARPED_CAUSAL eligibility when `av1_is_scaled(sf)`, so the 8x8 leaf
17396 /// must read the 2-symbol obmc alphabet (here: no symbol at all, OBMC
17397 /// off) instead of the 3-symbol motion_mode row.
17398 ///
17399 /// Each arm hard-asserts its own counter (class `gate-blind-to-feature`):
17400 /// a pixel match with zero scaled leaves/sub-8x8 blocks/suppressed warp
17401 /// eligibilities would prove nothing.
17402 #[test]
17403 fn real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact() {
17404 const NAME: &str = "real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact";
17405 let _gate_lock = lock_gate_counters();
17406 if !have_ffmpeg() {
17407 eprintln!("SKIP {NAME}: no ffmpeg");
17408 return;
17409 }
17410 if !have_aomenc() {
17411 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17412 return;
17413 }
17414 // Every tool whose scaled-reference path this round does NOT touch is
17415 // off, so a mismatch can only be the lifted paths (the same scoping
17416 // the r10 key+inter superres gate uses).
17417 let common: [&str; 21] = [
17418 "--codec=av1", "--passes=1", "--end-usage=q", "--threads=1", "--row-mt=0",
17419 "--kf-max-dist=9999", "--lag-in-frames=0", "--auto-alt-ref=0", "--cpu-used=0",
17420 "--sb-size=64", "--superres-mode=1", "--superres-denominator=12",
17421 "--superres-kf-denominator=12", "--enable-obmc=0", "--enable-masked-comp=0",
17422 "--enable-interintra-comp=0", "--enable-tx-size-search=0", "--enable-cdef=0",
17423 "--enable-restoration=0", "--enable-palette=0", "--enable-intrabc=0",
17424 ];
17425 struct Arm {
17426 name: &'static str,
17427 frames: usize,
17428 cq: &'static str,
17429 extra: [&'static str; 4],
17430 }
17431 let arms = [
17432 Arm {
17433 name: "sub8+leaf8",
17434 frames: 4,
17435 cq: "--cq-level=4",
17436 extra: [
17437 "--enable-warped-motion=0",
17438 "--enable-rect-partitions=1",
17439 "--max-partition-size=32",
17440 "--min-partition-size=4",
17441 ],
17442 },
17443 Arm {
17444 name: "warp",
17445 frames: 6,
17446 cq: "--cq-level=20",
17447 extra: [
17448 "--enable-warped-motion=1",
17449 "--enable-rect-partitions=1",
17450 "--max-partition-size=32",
17451 "--min-partition-size=8",
17452 ],
17453 },
17454 ];
17455 let (width, height) = (96usize, 96usize);
17456 for arm in &arms {
17457 let duration = format!("{}", arm.frames as f64 / 25.0);
17458 let src = format!("mandelbrot=size={width}x{height}:rate=25");
17459 let y4m = Command::new("ffmpeg")
17460 .args([
17461 "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt",
17462 "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
17463 ])
17464 .stdin(Stdio::null())
17465 .stdout(Stdio::piped())
17466 .stderr(Stdio::piped())
17467 .output()
17468 .expect("ffmpeg failed to run");
17469 assert!(y4m.status.success(), "{NAME}: ffmpeg refused the fixture");
17470 let limit = format!("--limit={}", arm.frames);
17471 let mut args: Vec<&str> = common.to_vec();
17472 args.push(&limit);
17473 args.push(arm.cq);
17474 args.extend_from_slice(&arm.extra);
17475 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
17476 let mut child = Command::new(aomenc_path())
17477 .args(&args)
17478 .stdin(Stdio::piped())
17479 .stdout(Stdio::piped())
17480 .stderr(Stdio::piped())
17481 .spawn()
17482 .expect("aomenc failed to start");
17483 child
17484 .stdin
17485 .take()
17486 .expect("aomenc stdin")
17487 .write_all(&y4m.stdout)
17488 .expect("writing y4m to aomenc");
17489 let out = child.wait_with_output().expect("aomenc failed to run");
17490 assert!(
17491 out.status.success(),
17492 "{NAME} {}: aomenc refused the recipe: {}",
17493 arm.name,
17494 String::from_utf8_lossy(&out.stderr)
17495 );
17496 let stream = out.stdout;
17497 let leaf8_before = crate::decode::scaled_leaf8_hits();
17498 let sub8_before = crate::decode::scaled_sub8_hits();
17499 let warp_before = crate::decode::scaled_warp_suppressed_hits();
17500 let frames = decode_stream(&stream)
17501 .unwrap_or_else(|e| panic!("{NAME} {}: refused: {e}", arm.name));
17502 assert_eq!(frames.len(), arm.frames, "{NAME} {}", arm.name);
17503 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, arm.frames);
17504 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17505 assert_eq!(got.y, want.y, "{NAME} {} frame {i} luma vs ffmpeg", arm.name);
17506 assert_eq!(got.u, want.u, "{NAME} {} frame {i} U vs ffmpeg", arm.name);
17507 assert_eq!(got.v, want.v, "{NAME} {} frame {i} V vs ffmpeg", arm.name);
17508 }
17509 let (leaf8, sub8, warp) = (
17510 crate::decode::scaled_leaf8_hits() - leaf8_before,
17511 crate::decode::scaled_sub8_hits() - sub8_before,
17512 crate::decode::scaled_warp_suppressed_hits() - warp_before,
17513 );
17514 eprintln!(
17515 "{NAME} {}: {} frames pixel-exact, scaled leaf8={leaf8} sub8={sub8} \
17516 warp_suppressed={warp}",
17517 arm.name, arm.frames
17518 );
17519 if arm.name == "sub8+leaf8" {
17520 assert!(leaf8 > 0 && sub8 > 0, "{NAME} {}: the lifted paths never ran (leaf8={leaf8} sub8={sub8})", arm.name);
17521 } else {
17522 assert!(
17523 warp > 0,
17524 "{NAME} {}: no block reached WARPED_CAUSAL eligibility under a scaled \
17525 reference, so the alphabet fix is unexercised",
17526 arm.name
17527 );
17528 }
17529 }
17530 }
17531
17532 /// lane-interintra r1: `--enable-interintra-comp=1` streams must DECODE
17533 /// pixel-exact -- the interintra flag/mode/wedge-flag syntax and the
17534 /// non-wedge smooth blend are ported. A refusal naming interintra fails
17535 /// the gate UNLESS it is the wedge refusal (`use_wedge_interintra == 1`
17536 /// is r2, and this recipe encodes with wedge off so it must not fire
17537 /// either); warp/obmc are enabled and supported; refusals for OTHER
17538 /// named capabilities (screen content tools) still skip that seed. The
17539 /// sweep must actually exercise interintra (`interintra_hits > 0`).
17540 #[test]
17541 fn a_real_aomenc_stream_with_interintra_decodes_pixel_exact() {
17542 const NAME: &str = "a_real_aomenc_stream_with_interintra_decodes_pixel_exact";
17543 let _gate_lock = lock_gate_counters();
17544 if !have_ffmpeg() {
17545 eprintln!("SKIP {NAME}: no ffmpeg");
17546 return;
17547 }
17548 if !have_aomenc() {
17549 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17550 return;
17551 }
17552 let (width, height, frame_count) = (64usize, 64usize, 24usize);
17553 // lane-midcut r1: rect interintra (`write_w != write_h`) built its
17554 // intra predictor at the square `side`; this gate passed with that
17555 // bug, so the shape gets its own delta-counted assert below.
17556 let rect_before = crate::decode::interintra_rect_hits();
17557 let mut named_refusals = 0u32;
17558 let mut matched = 0u32;
17559 let n_attempts: u32 = std::env::var("EC_INTERINTRA_GATE_ATTEMPTS")
17560 .ok()
17561 .and_then(|s| s.parse().ok())
17562 .unwrap_or(40);
17563 for attempt in 0..n_attempts {
17564 let seed = 42 + attempt;
17565 let duration = frame_count as f64 / 25.0;
17566 let source =
17567 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
17568 let y4m = Command::new("ffmpeg")
17569 .args([
17570 "-v",
17571 "error",
17572 "-f",
17573 "lavfi",
17574 "-i",
17575 &source,
17576 "-pix_fmt",
17577 "yuv420p",
17578 "-f",
17579 "yuv4mpegpipe",
17580 "-",
17581 ])
17582 .stdin(Stdio::null())
17583 .stdout(Stdio::piped())
17584 .stderr(Stdio::piped())
17585 .output()
17586 .expect("ffmpeg failed to run");
17587 assert!(
17588 y4m.status.success(),
17589 "ffmpeg fixture: {}",
17590 String::from_utf8_lossy(&y4m.stderr)
17591 );
17592 let args: Vec<&str> = vec![
17593 "--codec=av1",
17594 "--passes=1",
17595 "--end-usage=q",
17596 "--cq-level=45",
17597 "--cpu-used=0",
17598 "--kf-max-dist=1000",
17599 "--threads=1",
17600 "--row-mt=0",
17601 "--auto-alt-ref=1",
17602 "--lag-in-frames=16",
17603 "--enable-fwd-kf=0",
17604 "--enable-order-hint=1",
17605 "--enable-warped-motion=1",
17606 "--enable-obmc=1",
17607 "--tune-content=default",
17608 "--enable-masked-comp=0",
17609 "--enable-interintra-comp=1",
17610 "--enable-onesided-comp=1",
17611 "--enable-interintra-wedge=0",
17612 "--enable-smooth-interintra=1",
17613 "--enable-rect-partitions=0",
17614 "--enable-ab-partitions=0",
17615 "--enable-1to4-partitions=0",
17616 "--enable-filter-intra=0",
17617 "--enable-smooth-intra=0",
17618 "--enable-paeth-intra=0",
17619 "--enable-directional-intra=0",
17620 "--enable-angle-delta=0",
17621 "--enable-tx-size-search=0",
17622 "--enable-cdef=0",
17623 "--enable-restoration=0",
17624 "--max-partition-size=32",
17625 "--min-partition-size=32",
17626 "--enable-palette=0",
17627 "--enable-intrabc=0",
17628 "--enable-cfl-intra=0",
17629 "--enable-ref-frame-mvs=0",
17630 "--obu",
17631 "-o",
17632 "-",
17633 "-",
17634 ];
17635 let mut child = Command::new(aomenc_path())
17636 .args(&args)
17637 .stdin(Stdio::piped())
17638 .stdout(Stdio::piped())
17639 .stderr(Stdio::piped())
17640 .spawn()
17641 .expect("aomenc failed to start");
17642 child
17643 .stdin
17644 .take()
17645 .expect("aomenc stdin")
17646 .write_all(&y4m.stdout)
17647 .expect("writing y4m to aomenc");
17648 let out = child.wait_with_output().expect("aomenc failed to run");
17649 assert!(
17650 out.status.success(),
17651 "aomenc refused the fixture: {}",
17652 String::from_utf8_lossy(&out.stderr)
17653 );
17654 let stream = out.stdout;
17655 let frames = match decode_stream(&stream) {
17656 Err(e) => {
17657 let msg = e.to_string();
17658 assert!(
17659 msg.contains("unsupported"),
17660 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
17661 );
17662 assert!(
17663 !msg.contains("warp"),
17664 "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \
17665 refusal must not exist: {msg}"
17666 );
17667 assert!(
17668 !msg.contains("interintra"),
17669 "{NAME} refused on interintra (seed {seed}) -- non-wedge interintra \
17670 is ported and this recipe encodes with wedge off: {msg}"
17671 );
17672 named_refusals += 1;
17673 eprintln!("seed {seed} refusal (non-warp capability): {msg}");
17674 continue;
17675 }
17676 Ok(frames) => frames,
17677 };
17678 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17679 assert_eq!(frames.len(), frame_count);
17680 let mismatched = frames
17681 .iter()
17682 .zip(&ffmpeg_frames)
17683 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17684 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17685 std::fs::write(&path, &stream).expect("writing pinned stream");
17686 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
17687 }
17688 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17689 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
17690 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
17691 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
17692 }
17693 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
17694 // stream again, comparing EVERY decode-order frame -- the hidden
17695 // (show_frame == 0) alt-ref frames the ffmpeg compare above
17696 // cannot see, because both sides of it emit shown frames only.
17697 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
17698 eprintln!(
17699 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
17700 {hidden_n} hidden, all pixel-exact vs the oracle"
17701 );
17702 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
17703 // libaom's temporal alt-ref filter absorbs this recipe's hidden
17704 // frames, so the compare above is vacuous -- re-encode the same
17705 // fixture with --arnr-maxframes=0 and compare THOSE.
17706 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
17707 eprintln!(
17708 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
17709 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
17710 );
17711 }
17712 // lane-midcut r3 RECT ARM: the recipe above spells
17713 // `--enable-rect-partitions=0 --min-partition-size=32`, so it can
17714 // never produce a RECT interintra block -- the delta assert at the
17715 // end of this gate was unsatisfiable on it (the gate disabled the
17716 // very shape it claims to prove). Re-encode the SAME source with
17717 // the rect overrides APPENDED (aomenc keeps the LAST occurrence of
17718 // a repeated flag) and compare every decode-order frame of that
17719 // stream against aomdec, until a rect interintra block fires.
17720 if crate::decode::interintra_rect_hits() == rect_before {
17721 let mut rect_args = args.clone();
17722 rect_args.extend_from_slice(&[
17723 "--enable-rect-partitions=1",
17724 "--min-partition-size=8",
17725 "--max-partition-size=64",
17726 ]);
17727 let mut child = Command::new(aomenc_path())
17728 .args(&rect_args)
17729 .stdin(Stdio::piped())
17730 .stdout(Stdio::piped())
17731 .stderr(Stdio::piped())
17732 .spawn()
17733 .expect("aomenc failed to start");
17734 child
17735 .stdin
17736 .take()
17737 .expect("aomenc stdin")
17738 .write_all(&y4m.stdout)
17739 .expect("writing y4m to aomenc");
17740 let out = child.wait_with_output().expect("aomenc failed to run");
17741 assert!(
17742 out.status.success(),
17743 "{NAME} RECT-ARM: aomenc refused its own recipe plus the rect overrides: {}",
17744 String::from_utf8_lossy(&out.stderr)
17745 );
17746 let rect_stream = out.stdout;
17747 match decode_stream(&rect_stream) {
17748 Err(e) => {
17749 let msg = e.to_string();
17750 assert!(
17751 msg.contains("unsupported"),
17752 "{NAME} RECT-ARM failed outright, not a named refusal (seed {seed}): {msg}"
17753 );
17754 eprintln!("{NAME} RECT-ARM: skipped on a named refusal: {msg}");
17755 }
17756 Ok(_) => {
17757 let (total, hidden) =
17758 decode_all_frames_vs_oracle(&rect_stream, &format!("{NAME}-rect"));
17759 eprintln!(
17760 "{NAME} RECT-ARM: seed {seed}: {total} decode-order frames, {hidden} \
17761 hidden, all pixel-exact vs the oracle, interintra_rect_hits={}",
17762 crate::decode::interintra_rect_hits() - rect_before
17763 );
17764 }
17765 }
17766 }
17767 matched += 1;
17768 }
17769 assert!(
17770 matched > 0,
17771 "{NAME}: every attempt refused on other capabilities; the gate never exercised warp"
17772 );
17773 assert!(
17774 crate::decode::interintra_hits() > 0,
17775 "{NAME}: {matched} matches but zero interintra blocks fired -- the gate decodes \
17776 these streams without ever taking interintra, so it proves nothing"
17777 );
17778 // lane-defon r1: `--enable-onesided-comp=1` is spelled on this
17779 // recipe, so a UNIDIR_COMP_REFERENCE pair must actually have been
17780 // read -- otherwise the on-value proves nothing.
17781 assert!(
17782 crate::decode::uni_comp_hits() > 0,
17783 "{NAME}: {matched} matches but zero UNIDIR_COMP_REFERENCE pairs read -- \
17784 --enable-onesided-comp=1 never reached the uni_comp_ref alphabet"
17785 );
17786 assert!(
17787 crate::decode::interintra_rect_hits() > rect_before,
17788 "{NAME}: {matched} matches but zero RECTANGULAR interintra blocks fired -- the \
17789 square-only blend defect (lane-midcut r1) would pass this gate unseen"
17790 );
17791 eprintln!(
17792 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, interintra_hits={} interintra_rect_hits={} uni_comp_hits={}",
17793 crate::decode::interintra_hits(),
17794 crate::decode::interintra_rect_hits() - rect_before,
17795 crate::decode::uni_comp_hits()
17796 );
17797 }
17798
17799 /// lane-scaledref r1: a real aomenc `--superres-mode=1` sequence with
17800 /// compound, OBMC, interintra and 8x8 leaves ALL enabled must decode
17801 /// pixel-exact -- these are the combinations the three
17802 /// "... with a scaled reference (superres, unimplemented)" refusals used
17803 /// to cover. Each combination gets its OWN hard-asserted hit counter
17804 /// (`crate::decode::scaled_*_hits`), because an unscaled reference would
17805 /// pass the pixels and prove nothing (class `gate-blind-to-feature`), and
17806 /// a stream that scales but never takes compound/OBMC/interintra/8x8
17807 /// would prove nothing about the code this round adds either. A refusal
17808 /// naming a scaled reference is a hard failure: those are exactly the
17809 /// strings this round lifts. Other named capabilities skip that seed.
17810 #[test]
17811 fn a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact()
17812 {
17813 const NAME: &str = "a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact";
17814 let _gate_lock = lock_gate_counters();
17815 if !have_ffmpeg() {
17816 eprintln!("SKIP {NAME}: no ffmpeg");
17817 return;
17818 }
17819 if !have_aomenc() {
17820 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17821 return;
17822 }
17823 let (width, height, frame_count) = (64usize, 64usize, 24usize);
17824 let mut named_refusals = 0u32;
17825 let mut matched = 0u32;
17826 let n_attempts: u32 = std::env::var("EC_SCALEDREF_GATE_ATTEMPTS")
17827 .ok()
17828 .and_then(|s| s.parse().ok())
17829 .unwrap_or(12);
17830 for attempt in 0..n_attempts {
17831 let seed = 42 + attempt;
17832 let duration = frame_count as f64 / 25.0;
17833 let source =
17834 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
17835 let y4m = Command::new("ffmpeg")
17836 .args([
17837 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
17838 "yuv4mpegpipe", "-",
17839 ])
17840 .stdin(Stdio::null())
17841 .stdout(Stdio::piped())
17842 .stderr(Stdio::piped())
17843 .output()
17844 .expect("ffmpeg failed to run");
17845 assert!(
17846 y4m.status.success(),
17847 "ffmpeg fixture: {}",
17848 String::from_utf8_lossy(&y4m.stderr)
17849 );
17850 let on = |name: &str| {
17851 if std::env::var(name).as_deref() == Ok("0") { "0" } else { "1" }
17852 };
17853 // lane-scaledref r2: warp is ON. A warp-capable frame header
17854 // under a scaled reference is exactly the case r1 got wrong
17855 // (the block must read the 2-symbol `obmc_cdf`, not the
17856 // 3-symbol `motion_mode_cdf` -- libaom `motion_mode_allowed`,
17857 // blockd.h:1484), and it decoded silently wrong pixels rather
17858 // than refusing. `EC_SCALEDREF_WARP=0` turns it off for
17859 // bisecting only.
17860 let warp = format!("--enable-warped-motion={}", on("EC_SCALEDREF_WARP"));
17861 // lane-scaledref r2: `EC_SCALEDREF_MODE=3` (qthresh) lets
17862 // superres switch on and off per frame, so a compound block can
17863 // reference one scaled and one unscaled reference -- the mixed
17864 // case mode 1 (every frame scaled) never produces.
17865 let superres_mode = format!(
17866 "--superres-mode={}",
17867 std::env::var("EC_SCALEDREF_MODE").unwrap_or_else(|_| "1".into())
17868 );
17869 let obmc = format!("--enable-obmc={}", on("EC_SCALEDREF_OBMC"));
17870 let interintra = format!("--enable-interintra-comp={}", on("EC_SCALEDREF_II"));
17871 let lag = format!(
17872 "--lag-in-frames={}",
17873 if on("EC_SCALEDREF_COMP") == "0" { "0" } else { "25" }
17874 );
17875 let alt_ref = format!("--auto-alt-ref={}", on("EC_SCALEDREF_COMP"));
17876 let args: Vec<&str> = vec![
17877 "--codec=av1",
17878 "--passes=1",
17879 "--end-usage=q",
17880 "--cq-level=45",
17881 "--cpu-used=0",
17882 "--kf-max-dist=1000",
17883 "--threads=1",
17884 "--row-mt=0",
17885 "--sb-size=64",
17886 // superres on every frame, key and inter alike -- the scaled
17887 // reference this gate is about.
17888 // denominator 16 (the maximum) keeps the CODED frame
17889 // 32x64 -- a multiple of 16 both ways, so no frame-edge
17890 // 16x16 straddle forces a sub-16x16 partition this decoder
17891 // still refuses on the aligned path ("an inter partition
17892 // below 16x16"). Denominator 12 codes 43 columns and every
17893 // seed refused there.
17894 &superres_mode,
17895 "--superres-denominator=16",
17896 "--superres-kf-denominator=16",
17897 // the four combinations this round lifts (each switchable
17898 // by env for bisecting a mismatch without a rebuild)
17899 &alt_ref,
17900 &lag,
17901 "--enable-order-hint=1",
17902 &warp,
17903 &obmc,
17904 &interintra,
17905 "--enable-smooth-interintra=1",
17906 "--enable-interintra-wedge=0",
17907 "--enable-masked-comp=0",
17908 "--enable-onesided-comp=0",
17909 "--enable-fwd-kf=0",
17910 "--tune-content=default",
17911 "--max-partition-size=32",
17912 "--min-partition-size=32",
17913 // everything this decoder still refuses under any reference
17914 "--enable-rect-partitions=0",
17915 "--enable-ab-partitions=0",
17916 "--enable-1to4-partitions=0",
17917 "--enable-filter-intra=0",
17918 "--enable-smooth-intra=0",
17919 "--enable-paeth-intra=0",
17920 "--enable-directional-intra=0",
17921 "--enable-angle-delta=0",
17922 "--enable-tx-size-search=0",
17923 "--enable-cdef=0",
17924 "--enable-restoration=0",
17925 "--enable-palette=0",
17926 "--enable-intrabc=0",
17927 "--enable-cfl-intra=0",
17928 "--enable-ref-frame-mvs=0",
17929 "--obu",
17930 "-o",
17931 "-",
17932 "-",
17933 ];
17934 let mut child = Command::new(aomenc_path())
17935 .args(&args)
17936 .stdin(Stdio::piped())
17937 .stdout(Stdio::piped())
17938 .stderr(Stdio::piped())
17939 .spawn()
17940 .expect("aomenc failed to start");
17941 child
17942 .stdin
17943 .take()
17944 .expect("aomenc stdin")
17945 .write_all(&y4m.stdout)
17946 .expect("writing y4m to aomenc");
17947 let out = child.wait_with_output().expect("aomenc failed to run");
17948 assert!(
17949 out.status.success(),
17950 "aomenc refused the fixture: {}",
17951 String::from_utf8_lossy(&out.stderr)
17952 );
17953 let stream = out.stdout;
17954 let frames = match decode_stream(&stream) {
17955 Err(e) => {
17956 let msg = e.to_string();
17957 assert!(
17958 msg.contains("unsupported"),
17959 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
17960 );
17961 assert!(
17962 !msg.contains("scaled reference"),
17963 "{NAME} refused on a scaled reference (seed {seed}) -- those refusals \
17964 are exactly what this round lifts: {msg}"
17965 );
17966 named_refusals += 1;
17967 eprintln!("seed {seed} refusal (other capability): {msg}");
17968 continue;
17969 }
17970 Ok(frames) => frames,
17971 };
17972 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17973 assert_eq!(frames.len(), frame_count);
17974 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17975 let mismatched = frames
17976 .iter()
17977 .zip(&ffmpeg_frames)
17978 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17979 if mismatched {
17980 std::fs::write(&path, &stream).expect("writing pinned stream");
17981 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
17982 }
17983 }
17984 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17985 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
17986 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
17987 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
17988 }
17989 matched += 1;
17990 }
17991 eprintln!(
17992 "{NAME}: {named_refusals} other-capability refusals, {matched}/{n_attempts} pixel-exact, \
17993 superres_hits={} predict_scaled_hits={} scaled_compound={} scaled_warp_fallback={} \
17994 scaled_obmc={} scaled_interintra={} scaled_block8={} scaled_warp_suppressed={} mixed_scale_compound={}",
17995 crate::superres::superres_hits(),
17996 crate::mc::predict_scaled_hits(),
17997 crate::decode::scaled_compound_hits(),
17998 crate::decode::scaled_warp_fallback_hits(),
17999 crate::decode::scaled_obmc_hits(),
18000 crate::decode::scaled_interintra_hits(),
18001 crate::decode::scaled_block8_hits(),
18002 crate::decode::scaled_warp_suppressed_hits(),
18003 crate::decode::mixed_scale_compound_hits(),
18004 );
18005 assert!(
18006 matched > 0,
18007 "{NAME}: every attempt refused on other capabilities; the gate proves nothing"
18008 );
18009 assert!(
18010 crate::mc::predict_scaled_hits() > 0,
18011 "{NAME}: matched but zero predict_scaled_hits -- no block took the scaled MC path"
18012 );
18013 // The 8x8 leaf is NOT asserted here: it stays refused (no recipe
18014 // produced an 8x8 inter leaf at all), so its counter is a
18015 // diagnostic only -- see this gate's own doc and decode.rs.
18016 // `scaled_warp_suppressed` IS asserted: it counts the blocks whose
18017 // WARPED_CAUSAL eligibility libaom drops because the reference is
18018 // scaled, i.e. the blocks that must read `obmc_cdf`. Zero of them
18019 // would mean this gate's `--enable-warped-motion=1` never reached a
18020 // warp-eligible block and proves nothing about r2's fix.
18021 assert!(
18022 crate::decode::scaled_warp_suppressed_hits() > 0,
18023 "{NAME}: {matched} matches but no block had its warp eligibility \
18024 suppressed by a scaled reference -- the warp arm proves nothing"
18025 );
18026 for (hits, what) in [
18027 (crate::decode::scaled_compound_hits(), "compound with a scaled reference"),
18028 (crate::decode::scaled_obmc_hits(), "OBMC with a scaled reference"),
18029 (crate::decode::scaled_interintra_hits(), "interintra with a scaled reference"),
18030 ] {
18031 assert!(hits > 0, "{NAME}: {matched} matches but zero blocks took {what}");
18032 }
18033 }
18034
18035 /// lane-defon r1: the 10-bit one-sided-compound hole --
18036 /// `--enable-onesided-comp` was spelled on in no 10-bit gate (5 of the 15
18037 /// pin it off, the rest default), so the UNIDIR_COMP_REFERENCE alphabet
18038 /// was proven at 8 bits only while both of his films are 10-bit 4:2:0.
18039 /// `--enable-diff-wtd-comp=1` is deliberately NOT spelled here (a flag a
18040 /// gate turns on without asserting it fired is coverage theatre, class
18041 /// gate-blind-to-feature): measured this round, the 10-bit `gradients`
18042 /// fixture decodes 8/8 pixel-exact with `diffwtd_hits == 0` -- smooth
18043 /// gradients never win
18044 /// a difference-weighted mask (the 8-bit gate needs `mandelbrot`'s hard
18045 /// diagonal edge, and [`ten_bit_tool_gate`] has no mandelbrot source), so
18046 /// hard-asserting it here would fail on encoder choice, not on a decoder
18047 /// defect.
18048 #[test]
18049 fn a_real_aomenc_10bit_stream_with_onesided_compound_decodes_pixel_exact() {
18050 const NAME: &str = "a_real_aomenc_10bit_stream_with_onesided_compound_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 ten_bit_tool_gate(
18061 NAME,
18062 64,
18063 64,
18064 24,
18065 &[
18066 "--enable-onesided-comp=1",
18067 "--enable-masked-comp=1",
18068 "--enable-dist-wtd-comp=0",
18069 "--cq-level=45",
18070 "--kf-max-dist=1000",
18071 "--auto-alt-ref=1",
18072 "--lag-in-frames=16",
18073 "--enable-fwd-kf=0",
18074 "--enable-order-hint=1",
18075 "--enable-global-motion=0",
18076 "--enable-warped-motion=1",
18077 "--enable-obmc=1",
18078 "--tune-content=default",
18079 "--enable-interintra-comp=0",
18080 "--enable-interintra-wedge=0",
18081 "--enable-smooth-interintra=0",
18082 "--enable-rect-partitions=0",
18083 "--enable-ab-partitions=0",
18084 "--enable-1to4-partitions=0",
18085 "--enable-filter-intra=0",
18086 "--enable-smooth-intra=0",
18087 "--enable-paeth-intra=0",
18088 "--enable-directional-intra=0",
18089 "--enable-angle-delta=0",
18090 "--enable-tx-size-search=0",
18091 "--enable-cdef=0",
18092 "--enable-restoration=0",
18093 "--max-partition-size=32",
18094 "--min-partition-size=32",
18095 "--enable-palette=0",
18096 "--enable-intrabc=0",
18097 "--enable-cfl-intra=0",
18098 "--enable-ref-frame-mvs=0",
18099 ],
18100 &[42, 43, 44, 45, 46, 47, 48, 49],
18101 &[("uni_comp_hits", crate::decode::uni_comp_hits as fn() -> usize)],
18102 );
18103 }
18104
18105 /// lane-defon r1: the 10-bit sibling of
18106 /// [`a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact`] --
18107 /// `--enable-interintra-wedge=1` was spelled on in no 10-bit gate (5 of
18108 /// the 15 pin it off), and his two films are 10-bit, so the 8-bit
18109 /// gate alone proves nothing about the streams that matter. Same tool
18110 /// set as the 8-bit recipe (`--enable-masked-comp=0` keeps inter blocks
18111 /// off the COMPOUND_WEDGE path, fixed 32x32 partitions), driven through
18112 /// [`ten_bit_tool_gate`], which hard-asserts `wii_hits` moved and
18113 /// compares every plane against ffmpeg's own 10-bit decode.
18114 #[test]
18115 fn a_real_aomenc_10bit_stream_with_interintra_wedge_decodes_pixel_exact() {
18116 const NAME: &str = "a_real_aomenc_10bit_stream_with_interintra_wedge_decodes_pixel_exact";
18117 let _gate_lock = lock_gate_counters();
18118 if !have_ffmpeg() {
18119 eprintln!("SKIP {NAME}: no ffmpeg");
18120 return;
18121 }
18122 if !have_aomenc() {
18123 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18124 return;
18125 }
18126 ten_bit_tool_gate(
18127 NAME,
18128 64,
18129 64,
18130 24,
18131 &[
18132 "--enable-interintra-wedge=1",
18133 "--enable-interintra-comp=1",
18134 "--enable-smooth-interintra=1",
18135 "--cq-level=45",
18136 "--kf-max-dist=1000",
18137 "--auto-alt-ref=1",
18138 "--lag-in-frames=16",
18139 "--enable-fwd-kf=0",
18140 "--enable-order-hint=1",
18141 "--enable-warped-motion=1",
18142 "--enable-obmc=1",
18143 "--tune-content=default",
18144 "--enable-masked-comp=0",
18145 "--enable-onesided-comp=0",
18146 "--enable-rect-partitions=0",
18147 "--enable-ab-partitions=0",
18148 "--enable-1to4-partitions=0",
18149 "--enable-filter-intra=0",
18150 "--enable-smooth-intra=0",
18151 "--enable-paeth-intra=0",
18152 "--enable-directional-intra=0",
18153 "--enable-angle-delta=0",
18154 "--enable-tx-size-search=0",
18155 "--enable-cdef=0",
18156 "--enable-restoration=0",
18157 "--max-partition-size=32",
18158 "--min-partition-size=32",
18159 "--enable-palette=0",
18160 "--enable-intrabc=0",
18161 "--enable-cfl-intra=0",
18162 "--enable-ref-frame-mvs=0",
18163 ],
18164 &[42, 43, 44, 45, 46, 47, 48, 49],
18165 &[
18166 ("wii_hits", crate::decode::wii_hits as fn() -> usize),
18167 ("interintra_hits", crate::decode::interintra_hits as fn() -> usize),
18168 ],
18169 );
18170 }
18171
18172 /// lane-wii r2: `--enable-interintra-wedge=1` streams must DECODE
18173 /// pixel-exact -- the wedge-interintra syntax (adapting `wedge_index`
18174 /// CDF symbol, fixed sign 0) and the wedge mask blend are ported over
18175 /// the checksum-verified codebook. `--enable-masked-comp=0` stays so
18176 /// the encoder cannot route inter blocks through the still-unported
18177 /// COMPOUND_WEDGE/DIFFWTD path. A refusal naming interintra/wedge
18178 /// fails the gate; refusals for OTHER named capabilities still skip
18179 /// that seed. Zero `wii_hits` on a run means the encoder never
18180 /// selected wedge-interintra -- soft-skipped (warned), not failed:
18181 /// that is encoder choice, not a decoder bug.
18182 #[test]
18183 fn a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact() {
18184 const NAME: &str = "a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact";
18185 let _gate_lock = lock_gate_counters();
18186 if !have_ffmpeg() {
18187 eprintln!("SKIP {NAME}: no ffmpeg");
18188 return;
18189 }
18190 if !have_aomenc() {
18191 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18192 return;
18193 }
18194 let (width, height, frame_count) = (64usize, 64usize, 24usize);
18195 let mut named_refusals = 0u32;
18196 let mut matched = 0u32;
18197 let n_attempts: u32 = std::env::var("EC_WEDGE_GATE_ATTEMPTS")
18198 .ok()
18199 .and_then(|s| s.parse().ok())
18200 .unwrap_or(40);
18201 for attempt in 0..n_attempts {
18202 let seed = 42 + attempt;
18203 let duration = frame_count as f64 / 25.0;
18204 let source = if attempt % 2 == 0 {
18205 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
18206 } else {
18207 // `end_pts` does NOT bound mandelbrot (it generated 300+
18208 // frames and hung the gate for an hour); `-t` below is the
18209 // real bound, matching every other mandelbrot gate recipe.
18210 format!("mandelbrot=size={width}x{height}:rate=25")
18211 };
18212 let duration_arg = format!("{duration}");
18213 let y4m = Command::new("ffmpeg")
18214 .args([
18215 "-v",
18216 "error",
18217 "-f",
18218 "lavfi",
18219 "-i",
18220 &source,
18221 "-pix_fmt",
18222 "yuv420p",
18223 "-t",
18224 &duration_arg,
18225 "-f",
18226 "yuv4mpegpipe",
18227 "-",
18228 ])
18229 .stdin(Stdio::null())
18230 .stdout(Stdio::piped())
18231 .stderr(Stdio::piped())
18232 .output()
18233 .expect("ffmpeg failed to run");
18234 assert!(
18235 y4m.status.success(),
18236 "ffmpeg fixture: {}",
18237 String::from_utf8_lossy(&y4m.stderr)
18238 );
18239 let args: Vec<&str> = vec![
18240 "--codec=av1",
18241 "--passes=1",
18242 "--end-usage=q",
18243 "--cq-level=45",
18244 "--cpu-used=0",
18245 "--kf-max-dist=1000",
18246 "--threads=1",
18247 "--row-mt=0",
18248 "--auto-alt-ref=1",
18249 "--lag-in-frames=16",
18250 "--enable-fwd-kf=0",
18251 "--enable-order-hint=1",
18252 "--enable-warped-motion=1",
18253 "--enable-obmc=1",
18254 "--tune-content=default",
18255 "--enable-masked-comp=0",
18256 "--enable-interintra-comp=1",
18257 "--enable-onesided-comp=0",
18258 "--enable-interintra-wedge=1",
18259 "--enable-smooth-interintra=1",
18260 "--enable-rect-partitions=0",
18261 "--enable-ab-partitions=0",
18262 "--enable-1to4-partitions=0",
18263 "--enable-filter-intra=0",
18264 "--enable-smooth-intra=0",
18265 "--enable-paeth-intra=0",
18266 "--enable-directional-intra=0",
18267 "--enable-angle-delta=0",
18268 "--enable-tx-size-search=0",
18269 "--enable-cdef=0",
18270 "--enable-restoration=0",
18271 "--max-partition-size=32",
18272 "--min-partition-size=32",
18273 "--enable-palette=0",
18274 "--enable-intrabc=0",
18275 "--enable-cfl-intra=0",
18276 "--enable-ref-frame-mvs=0",
18277 "--obu",
18278 "-o",
18279 "-",
18280 "-",
18281 ];
18282 let mut child = Command::new(aomenc_path())
18283 .args(&args)
18284 .stdin(Stdio::piped())
18285 .stdout(Stdio::piped())
18286 .stderr(Stdio::piped())
18287 .spawn()
18288 .expect("aomenc failed to start");
18289 child
18290 .stdin
18291 .take()
18292 .expect("aomenc stdin")
18293 .write_all(&y4m.stdout)
18294 .expect("writing y4m to aomenc");
18295 let out = child.wait_with_output().expect("aomenc failed to run");
18296 assert!(
18297 out.status.success(),
18298 "aomenc refused the fixture: {}",
18299 String::from_utf8_lossy(&out.stderr)
18300 );
18301 let stream = out.stdout;
18302 let frames = match decode_stream(&stream) {
18303 Err(e) => {
18304 let msg = e.to_string();
18305 assert!(
18306 msg.contains("unsupported"),
18307 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
18308 );
18309 // Verifier note (lane-wii r2): no refusal string containing
18310 // "wedge"/"interintra" exists in the decoder any more, so
18311 // string-forbidding asserts here would be vacuous (class
18312 // gate-blind-to-feature). The proof this gate carries is
18313 // pixel-exact decode plus the wii_hits count printed below.
18314 named_refusals += 1;
18315 eprintln!("seed {seed} refusal (non-wedge capability): {msg}");
18316 continue;
18317 }
18318 Ok(frames) => frames,
18319 };
18320 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
18321 assert_eq!(frames.len(), frame_count);
18322 let mismatched = frames
18323 .iter()
18324 .zip(&ffmpeg_frames)
18325 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
18326 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
18327 std::fs::write(&path, &stream).expect("writing pinned stream");
18328 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
18329 }
18330 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18331 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
18332 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
18333 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
18334 }
18335 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
18336 // stream again, comparing EVERY decode-order frame -- the hidden
18337 // (show_frame == 0) alt-ref frames the ffmpeg compare above
18338 // cannot see, because both sides of it emit shown frames only.
18339 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
18340 eprintln!(
18341 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
18342 {hidden_n} hidden, all pixel-exact vs the oracle"
18343 );
18344 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
18345 // libaom's temporal alt-ref filter absorbs this recipe's hidden
18346 // frames, so the compare above is vacuous -- re-encode the same
18347 // fixture with --arnr-maxframes=0 and compare THOSE.
18348 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
18349 eprintln!(
18350 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
18351 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
18352 );
18353 }
18354 matched += 1;
18355 }
18356 assert!(
18357 matched > 0,
18358 "{NAME}: every attempt refused on other capabilities; the gate never exercised wedge-interintra"
18359 );
18360 // Hardened from a soft-note (verifier: gate-blind-to-feature): the
18361 // recipe fired wedge-interintra on EVERY one of 6 hammer runs
18362 // (wii_hits 2-7), so a zero-hit run is a regression, not sampling.
18363 assert!(
18364 crate::decode::wii_hits() > 0,
18365 "{NAME}: {matched} pixel-exact matches but zero wedge-interintra blocks fired -- \
18366 the blend is unexercised (recipe fired 2-7 hits per run when landed)"
18367 );
18368 eprintln!(
18369 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, wii_hits={}",
18370 crate::decode::wii_hits()
18371 );
18372 }
18373
18374 /// The affine-capable encoder (`scripts/build-aom-affine-oracle.sh`),
18375 /// separate from the shared oracle because stock libaom's global-motion
18376 /// model search is pinned to ROTZOOM and can never emit AFFINE.
18377 fn affine_aomenc_path() -> std::path::PathBuf {
18378 if let Some(p) = std::env::var_os("EC_AV1_AFFINE_AOMENC") {
18379 return std::path::PathBuf::from(p);
18380 }
18381 let home = std::env::var_os("HOME").unwrap_or_default();
18382 std::path::PathBuf::from(home).join(".cache/aom-affine/build/aomenc")
18383 }
18384
18385 fn have_affine_aomenc() -> bool {
18386 let present = affine_aomenc_path().is_file();
18387 assert!(
18388 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
18389 "EC_AV1_REQUIRE_AOMENC is set but no affine-capable aomenc at {} -- run \
18390 scripts/build-aom-affine-oracle.sh",
18391 affine_aomenc_path().display()
18392 );
18393 present
18394 }
18395
18396 /// lane-gmaffine r1: an inter frame whose `global_motion_params` carries a
18397 /// SIX-parameter (`AFFINE`) model for a single-reference frame -- refused
18398 /// by name since lane-gm r4 because no aomenc recipe ever reached it.
18399 /// The reason it never did is in libaom's own encoder, not in the
18400 /// content: `av1/encoder/global_motion_facade.c:24` pins the model search
18401 /// to `ROTZOOM` at both ends, so *no* `--enable-global-motion=1` command
18402 /// line over any source can produce the case. The decoder must still
18403 /// handle it (the bitstream allows it, `read_global_motion_params` reads
18404 /// params 4/5 with their own subexp references, and ffmpeg decodes it),
18405 /// so this gate widens exactly that one encoder-side search range in a
18406 /// side build and encodes with it. Everything downstream is ordinary
18407 /// libaom and the pixel oracle is still ffmpeg.
18408 ///
18409 /// Content: rotation composed with a progressive *anisotropic* stretch --
18410 /// a similarity transform plus unequal axis scaling is precisely what a
18411 /// 4-parameter ROTZOOM model cannot express, which is what makes the
18412 /// encoder's RD pick AFFINE. `affine_gm_hits()` hard-asserts that real
18413 /// blocks were predicted through the 6-parameter warp, not merely that a
18414 /// header parsed one (class `gate-blind-to-feature`).
18415 #[test]
18416 fn a_real_affine_global_motion_stream_decodes_pixel_exact() {
18417 const NAME: &str = "a_real_affine_global_motion_stream_decodes_pixel_exact";
18418 let _gate_lock = lock_gate_counters();
18419 if !have_ffmpeg() {
18420 eprintln!("SKIP {NAME}: no ffmpeg");
18421 return;
18422 }
18423 if !have_affine_aomenc() {
18424 eprintln!(
18425 "SKIP {NAME}: no affine-capable aomenc at {} (scripts/build-aom-affine-oracle.sh)",
18426 affine_aomenc_path().display()
18427 );
18428 return;
18429 }
18430 let (width, height, frame_count) = (64usize, 64usize, 24usize);
18431 let duration = frame_count as f64 / 25.0;
18432 // Both depths: his own AV1 library is yuv420p10le throughout, and a
18433 // 10-bit AFFINE warp runs the same `warp_affine` over wider samples.
18434 for depth in [8u32, 10u32] {
18435 // `-t` is the real bound on mandelbrot (it ignores `end_pts` and
18436 // has hung a gate for an hour); the 96x96 source is rotated and
18437 // then stretched horizontally only, and cropped back to 64x64.
18438 let source = format!(
18439 "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\
18440 scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}"
18441 );
18442 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
18443 let mut ff_args: Vec<&str> =
18444 vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt];
18445 // y4m has no official 10-bit tag, same as the 10-bit gate above.
18446 if depth == 10 {
18447 ff_args.extend(["-strict", "-1"]);
18448 }
18449 let duration_arg = duration.to_string();
18450 ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]);
18451 let y4m = Command::new("ffmpeg")
18452 .args(&ff_args)
18453 .stdin(Stdio::null())
18454 .stdout(Stdio::piped())
18455 .stderr(Stdio::piped())
18456 .output()
18457 .expect("ffmpeg failed to run");
18458 assert!(
18459 y4m.status.success(),
18460 "ffmpeg fixture: {}",
18461 String::from_utf8_lossy(&y4m.stderr)
18462 );
18463 let bit_depth = format!("--bit-depth={depth}");
18464 let input_bit_depth = format!("--input-bit-depth={depth}");
18465 let args: Vec<&str> = vec![
18466 "--codec=av1",
18467 "--passes=1",
18468 "--end-usage=q",
18469 "--cq-level=45",
18470 "--cpu-used=0",
18471 "--kf-max-dist=1000",
18472 "--threads=1",
18473 "--row-mt=0",
18474 "--auto-alt-ref=0",
18475 "--lag-in-frames=0",
18476 "--enable-fwd-kf=0",
18477 "--enable-order-hint=1",
18478 "--enable-global-motion=1",
18479 "--enable-warped-motion=0",
18480 "--enable-obmc=0",
18481 "--tune-content=default",
18482 "--enable-masked-comp=0",
18483 "--enable-interintra-comp=0",
18484 "--enable-onesided-comp=0",
18485 "--enable-rect-partitions=0",
18486 "--enable-ab-partitions=0",
18487 "--enable-1to4-partitions=0",
18488 "--enable-filter-intra=0",
18489 "--enable-smooth-intra=0",
18490 "--enable-paeth-intra=0",
18491 "--enable-directional-intra=0",
18492 "--enable-angle-delta=0",
18493 "--enable-tx-size-search=0",
18494 "--enable-cdef=0",
18495 "--enable-restoration=0",
18496 "--max-partition-size=32",
18497 "--min-partition-size=32",
18498 "--enable-palette=0",
18499 "--enable-intrabc=0",
18500 "--enable-cfl-intra=0",
18501 "--enable-ref-frame-mvs=0",
18502 &bit_depth,
18503 &input_bit_depth,
18504 "--obu",
18505 "-o",
18506 "-",
18507 "-",
18508 ];
18509 let mut child = Command::new(affine_aomenc_path())
18510 .args(&args)
18511 .stdin(Stdio::piped())
18512 .stdout(Stdio::piped())
18513 .stderr(Stdio::piped())
18514 .spawn()
18515 .expect("affine aomenc failed to start");
18516 child
18517 .stdin
18518 .take()
18519 .expect("aomenc stdin")
18520 .write_all(&y4m.stdout)
18521 .expect("writing y4m to aomenc");
18522 let out = child.wait_with_output().expect("aomenc failed to run");
18523 assert!(
18524 out.status.success(),
18525 "aomenc refused the fixture: {}",
18526 String::from_utf8_lossy(&out.stderr)
18527 );
18528 let stream = out.stdout;
18529 let before = crate::decode::affine_gm_hits();
18530 let frames =
18531 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} ({depth}-bit): {e}"));
18532 let ffmpeg_frames = if depth == 10 {
18533 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
18534 } else {
18535 ffmpeg_decode_sequence(&stream, width, height, frame_count)
18536 };
18537 assert_eq!(frames.len(), frame_count);
18538 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18539 assert_eq!(got.y, want.y, "{NAME} {depth}-bit frame {i} luma vs ffmpeg");
18540 assert_eq!(got.u, want.u, "{NAME} {depth}-bit frame {i} U vs ffmpeg");
18541 assert_eq!(got.v, want.v, "{NAME} {depth}-bit frame {i} V vs ffmpeg");
18542 }
18543 let hits = crate::decode::affine_gm_hits() - before;
18544 assert!(
18545 hits > 0,
18546 "{NAME} ({depth}-bit): decoded pixel-exact but no block was predicted through a \
18547 6-parameter global-motion warp -- the AFFINE path is unexercised"
18548 );
18549 eprintln!("{NAME}: {depth}-bit, {frame_count} frames pixel-exact, affine_gm_hits={hits}");
18550 }
18551 }
18552
18553 /// lane-gmaffine r1: the two 8x8-LEAF motion gates. `decode_inter_block8`
18554 /// is a separate function from [`decode_inter_block`], and until this
18555 /// round it refused both `GLOBALMV` ("GLOBALMV (round 3)") and
18556 /// `WARPED_CAUSAL` at that size while the 16x16+ leaf had implemented
18557 /// both for rounds. The reason no earlier gate caught it: the existing
18558 /// 8x8 OBMC gate clamps `--max-partition-size=32` and aomenc's RD then
18559 /// never splits down to a clean 8x8 leaf (that gate has never fired in
18560 /// 80 attempts). `--min-partition-size=8 --max-partition-size=8` removes
18561 /// the choice entirely -- every inter leaf in the stream IS an 8x8 one,
18562 /// so the leaf path is exercised by construction rather than by luck.
18563 ///
18564 /// Content is the affine gate's rotating/zooming mandelbrot (global
18565 /// motion the encoder can actually model), and the hit counters
18566 /// (`globalmv_hits_8` / `warp_hits_8`) are 8x8-leaf-specific: a
18567 /// 16x16-leaf GLOBALMV or warp cannot satisfy them.
18568 fn run_8x8_leaf_motion_gate(
18569 name: &str,
18570 global_motion: bool,
18571 counter: fn() -> usize,
18572 ) {
18573 // 72x64: `decode_inter_block8` is reached ONLY through the
18574 // true-edge-straddling 16x16 path (an interior 16x16
18575 // PARTITION_SPLIT is still refused by name), so the frame is 8
18576 // luma columns wider than its last whole superblock -- every 16x16
18577 // block in that right-hand strip is cut on ONE axis and decodes as
18578 // four 8x8 leaves by construction. `--min-partition-size=16` keeps
18579 // the interior out of the still-refused sub-16x16 case.
18580 let (width, height, frame_count) = (64usize, 64usize, 24usize);
18581 let duration = frame_count as f64 / 25.0;
18582 // The encoder's own RD still chooses WHICH 8x8 leaf codes GLOBALMV /
18583 // WARPED_CAUSAL, and at some quantisers it picks a rect partition at
18584 // 16x16 (still refused) or a non-LAST reference (still refused at the
18585 // 8x8 leaf) before ever reaching one. So sweep a few quantisers and
18586 // require at least one attempt, at each depth, that BOTH decodes
18587 // pixel-exact AND fires the counter -- a refusing attempt is recorded,
18588 // never a pass (class `gate-skips-on-its-own-failure`).
18589 let mut fired_any = [false; 2];
18590 let mut notes: Vec<String> = Vec::new();
18591 for (di, depth) in [8u32, 10u32].into_iter().enumerate() {
18592 for cq in [32u32, 45, 55] {
18593 let cq_arg = format!("--cq-level={cq}");
18594 let max_part_arg = format!(
18595 "--max-partition-size={}",
18596 std::env::var("EC_8X8_MAXPART").unwrap_or_else(|_| "8".into())
18597 );
18598 let source = format!(
18599 "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\
18600 scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}"
18601 );
18602 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
18603 let mut ff_args: Vec<&str> =
18604 vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt];
18605 if depth == 10 {
18606 ff_args.extend(["-strict", "-1"]);
18607 }
18608 let duration_arg = duration.to_string();
18609 ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]);
18610 let y4m = Command::new("ffmpeg")
18611 .args(&ff_args)
18612 .stdin(Stdio::null())
18613 .stdout(Stdio::piped())
18614 .stderr(Stdio::piped())
18615 .output()
18616 .expect("ffmpeg failed to run");
18617 assert!(
18618 y4m.status.success(),
18619 "ffmpeg fixture: {}",
18620 String::from_utf8_lossy(&y4m.stderr)
18621 );
18622 let bit_depth = format!("--bit-depth={depth}");
18623 let input_bit_depth = format!("--input-bit-depth={depth}");
18624 let gm_arg = format!("--enable-global-motion={}", u8::from(global_motion));
18625 let warp_arg = format!("--enable-warped-motion={}", u8::from(!global_motion));
18626 let args: Vec<&str> = vec![
18627 "--codec=av1",
18628 "--passes=1",
18629 "--end-usage=q",
18630 &cq_arg,
18631 "--cpu-used=0",
18632 "--kf-max-dist=1000",
18633 "--threads=1",
18634 "--row-mt=0",
18635 "--auto-alt-ref=0",
18636 "--lag-in-frames=0",
18637 "--enable-fwd-kf=0",
18638 "--enable-order-hint=1",
18639 &gm_arg,
18640 &warp_arg,
18641 "--enable-obmc=0",
18642 "--tune-content=default",
18643 "--enable-masked-comp=0",
18644 "--enable-interintra-comp=0",
18645 "--enable-onesided-comp=0",
18646 "--enable-rect-partitions=0",
18647 "--enable-ab-partitions=0",
18648 "--enable-1to4-partitions=0",
18649 "--enable-filter-intra=0",
18650 "--enable-smooth-intra=0",
18651 "--enable-paeth-intra=0",
18652 "--enable-directional-intra=0",
18653 "--enable-angle-delta=0",
18654 "--enable-tx-size-search=0",
18655 "--enable-cdef=0",
18656 "--enable-restoration=0",
18657 &max_part_arg,
18658 "--min-partition-size=8",
18659 "--enable-palette=0",
18660 "--enable-intrabc=0",
18661 "--enable-cfl-intra=0",
18662 "--enable-ref-frame-mvs=0",
18663 &bit_depth,
18664 &input_bit_depth,
18665 "--obu",
18666 "-o",
18667 "-",
18668 "-",
18669 ];
18670 let mut child = Command::new(aomenc_path())
18671 .args(&args)
18672 .stdin(Stdio::piped())
18673 .stdout(Stdio::piped())
18674 .stderr(Stdio::piped())
18675 .spawn()
18676 .expect("aomenc failed to start");
18677 child
18678 .stdin
18679 .take()
18680 .expect("aomenc stdin")
18681 .write_all(&y4m.stdout)
18682 .expect("writing y4m to aomenc");
18683 let out = child.wait_with_output().expect("aomenc failed to run");
18684 assert!(
18685 out.status.success(),
18686 "aomenc refused the fixture: {}",
18687 String::from_utf8_lossy(&out.stderr)
18688 );
18689 let stream = out.stdout;
18690 let before = counter();
18691 let frames = match decode_stream(&stream) {
18692 Ok(f) => f,
18693 Err(e) => {
18694 let msg = e.to_string();
18695 assert!(
18696 msg.contains("unsupported"),
18697 "{name} ({depth}-bit, cq {cq}) failed outright: {msg}"
18698 );
18699 notes.push(format!("{depth}-bit cq {cq}: {msg}"));
18700 continue;
18701 }
18702 };
18703 let ffmpeg_frames = if depth == 10 {
18704 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
18705 } else {
18706 ffmpeg_decode_sequence(&stream, width, height, frame_count)
18707 };
18708 assert_eq!(frames.len(), frame_count);
18709 let hits = counter() - before;
18710 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18711 assert_eq!(got.y, want.y, "{name} {depth}-bit frame {i} luma vs ffmpeg");
18712 assert_eq!(got.u, want.u, "{name} {depth}-bit frame {i} U vs ffmpeg");
18713 assert_eq!(got.v, want.v, "{name} {depth}-bit frame {i} V vs ffmpeg");
18714 }
18715 if hits == 0 {
18716 notes.push(format!(
18717 "{depth}-bit cq {cq}: {frame_count} frames pixel-exact but 0 8x8-leaf hits"
18718 ));
18719 continue;
18720 }
18721 fired_any[di] = true;
18722 eprintln!(
18723 "{name}: {depth}-bit cq {cq}, {frame_count} frames pixel-exact, 8x8 hits={hits}"
18724 );
18725 }
18726 }
18727 assert!(
18728 fired_any[0] && fired_any[1],
18729 "{name}: no attempt both decoded pixel-exact and fired the 8x8 leaf \
18730 (8-bit fired {}, 10-bit fired {}):\n{}",
18731 fired_any[0], fired_any[1], notes.join("\n")
18732 );
18733 }
18734
18735 /// lane-gmaffine r1 item (3): `GLOBALMV` at an 8x8 leaf, ROTZOOM global
18736 /// motion, warp built from the frame's own model.
18737 #[test]
18738 fn a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact() {
18739 const NAME: &str = "a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact";
18740 let _gate_lock = lock_gate_counters();
18741 if !have_ffmpeg() {
18742 eprintln!("SKIP {NAME}: no ffmpeg");
18743 return;
18744 }
18745 if !have_aomenc() {
18746 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18747 return;
18748 }
18749 run_8x8_leaf_motion_gate(NAME, true, crate::decode::globalmv_hits_8);
18750 }
18751
18752 /// lane-gmaffine r1 item (2): `WARPED_CAUSAL` at an 8x8 leaf --
18753 /// findSamples + `av1_find_projection` + the warp filter at BLOCK_8X8.
18754 #[test]
18755 fn a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact() {
18756 const NAME: &str = "a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact";
18757 let _gate_lock = lock_gate_counters();
18758 if !have_ffmpeg() {
18759 eprintln!("SKIP {NAME}: no ffmpeg");
18760 return;
18761 }
18762 if !have_aomenc() {
18763 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18764 return;
18765 }
18766 run_8x8_leaf_motion_gate(NAME, false, crate::decode::warp_hits_8);
18767 }
18768
18769 /// lane-rect16 r1/r2: a plain default-settings aomenc run over lavfi
18770 /// `mandelbrot` (`--cpu-used=4 --end-usage=q --cq-level=32`, no
18771 /// `--enable-*` flags) used to refuse frame 0 outright with "a partition
18772 /// below 16x16 other than a clean split". r1 root-caused the FIRST hit to
18773 /// a `PARTITION_VERT_B` `partition_w16` symbol at mi=(3,2) and wired it
18774 /// (left 8x16 real `decode_block_rect` strip + two stacked 8x8
18775 /// `decode_leaf8` leaves on the right). r2 re-measured after that fix
18776 /// (`decision-before-quantiser`-shaped: don't trust a stale premise) and
18777 /// found this stream's REAL first-hit blocker in z-order is earlier, at
18778 /// mi=(0,7): a plain `PARTITION_HORZ`. That arm is now wired too
18779 /// (`decode_leaf_rect`, sibling to `decode_leaf8` but real-mi-addressed
18780 /// for a non-square strip) -- `horz_vert_intra_hits` proves it fires.
18781 /// This exact stream's own HORZ block at mi=(0,7) is *coded* (real
18782 /// coefficients), which is NOT ported (same ceiling as VERT_B's own
18783 /// non-skip refusal -- no rectangular-transform coefficient tables at
18784 /// this size), so decode still stops there and `vert_b_intra_hits`
18785 /// never gets a chance to increment on this particular stream. This gate
18786 /// proves the HORZ arm fires and the OLD (now-false) two-clause refusal
18787 /// never reappears, not a pixel-exact decode of this stream.
18788 #[test]
18789 fn a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm() {
18790 const NAME: &str = "a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm";
18791 let _gate_lock = lock_gate_counters();
18792 if !have_ffmpeg() {
18793 eprintln!("SKIP {NAME}: no ffmpeg");
18794 return;
18795 }
18796 if !have_aomenc() {
18797 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18798 return;
18799 }
18800 let (width, height) = (192usize, 128usize);
18801 let y4m = Command::new("ffmpeg")
18802 .args([
18803 "-v",
18804 "error",
18805 "-f",
18806 "lavfi",
18807 "-i",
18808 &format!("mandelbrot=size={width}x{height}"),
18809 "-pix_fmt",
18810 "yuv420p",
18811 "-t",
18812 "1",
18813 "-f",
18814 "yuv4mpegpipe",
18815 "-",
18816 ])
18817 .stdin(Stdio::null())
18818 .stdout(Stdio::piped())
18819 .stderr(Stdio::piped())
18820 .output()
18821 .expect("ffmpeg failed to run");
18822 assert!(
18823 y4m.status.success(),
18824 "ffmpeg fixture: {}",
18825 String::from_utf8_lossy(&y4m.stderr)
18826 );
18827 let mut child = Command::new(aomenc_path())
18828 .args([
18829 "--threads=1",
18830 "--row-mt=0",
18831 "--sb-size=64",
18832 "--cpu-used=4",
18833 "--end-usage=q",
18834 "--cq-level=32",
18835 "--passes=1",
18836 "--obu",
18837 "-o",
18838 "-",
18839 "-",
18840 ])
18841 .stdin(Stdio::piped())
18842 .stdout(Stdio::piped())
18843 .stderr(Stdio::piped())
18844 .spawn()
18845 .expect("aomenc failed to start");
18846 child
18847 .stdin
18848 .take()
18849 .expect("aomenc stdin")
18850 .write_all(&y4m.stdout)
18851 .expect("writing y4m to aomenc");
18852 let out = child.wait_with_output().expect("aomenc failed to run");
18853 assert!(
18854 out.status.success(),
18855 "aomenc refused the fixture: {}",
18856 String::from_utf8_lossy(&out.stderr)
18857 );
18858 let stream = out.stdout;
18859 // lane-rect16 r2: the recipe above was missing `--passes=1` --
18860 // without it aomenc silently ran 2-pass and wrote nothing to stdout
18861 // on pass 1 (still exit 0), so this gate always decoded an EMPTY
18862 // stream and never actually exercised the arm it claims to gate.
18863 assert!(
18864 !stream.is_empty(),
18865 "{NAME}: aomenc wrote an empty stream (missing --passes=1?)"
18866 );
18867 let result = decode_stream(&stream);
18868 // The now-lifted false claim ("codes only the square arms below
18869 // 16x16") must never appear again.
18870 if let Err(e) = &result {
18871 let msg = e.to_string();
18872 assert!(
18873 !msg.contains("this decoder codes only the square arms below 16x16"),
18874 "{NAME}: the OLD (disproved) refusal reappeared: {msg}"
18875 );
18876 }
18877 assert!(
18878 crate::decode::horz_vert_intra_hits() > 0,
18879 "{NAME}: the plain PARTITION_HORZ/VERT arm never fired on this stream (regression -- \
18880 it fired deterministically at mi=(0,7) when this gate was written)"
18881 );
18882 eprintln!(
18883 "{NAME}: horz_vert_intra_hits={}, vert_b_intra_hits={}, decode result: {:?}",
18884 crate::decode::horz_vert_intra_hits(),
18885 crate::decode::vert_b_intra_hits(),
18886 result.as_ref().map(|f| f.len()).map_err(|e| e.to_string())
18887 );
18888 }
18889 /// lane-rectx r3: a real `aomenc` stream whose 16x16-level
18890 /// `PARTITION_HORZ`/`PARTITION_VERT` strips are CODED (non-skip), i.e.
18891 /// carry genuine `TX_16X8`/`TX_8X16` luma coefficients and their
18892 /// `TX_8X4`/`TX_4X8` chroma halves through [`decode_leaf_rect`]'s
18893 /// lane-rectx arm -- the refusal "a coded (non-skip) HORZ/VERT rect strip
18894 /// below 16x16" this round lifts. `--min-partition-size=8
18895 /// --max-partition-size=32 --enable-rect-partitions=1` is what makes
18896 /// aomenc reach for a 16x8 leaf at all; mandelbrot at `cq-level=24` is
18897 /// what makes those leaves non-skip (a gradient fixture codes them all
18898 /// away). `--reduced-tx-type-set=1` pins the five-symbol
18899 /// `EXT_TX_SET_DTT4_IDTX` alphabet: without it aomenc also writes
18900 /// `V_DCT`/`H_DCT`, whose 1D tx classes [`read_coeffs_rect`] still
18901 /// refuses by name (see the r3 report's open residue), so a `=0` run
18902 /// would prove nothing about the 2D path it does support.
18903 ///
18904 /// r2 shipped this path unproven; it was wrong. `TxbSet::LumaRect16x8`
18905 /// read its `tx_type` symbol from the 16x16 row, but libaom's
18906 /// `read_tx_type` indexes `intra_ext_tx_cdf[eset][txsize_sqr_map[tx_size]]`
18907 /// and `txsize_sqr_map[TX_16X8] == TX_8X8` -- a five-symbol CDF where a
18908 /// seven-symbol one belonged, desyncing at the FIRST coded rect leaf
18909 /// (whole frame wrong from pixel (0,0)).
18910 #[test]
18911 fn a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact() {
18912 const NAME: &str =
18913 "a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact";
18914 let _gate_lock = lock_gate_counters();
18915 if !have_ffmpeg() {
18916 eprintln!("SKIP {NAME}: no ffmpeg");
18917 return;
18918 }
18919 if !have_aomenc() {
18920 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18921 return;
18922 }
18923 let (width, height) = (64usize, 64usize);
18924 let y4m = Command::new("ffmpeg")
18925 .args([
18926 "-v",
18927 "error",
18928 "-f",
18929 "lavfi",
18930 "-i",
18931 &format!("mandelbrot=size={width}x{height}:start_x=-0.6"),
18932 "-pix_fmt",
18933 "yuv420p",
18934 "-t",
18935 "1",
18936 "-vframes",
18937 "1",
18938 "-f",
18939 "yuv4mpegpipe",
18940 "-",
18941 ])
18942 .stdin(Stdio::null())
18943 .stdout(Stdio::piped())
18944 .stderr(Stdio::piped())
18945 .output()
18946 .expect("ffmpeg failed to run");
18947 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
18948 let encode = || {
18949 let mut child = Command::new(aomenc_path())
18950 .args([
18951 "--codec=av1",
18952 "--passes=1",
18953 "--end-usage=q",
18954 "--cq-level=16",
18955 "--cpu-used=4",
18956 "--threads=1",
18957 "--row-mt=0",
18958 "--sb-size=64",
18959 "--kf-max-dist=0",
18960 "--enable-rect-partitions=1",
18961 "--enable-ab-partitions=0",
18962 "--enable-1to4-partitions=0",
18963 "--enable-tx-size-search=0",
18964 // Filter intra on a strip is a separate, still-refused
18965 // predictor (`filter intra on a HORZ/VERT strip`); this
18966 // gate is about the rect RESIDUAL path, so it is off here
18967 // and covered by the square filter-intra gate instead.
18968 "--enable-filter-intra=0",
18969 "--reduced-tx-type-set=1",
18970 "--min-partition-size=8",
18971 "--max-partition-size=32",
18972 "--obu",
18973 "-o",
18974 "-",
18975 "-",
18976 ])
18977 .stdin(Stdio::piped())
18978 .stdout(Stdio::piped())
18979 .stderr(Stdio::piped())
18980 .spawn()
18981 .expect("aomenc failed to start");
18982 child
18983 .stdin
18984 .take()
18985 .expect("aomenc stdin")
18986 .write_all(&y4m.stdout)
18987 .expect("writing y4m to aomenc");
18988 let out = child.wait_with_output().expect("aomenc failed to run");
18989 assert!(
18990 out.status.success(),
18991 "aomenc refused the fixture: {}",
18992 String::from_utf8_lossy(&out.stderr)
18993 );
18994 out.stdout
18995 };
18996 // The fixture rule: an encoder output is only a pin if it reproduces.
18997 let stream = encode();
18998 assert_eq!(stream, encode(), "{NAME}: aomenc output is not reproducible for this recipe");
18999 let before = crate::decode::rect_leaf_coeff_hits();
19000 let frames = decode_stream(&stream)
19001 .unwrap_or_else(|e| panic!("{NAME}: decode failed, not a pixel mismatch: {e}"));
19002 let fired = crate::decode::rect_leaf_coeff_hits() - before;
19003 assert!(
19004 fired > 0,
19005 "{NAME}: the stream decoded but no coded (non-skip) rect leaf fired -- \
19006 the gate proves nothing"
19007 );
19008 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
19009 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame");
19010 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
19011 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19012 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg ({fired} coded rect leaves)");
19013 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
19014 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
19015 }
19016 eprintln!("{NAME}: pixel-exact, rect_leaf_coeff_hits={fired}");
19017 }
19018
19019 /// lane-rectx r5: the same 16x8/8x16 rect leaves, but this time proving
19020 /// what a LATER, non-strip block reads from them. `decode_leaf_rect` took
19021 /// the mi-exact intra mode map in r4; `decode_block`/`decode_block_rect`/
19022 /// `decode_block_rect64` did not, so a 32x16 strip whose left neighbour was
19023 /// a 16x8 leaf still read the coarse per-16x16 `left_mode` slot -- which no
19024 /// sub-16x16 block ever writes -- and picked a DIFFERENT `kf_y_mode` CDF row
19025 /// for the same decoded mode value. The stream stayed in sync through mode
19026 /// info (`EC_TRACE_MODE_STEP` ranges match up to that symbol) and then
19027 /// diverged inside the block's own coefficients: the whole bottom-right
19028 /// 32x32 quadrant of this fixture decoded wrong (1650 bytes) while the
19029 /// three earlier quadrants were exact -- wrong pixels returned as success.
19030 /// `mode_mi_override_hits` counts exactly the reads where the mi-exact
19031 /// neighbour disagrees with the coarse slot, so a regression that drops the
19032 /// override again fails the counter as well as the pixels.
19033 #[test]
19034 fn a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact() {
19035 const NAME: &str =
19036 "a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact";
19037 let _gate_lock = lock_gate_counters();
19038 if !have_ffmpeg() {
19039 eprintln!("SKIP {NAME}: no ffmpeg");
19040 return;
19041 }
19042 if !have_aomenc() {
19043 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19044 return;
19045 }
19046 let (width, height) = (64usize, 64usize);
19047 let y4m = Command::new("ffmpeg")
19048 .args([
19049 "-v", "error", "-f", "lavfi", "-i",
19050 &format!("rgbtestsrc=size={width}x{height}"),
19051 "-pix_fmt", "yuv420p", "-t", "1", "-vframes", "1", "-f", "yuv4mpegpipe", "-",
19052 ])
19053 .stdin(Stdio::null())
19054 .stdout(Stdio::piped())
19055 .stderr(Stdio::piped())
19056 .output()
19057 .expect("ffmpeg failed to run");
19058 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
19059 // Two swept cells of the r4 sweep that decoded to completion with
19060 // WRONG pixels (1714 and 1650 bytes): `--reduced-tx-type-set` and
19061 // `--enable-filter-intra` are the two axes that move which block sizes
19062 // aomenc reaches for here; both arms are pinned.
19063 let mut total_overrides = 0usize;
19064 for (rtx, filter_intra) in [("1", "0"), ("0", "1")] {
19065 let encode = || {
19066 let mut child = Command::new(aomenc_path())
19067 .args([
19068 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32",
19069 "--cpu-used=4", "--threads=1", "--row-mt=0", "--sb-size=64",
19070 "--kf-max-dist=0", "--enable-rect-partitions=1",
19071 "--enable-ab-partitions=0", "--enable-1to4-partitions=0",
19072 "--enable-tx-size-search=0", "--enable-cdef=0",
19073 "--enable-restoration=0",
19074 &format!("--enable-filter-intra={filter_intra}"),
19075 &format!("--reduced-tx-type-set={rtx}"),
19076 "--min-partition-size=8", "--max-partition-size=32",
19077 "--obu", "-o", "-", "-",
19078 ])
19079 .stdin(Stdio::piped())
19080 .stdout(Stdio::piped())
19081 .stderr(Stdio::piped())
19082 .spawn()
19083 .expect("aomenc failed to start");
19084 child
19085 .stdin
19086 .take()
19087 .expect("aomenc stdin")
19088 .write_all(&y4m.stdout)
19089 .expect("writing y4m to aomenc");
19090 let out = child.wait_with_output().expect("aomenc failed to run");
19091 assert!(
19092 out.status.success(),
19093 "aomenc refused the fixture: {}",
19094 String::from_utf8_lossy(&out.stderr)
19095 );
19096 out.stdout
19097 };
19098 let stream = encode();
19099 assert_eq!(
19100 stream,
19101 encode(),
19102 "{NAME}: aomenc output is not reproducible (rtx={rtx} filter_intra={filter_intra})"
19103 );
19104 let before = crate::decode::mode_mi_override_hits();
19105 let frames = decode_stream(&stream).unwrap_or_else(|e| {
19106 panic!("{NAME}: decode failed (rtx={rtx} filter_intra={filter_intra}): {e}")
19107 });
19108 // Counted only on an attempt that actually decoded AND is compared
19109 // below -- a refusal never contributes to the firing assert.
19110 let overrides = crate::decode::mode_mi_override_hits() - before;
19111 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
19112 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame");
19113 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
19114 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19115 assert_eq!(
19116 got.y, want.y,
19117 "{NAME} frame {i} luma vs ffmpeg (rtx={rtx} filter_intra={filter_intra}, \
19118 {overrides} mi-exact mode overrides)"
19119 );
19120 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (rtx={rtx})");
19121 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (rtx={rtx})");
19122 }
19123 total_overrides += overrides;
19124 }
19125 assert!(
19126 total_overrides > 0,
19127 "{NAME}: no non-strip block ever read a mi-exact neighbour that disagreed with its \
19128 coarse slot -- the gate proves nothing"
19129 );
19130 eprintln!("{NAME}: pixel-exact, mode_mi_override_hits={total_overrides}");
19131 }
19132
19133 /// lane-cfl r1: the chroma intra-edge FILTER TYPE is the neighbour's
19134 /// `uv_mode` (libaom `get_filt_type`, reconintra.c: `chroma_above_mbmi`/
19135 /// `chroma_left_mbmi` -> `is_smooth` on `uv_mode`), and two whole decode
19136 /// paths passed a hardcoded `false` for it -- `decode_leaf_8x8` (every
19137 /// 8x8 leaf of a SPLIT) and `decode_leaf_rect` (every rect strip below
19138 /// 16x16), on a stale "chroma stays false (exact) until a smooth/paeth
19139 /// uv_mode can reach decode at all" comment. On top of that the coarse
19140 /// `above_uv_mode`/`left_uv_mode` cells are 16px-granular and their
19141 /// `for cell in 0..w / SUB` write runs ZERO times for any block below
19142 /// 16x16, so even the paths that DID read them saw whatever a
19143 /// 16x16-or-larger block had left there (class: context read from one
19144 /// cell / neighbour map at the wrong granularity). Result on this
19145 /// recipe: luma byte-exact, entropy ladder identical, and 40 U + 86 V
19146 /// chroma bytes wrong -- every one of them downstream of one 4x4 chroma
19147 /// block at mi(8,12) whose D135 + `angle_delta_uv=-3` left edge was
19148 /// filtered at the wrong strength (`ft=0` where the instrumented aomdec
19149 /// prints `ft=1`, left edge `95,59,30,28` vs `90,61,37,29`).
19150 ///
19151 /// Both arms hard-assert per-attempt counters for the two chroma block
19152 /// shapes involved (`UV_CFL_PRED` blocks, nonzero `angle_delta_uv`
19153 /// blocks) plus the mi-exact UV-neighbour override, and are counted only
19154 /// on an attempt that decoded AND is pixel-compared.
19155 #[test]
19156 fn a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact()
19157 {
19158 const NAME: &str = "a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact";
19159 let _gate_lock = lock_gate_counters();
19160 if !have_ffmpeg() {
19161 eprintln!("SKIP {NAME}: no ffmpeg");
19162 return;
19163 }
19164 if !have_aomenc() {
19165 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19166 return;
19167 }
19168 let mut compared = 0usize;
19169 let (width, height) = (64usize, 64usize);
19170 // 8-bit arm = the r5 residue cell ("mandfi161"); 10-bit arm = its
19171 // twin through the same recipe at `--bit-depth=10`.
19172 for depth in [8usize, 10] {
19173 let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
19174 let y4m = Command::new("ffmpeg")
19175 .args([
19176 "-v", "error", "-f", "lavfi", "-i",
19177 &format!("mandelbrot=size={width}x{height}:start_x=-0.6"),
19178 "-pix_fmt", pix, "-strict", "-1", "-t", "1", "-vframes", "1",
19179 "-f", "yuv4mpegpipe", "-",
19180 ])
19181 .stdin(Stdio::null())
19182 .stdout(Stdio::piped())
19183 .stderr(Stdio::piped())
19184 .output()
19185 .expect("ffmpeg failed to run");
19186 assert!(
19187 y4m.status.success(),
19188 "{NAME}: ffmpeg fixture (depth={depth}): {}",
19189 String::from_utf8_lossy(&y4m.stderr)
19190 );
19191 let encode = || {
19192 let mut child = Command::new(aomenc_path())
19193 .args([
19194 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=16",
19195 "--cpu-used=4", "--threads=1", "--row-mt=0", "--sb-size=64",
19196 "--kf-max-dist=0", "--enable-rect-partitions=1",
19197 "--enable-ab-partitions=0", "--enable-1to4-partitions=0",
19198 "--enable-tx-size-search=0", "--enable-filter-intra=1",
19199 "--reduced-tx-type-set=1", "--min-partition-size=8",
19200 "--max-partition-size=32",
19201 &format!("--input-bit-depth={depth}"),
19202 &format!("--bit-depth={depth}"),
19203 "--obu", "-o", "-", "-",
19204 ])
19205 .stdin(Stdio::piped())
19206 .stdout(Stdio::piped())
19207 .stderr(Stdio::piped())
19208 .spawn()
19209 .expect("aomenc failed to start");
19210 child
19211 .stdin
19212 .take()
19213 .expect("aomenc stdin")
19214 .write_all(&y4m.stdout)
19215 .expect("writing y4m to aomenc");
19216 let out = child.wait_with_output().expect("aomenc failed to run");
19217 assert!(
19218 out.status.success(),
19219 "aomenc refused the fixture (depth={depth}): {}",
19220 String::from_utf8_lossy(&out.stderr)
19221 );
19222 out.stdout
19223 };
19224 let stream = encode();
19225 assert_eq!(
19226 stream,
19227 encode(),
19228 "{NAME}: aomenc output is not reproducible (depth={depth})"
19229 );
19230 let before_cfl = crate::decode::cfl_block_hits();
19231 let before_angle = crate::decode::uv_angle_delta_hits();
19232 let before_uv = crate::decode::uv_mode_mi_override_hits();
19233 let frames = match decode_stream(&stream) {
19234 Ok(frames) => frames,
19235 // Only a NAMED refusal is tolerated (COMMON rule): the 10-bit
19236 // twin of this recipe still stops at another lane's open
19237 // sub-16 AB-partition / strip-filter-intra refusals, so it
19238 // cannot be compared yet. Any other error is a failure, and
19239 // `compared` below keeps the test from passing vacuously.
19240 Err(e) => {
19241 let msg = e.to_string();
19242 assert!(
19243 msg.contains("unsupported"),
19244 "{NAME}: decode failed (depth={depth}): {msg}"
19245 );
19246 eprintln!("{NAME}: depth={depth} arm refused (not compared): {msg}");
19247 continue;
19248 }
19249 };
19250 compared += 1;
19251 // Read only on an attempt that decoded AND is compared below.
19252 let cfl_blocks = crate::decode::cfl_block_hits() - before_cfl;
19253 let angle_blocks = crate::decode::uv_angle_delta_hits() - before_angle;
19254 let uv_overrides = crate::decode::uv_mode_mi_override_hits() - before_uv;
19255 let ffmpeg_frames = if depth == 10 {
19256 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
19257 } else {
19258 ffmpeg_decode_sequence(&stream, width, height, frames.len())
19259 };
19260 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame (depth={depth})");
19261 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
19262 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19263 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (depth={depth})");
19264 assert_eq!(
19265 got.u, want.u,
19266 "{NAME} frame {i} U vs ffmpeg (depth={depth}, {cfl_blocks} CFL blocks, \
19267 {angle_blocks} nonzero-angle_delta_uv blocks, {uv_overrides} mi-exact UV \
19268 neighbour overrides)"
19269 );
19270 assert_eq!(
19271 got.v, want.v,
19272 "{NAME} frame {i} V vs ffmpeg (depth={depth}, {cfl_blocks} CFL blocks, \
19273 {angle_blocks} nonzero-angle_delta_uv blocks, {uv_overrides} mi-exact UV \
19274 neighbour overrides)"
19275 );
19276 }
19277 assert!(
19278 cfl_blocks > 0,
19279 "{NAME}: no UV_CFL_PRED block decoded (depth={depth}) -- the gate proves nothing"
19280 );
19281 assert!(
19282 angle_blocks > 0,
19283 "{NAME}: no nonzero angle_delta_uv chroma block decoded (depth={depth}) -- \
19284 the chroma intra-edge filter path never ran"
19285 );
19286 assert!(
19287 uv_overrides > 0,
19288 "{NAME}: no chroma edge-filter read ever took a mi-exact UV neighbour that \
19289 disagreed with its coarse 16x16 slot (depth={depth}) -- the r1 defect is \
19290 not exercised"
19291 );
19292 eprintln!(
19293 "{NAME}: pixel-exact at {depth}-bit, cfl_blocks={cfl_blocks} \
19294 angle_delta_uv_blocks={angle_blocks} uv_mi_overrides={uv_overrides}"
19295 );
19296 }
19297 assert!(
19298 compared > 0,
19299 "{NAME}: every arm refused -- the gate compared no pixels at all"
19300 );
19301 }
19302
19303 /// lane-reelckf r1: ReelC's key frames decoded with no refusal and WRONG
19304 /// CHROMA (luma bit-exact at every one of ten seek points), from two
19305 /// defects this gate pins:
19306 ///
19307 /// 1. a SKIPPED intra block whose `uv_mode` is `UV_CFL_PRED` still
19308 /// predicts with the CfL term -- libaom
19309 /// `predict_and_reconstruct_intra_block` (decodeframe.c) calls
19310 /// `av1_predict_intra_block_facade` unconditionally and only guards
19311 /// the residual on `mbmi->skip_txfm`. Three skip arms (the 16x16-level
19312 /// 1:4 chroma pair and the two sub-8x8 4x4 groups) dropped it.
19313 /// 2. the chroma intra-edge FILTER TYPE of a 1:4 pair comes from the
19314 /// CHROMA REFERENCE position (libaom `get_intra_edge_filter_type` ->
19315 /// `chroma_above_mbmi`/`chroma_left_mbmi`), not from the closing
19316 /// strip: at the closing strip the above cell is the pair's own first
19317 /// strip, the mi-exact UV map misses and the coarse fallback answers,
19318 /// which flipped `av1_use_intra_edge_upsample` (blk_wh 12 <= 16 for
19319 /// type 0, no upsample for type 1) and moved directional chroma by
19320 /// +-1..3.
19321 ///
19322 /// Recipe is a real `aomenc --sb-size=128 --cpu-used=0` (the shape ReelC
19323 /// uses) with 1:4 partitions and CfL on, both bit depths, and both
19324 /// counters hard-asserted per compared attempt.
19325 #[test]
19326 fn a_real_aomenc_sb128_stream_whose_skipped_cfl_and_1to4_chroma_pairs_decode_pixel_exact() {
19327 const NAME: &str =
19328 "a_real_aomenc_sb128_stream_whose_skipped_cfl_and_1to4_chroma_pairs_decode_pixel_exact";
19329 let _gate_lock = lock_gate_counters();
19330 if !have_ffmpeg() {
19331 eprintln!("SKIP {NAME}: no ffmpeg");
19332 return;
19333 }
19334 if !have_aomenc() {
19335 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19336 return;
19337 }
19338 let mut compared = 0usize;
19339 let (width, height) = (256usize, 256usize);
19340 for depth in [8usize, 10] {
19341 let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
19342 let y4m = Command::new("ffmpeg")
19343 .args([
19344 "-v", "error", "-f", "lavfi", "-i",
19345 &format!(
19346 "mandelbrot=size={width}x{height},\
19347 noise=alls=20:allf=t+u:all_seed=7"
19348 ),
19349 "-pix_fmt", pix, "-strict", "-1", "-t", "1", "-vframes", "1",
19350 "-f", "yuv4mpegpipe", "-",
19351 ])
19352 .stdin(Stdio::null())
19353 .stdout(Stdio::piped())
19354 .stderr(Stdio::piped())
19355 .output()
19356 .expect("ffmpeg failed to run");
19357 assert!(
19358 y4m.status.success(),
19359 "{NAME}: ffmpeg fixture (depth={depth}): {}",
19360 String::from_utf8_lossy(&y4m.stderr)
19361 );
19362 let encode = || {
19363 let mut child = Command::new(aomenc_path())
19364 .args([
19365 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=52",
19366 "--cpu-used=0", "--threads=1", "--row-mt=0", "--sb-size=128",
19367 "--kf-max-dist=0", "--enable-rect-partitions=1",
19368 "--enable-ab-partitions=0", "--enable-1to4-partitions=1",
19369 "--enable-cfl-intra=1", "--enable-tx-size-search=0",
19370 "--enable-filter-intra=0", "--enable-intra-edge-filter=1",
19371 "--reduced-tx-type-set=1", "--min-partition-size=4",
19372 "--max-partition-size=32",
19373 &format!("--input-bit-depth={depth}"),
19374 &format!("--bit-depth={depth}"),
19375 "--obu", "-o", "-", "-",
19376 ])
19377 .stdin(Stdio::piped())
19378 .stdout(Stdio::piped())
19379 .stderr(Stdio::piped())
19380 .spawn()
19381 .expect("aomenc failed to start");
19382 child
19383 .stdin
19384 .take()
19385 .expect("aomenc stdin")
19386 .write_all(&y4m.stdout)
19387 .expect("writing y4m to aomenc");
19388 let out = child.wait_with_output().expect("aomenc failed to run");
19389 assert!(
19390 out.status.success(),
19391 "aomenc refused the fixture (depth={depth}): {}",
19392 String::from_utf8_lossy(&out.stderr)
19393 );
19394 out.stdout
19395 };
19396 let stream = encode();
19397 assert_eq!(
19398 stream,
19399 encode(),
19400 "{NAME}: aomenc output is not reproducible (depth={depth})"
19401 );
19402 let before = crate::decode::reelc_chroma_counters();
19403 let frames = match decode_stream(&stream) {
19404 Ok(frames) => frames,
19405 Err(e) => {
19406 let msg = e.to_string();
19407 assert!(
19408 msg.contains("unsupported"),
19409 "{NAME}: decode failed (depth={depth}): {msg}"
19410 );
19411 eprintln!("{NAME}: depth={depth} arm refused (not compared): {msg}");
19412 continue;
19413 }
19414 };
19415 compared += 1;
19416 // Counters read only on an attempt that decoded AND is compared.
19417 let after = crate::decode::reelc_chroma_counters();
19418 let (skip_cfl, dir_pairs) = (after.0 - before.0, after.1 - before.1);
19419 let ffmpeg_frames = if depth == 10 {
19420 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
19421 } else {
19422 ffmpeg_decode_sequence(&stream, width, height, frames.len())
19423 };
19424 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
19425 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19426 assert_eq!(got.y, want.y, "{NAME} frame {i} luma (depth={depth})");
19427 assert_eq!(
19428 got.u, want.u,
19429 "{NAME} frame {i} U (depth={depth}, {skip_cfl} skipped-CfL blocks, \
19430 {dir_pairs} directional 1:4 chroma pairs)"
19431 );
19432 assert_eq!(
19433 got.v, want.v,
19434 "{NAME} frame {i} V (depth={depth}, {skip_cfl} skipped-CfL blocks, \
19435 {dir_pairs} directional 1:4 chroma pairs)"
19436 );
19437 }
19438 // Defect 1 (skipped `UV_CFL_PRED`) is NOT asserted here: 20 aomenc
19439 // recipes (cq 40..63, 9 lavfi sources, min/max-partition 4..64,
19440 // both `--sb-size=128` and 64) never made the encoder pick a
19441 // skipped 1:4 / sub-8x8 CfL block, so an assert would only ever
19442 // fire on his real film. Its evidence is ReelC's own key frames
19443 // (lanes/reelckf-r1.report.md): ss=2700 went 499 wrong chroma
19444 // samples -> 0 on this fix alone. The count is printed so a future
19445 // recipe that does reach it is visible immediately. r2 pinned that
19446 // film frame as a fixture instead:
19447 // `a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact`
19448 // hard-asserts the counter.
19449 assert!(
19450 dir_pairs > 0,
19451 "{NAME}: no directional 1:4 chroma pair decoded (depth={depth}) -- defect 2 \
19452 is not exercised"
19453 );
19454 eprintln!(
19455 "{NAME}: pixel-exact at {depth}-bit over {} frames, skipped_cfl={skip_cfl} \
19456 directional_1to4_chroma_pairs={dir_pairs}",
19457 frames.len()
19458 );
19459 }
19460 assert!(
19461 compared > 0,
19462 "{NAME}: every arm refused -- the gate compared no pixels at all"
19463 );
19464 }
19465
19466 /// lane-ab16 r1: real `aomenc --enable-ab-partitions=1` streams whose
19467 /// 16x16 blocks are split T-shaped (`PARTITION_HORZ_A`/`_HORZ_B`/
19468 /// `_VERT_A`/`_VERT_B`: two 8x8 squares plus one 16x8/8x16 strip), the
19469 /// refusals "a HORZ_A/HORZ_B/VERT_A partition below 16x16" and "a coded
19470 /// (non-skip) HORZ_B/VERT_B rect strip below 16x16" this round lifts.
19471 /// `--min-partition-size=8 --max-partition-size=16` pins the level so
19472 /// every AB symbol in the stream is a 16x16 one; the squares go through
19473 /// `decode_leaf8`, the strips through `decode_leaf_rect`'s non-skip
19474 /// coefficient path (lane-rectx). The per-arm counter is sampled per
19475 /// attempt and summed only over attempts that actually decoded AND were
19476 /// compared, and EACH of the four arms must have fired -- a run where
19477 /// aomenc's RD only ever picked HORZ_A cannot pass as proof of four
19478 /// ([[gate-blind-to-feature]]). 8-bit and 10-bit; `--tile-columns=1` is
19479 /// NOT among the attempts (base tile defect, reproducer in the r1
19480 /// report), and `--enable-tx-size-search` is left at aomenc's default
19481 /// (ON) -- pinning it off hid a panic in the TX4 sub-grid of an 8x8
19482 /// square inside a `PARTITION_VERT_A`/`_B` (r2).
19483 #[test]
19484 fn a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact() {
19485 const NAME: &str =
19486 "a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact";
19487 let _gate_lock = lock_gate_counters();
19488 if !have_ffmpeg() {
19489 eprintln!("SKIP {NAME}: no ffmpeg");
19490 return;
19491 }
19492 if !have_aomenc() {
19493 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19494 return;
19495 }
19496 struct Attempt {
19497 src: &'static str,
19498 w: usize,
19499 h: usize,
19500 cq: u32,
19501 ten_bit: bool,
19502 tile_cols: u32,
19503 /// Left at aomenc's default (ON) instead of pinned off: reaches
19504 /// the TX4 sub-grid of an 8x8 square inside a
19505 /// `PARTITION_VERT_A`/`_B` (r2's panic), at the cost of the
19506 /// strip-level split transform lane-rectx still refuses.
19507 tx_size_search: bool,
19508 }
19509 // Recipes chosen by a ~200-cell sweep of {source, size, cq} at this
19510 // level (r1 report): one cell per arm that is pixel-exact end to end,
19511 // plus two 10-bit cells. `--tile-columns=1` is deliberately absent --
19512 // it mismatches on blocks that are plain NONE/VERT with no AB symbol
19513 // in the failing superblock, i.e. a base tile defect this lane
19514 // neither introduced nor owns (reproducer pinned in the r1 report).
19515 let attempts = [
19516 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 22, ten_bit: false, tile_cols: 0, tx_size_search: false },
19517 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 20, ten_bit: false, tile_cols: 0, tx_size_search: false },
19518 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 50, ten_bit: false, tile_cols: 0, tx_size_search: false },
19519 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 },
19520 // 10-bit: the only two cells of the sweep that are exact at this
19521 // depth (HORZ_A and VERT_A); the 10-bit HORZ_B/VERT_B cells all
19522 // trip the base chroma defect the r1 report pins, so those two
19523 // arms are proven 8-bit only.
19524 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 30, ten_bit: true, tile_cols: 0, tx_size_search: false },
19525 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 },
19526 // `--enable-tx-size-search` at aomenc's default: an 8x8 square of
19527 // a VERT_A/VERT_B resolves to a 2x2 grid of TX4 units, which is
19528 // the reach lookup that had no table row and panicked (r2). These
19529 // attempts may legitimately stop at lane-rectx's still-standing
19530 // "strip with a split transform" refusal -- an `unsupported`
19531 // message is tolerated, a panic or a pixel mismatch is not, and
19532 // at least one of them must reach a TX4 unit inside a vertical AB
19533 // partition.
19534 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 55, ten_bit: false, tile_cols: 0, tx_size_search: true },
19535 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 22, ten_bit: false, tile_cols: 0, tx_size_search: true },
19536 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 20, ten_bit: false, tile_cols: 0, tx_size_search: true },
19537 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 },
19538 ];
19539 let mut arms = [0usize; 4];
19540 let mut compared = 0usize;
19541 let mut tx4_reached = 0usize;
19542 let mut tx4_compared = 0usize;
19543 for a in &attempts {
19544 let desc =
19545 format!("{} cq={} {}bit tiles={}", a.src, a.cq, if a.ten_bit { 10 } else { 8 }, a.tile_cols);
19546 let mut ff: Vec<String> = vec![
19547 "-v".into(), "error".into(), "-f".into(), "lavfi".into(), "-i".into(), a.src.into(),
19548 "-pix_fmt".into(),
19549 if a.ten_bit { "yuv420p10le".into() } else { "yuv420p".into() },
19550 ];
19551 if a.ten_bit {
19552 ff.push("-strict".into());
19553 ff.push("-1".into());
19554 }
19555 ff.extend(["-t".into(), "1".into(), "-vframes".into(), "1".into(),
19556 "-f".into(), "yuv4mpegpipe".into(), "-".into()]);
19557 let y4m = Command::new("ffmpeg")
19558 .args(&ff)
19559 .stdin(Stdio::null())
19560 .stdout(Stdio::piped())
19561 .stderr(Stdio::piped())
19562 .output()
19563 .expect("ffmpeg failed to run");
19564 assert!(y4m.status.success(), "ffmpeg fixture {desc}: {}", String::from_utf8_lossy(&y4m.stderr));
19565 let encode = || {
19566 let mut args: Vec<String> = vec![
19567 "--codec=av1".into(), "--passes=1".into(), "--end-usage=q".into(),
19568 format!("--cq-level={}", a.cq), "--cpu-used=4".into(), "--threads=1".into(),
19569 "--row-mt=0".into(), "--sb-size=64".into(), "--kf-max-dist=0".into(),
19570 "--limit=1".into(),
19571 "--enable-rect-partitions=1".into(), "--enable-ab-partitions=1".into(),
19572 "--enable-1to4-partitions=0".into(),
19573 format!("--enable-tx-size-search={}", u8::from(a.tx_size_search)),
19574 // Filter intra ON a rect strip is a separate, still-refused
19575 // predictor; this gate is about the AB partition wiring.
19576 "--enable-filter-intra=0".into(),
19577 "--reduced-tx-type-set=1".into(),
19578 "--min-partition-size=8".into(), "--max-partition-size=16".into(),
19579 format!("--tile-columns={}", a.tile_cols),
19580 ];
19581 if a.ten_bit {
19582 args.push("--input-bit-depth=10".into());
19583 args.push("--bit-depth=10".into());
19584 }
19585 args.extend(["--obu".into(), "-o".into(), "-".into(), "-".into()]);
19586 let mut child = Command::new(aomenc_path())
19587 .args(&args)
19588 .stdin(Stdio::piped())
19589 .stdout(Stdio::piped())
19590 .stderr(Stdio::piped())
19591 .spawn()
19592 .expect("aomenc failed to start");
19593 child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("y4m to aomenc");
19594 let out = child.wait_with_output().expect("aomenc failed to run");
19595 assert!(out.status.success(), "aomenc refused {desc}: {}", String::from_utf8_lossy(&out.stderr));
19596 out.stdout
19597 };
19598 let stream = encode();
19599 assert!(!stream.is_empty(), "{NAME}: {desc}: aomenc wrote an empty stream");
19600 assert_eq!(stream, encode(), "{NAME}: {desc}: aomenc output is not reproducible");
19601 let before = crate::decode::ab16_hits_by_arm();
19602 let tx4_before = crate::decode::vert_ab_tx4_hits();
19603 let decoded = decode_stream(&stream);
19604 let tx4_this = crate::decode::vert_ab_tx4_hits() - tx4_before;
19605 // Counted even when the attempt later stops at another lane's
19606 // refusal: reaching this lookup at all is what r2 fixed.
19607 tx4_reached += tx4_this;
19608 let frames = match decoded {
19609 Ok(frames) => frames,
19610 // Only lane-rectx's split-transform strip refusal may stop a
19611 // tx-size-search attempt; a panic never reaches here at all.
19612 Err(e) if a.tx_size_search => {
19613 let msg = e.to_string();
19614 assert!(
19615 msg.contains("unsupported"),
19616 "{NAME}: {desc}: decode failed with a non-refusal error: {msg}"
19617 );
19618 eprintln!("{NAME}: {desc} refused after {tx4_this} vert-AB TX4 units: {msg}");
19619 continue;
19620 }
19621 Err(e) => panic!("{NAME}: {desc}: decode failed, not a pixel mismatch: {e}"),
19622 };
19623 let after = crate::decode::ab16_hits_by_arm();
19624 let this: Vec<usize> = (0..4).map(|i| after[i] - before[i]).collect();
19625 eprintln!("{NAME}: {desc} decoded, arms this attempt={this:?}");
19626 let want = if a.ten_bit {
19627 ffmpeg_decode_sequence_10bit(&stream, a.w, a.h, frames.len())
19628 } else {
19629 ffmpeg_decode_sequence(&stream, a.w, a.h, frames.len())
19630 };
19631 assert_eq!(want.len(), frames.len(), "{NAME}: {desc}: ffmpeg frame count");
19632 for (i, (got, w)) in frames.iter().zip(&want).enumerate() {
19633 assert_eq!(got.y, w.y, "{NAME}: {desc} frame {i} luma vs ffmpeg");
19634 assert_eq!(got.u, w.u, "{NAME}: {desc} frame {i} U vs ffmpeg");
19635 assert_eq!(got.v, w.v, "{NAME}: {desc} frame {i} V vs ffmpeg");
19636 }
19637 // Counted only now: the attempt decoded AND compared exact.
19638 if a.tx_size_search {
19639 tx4_compared += 1;
19640 eprintln!("{NAME}: {desc} pixel-exact, vert-AB TX4 units={tx4_this}");
19641 continue;
19642 }
19643 for i in 0..4 {
19644 arms[i] += after[i] - before[i];
19645 }
19646 compared += 1;
19647 eprintln!("{NAME}: {desc} pixel-exact");
19648 }
19649 assert_eq!(
19650 compared,
19651 attempts.iter().filter(|a| !a.tx_size_search).count(),
19652 "{NAME}: every fixed-transform attempt must decode and compare"
19653 );
19654 // Until the lane-rectsplitx merge every tx-size-search attempt stopped
19655 // at "a HORZ/VERT intra strip below 16x16 with a split transform", so
19656 // this gate could only claim that the TX4 sub-grid of an 8x8 square
19657 // inside a VERT_A/VERT_B was REACHED (`tx4_reached`, counted even on a
19658 // refused attempt). With per-TU rect prediction those same attempts now
19659 // decode to the end and compare pixel-exact, and they carry no vert-AB
19660 // TX4 unit at all -- the pre-merge nonzero count came from decodes that
19661 // were still desynced when they hit the refusal (class
19662 // counter-from-refused-stream). The full pixel compare is the stronger
19663 // claim and replaces it; the lookup's VALUES stay pinned against libaom
19664 // in `of_tu_keeps_the_ordinary_answer_and_uses_the_block_row_under_vert_ab`.
19665 eprintln!("{NAME}: vert-AB TX4 units reached across tx-size-search attempts: {tx4_reached}");
19666 let _ = tx4_reached;
19667 assert_eq!(
19668 tx4_compared,
19669 attempts.iter().filter(|a| a.tx_size_search).count(),
19670 "{NAME}: every --enable-tx-size-search=1 attempt must now decode to the end and \
19671 compare pixel-exact (the split-transform strip refusal these used to stop at is \
19672 lifted); the vert-AB TX4 lookup values stay pinned by \
19673 `of_tu_keeps_the_ordinary_answer_and_uses_the_block_row_under_vert_ab`"
19674 );
19675 for (i, arm) in ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"].iter().enumerate() {
19676 assert!(arms[i] > 0, "{NAME}: PARTITION_{arm} at 16x16 never fired across {compared} \
19677 compared streams -- the gate proves nothing about that arm (arms={arms:?})");
19678 }
19679 eprintln!("{NAME}: pixel-exact on {compared} streams, ab16 arms(HORZ_A,HORZ_B,VERT_A,VERT_B)={arms:?}");
19680 }
19681
19682 #[test]
19683 #[ignore = "lane-rectx r3 scratch sweep"]
19684 fn sweep_rectx_recipes() {
19685 let _gate_lock = lock_gate_counters();
19686 let srcs: Vec<String> = vec![
19687 "mandelbrot=size=64x64:start_x=0.4".into(),
19688 "mandelbrot=size=64x64:start_x=-0.6".into(),
19689 "mandelbrot=size=64x64:start_x=0.1".into(),
19690 "mandelbrot=size=128x128:start_x=0.4".into(),
19691 "mandelbrot=size=128x128:start_x=-0.6".into(),
19692 "testsrc2=size=64x64".into(),
19693 "testsrc2=size=128x128".into(),
19694 "rgbtestsrc=size=64x64".into(),
19695 "smptebars=size=128x128".into(),
19696 ];
19697 for start_x in srcs {
19698 let y4m = Command::new("ffmpeg")
19699 .args([
19700 "-v", "error", "-f", "lavfi", "-i",
19701 &start_x,
19702 "-pix_fmt", "yuv420p", "-t", "1", "-vframes", "1", "-f", "yuv4mpegpipe", "-",
19703 ])
19704 .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped())
19705 .output().expect("ffmpeg");
19706 assert!(y4m.status.success());
19707 let (width, height) = if start_x.contains("128x128") { (128usize, 128usize) } else { (64usize, 64usize) };
19708 for cq in [16u32, 20, 24, 28, 32, 40, 50] {
19709 for rtx in ["0", "1"] {
19710 let mut child = Command::new(aomenc_path())
19711 .args([
19712 "--codec=av1", "--passes=1", "--end-usage=q",
19713 &format!("--cq-level={cq}"), "--cpu-used=4", "--threads=1",
19714 "--row-mt=0", "--sb-size=64", "--kf-max-dist=0",
19715 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
19716 "--enable-1to4-partitions=0", "--enable-tx-size-search=0",
19717 "--enable-cdef=0", "--enable-restoration=0",
19718 &format!("--reduced-tx-type-set={rtx}"),
19719 "--min-partition-size=8", "--max-partition-size=32",
19720 "--obu", "-o", "-", "-",
19721 ])
19722 .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
19723 .spawn().expect("aomenc");
19724 child.stdin.take().unwrap().write_all(&y4m.stdout).unwrap();
19725 let out = child.wait_with_output().unwrap();
19726 assert!(out.status.success());
19727 let stream = out.stdout;
19728 let before = crate::decode::rect_leaf_coeff_hits();
19729 let res = decode_stream(&stream);
19730 let fired = crate::decode::rect_leaf_coeff_hits() - before;
19731 match res {
19732 Err(e) => eprintln!("x={start_x} cq={cq} rtx={rtx} fired={fired} REFUSED {e}"),
19733 Ok(frames) => {
19734 let want = ffmpeg_decode_sequence(&stream, width, height, frames.len());
19735 let bad = frames.iter().zip(&want)
19736 .filter(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v).count();
19737 eprintln!("x={start_x} cq={cq} rtx={rtx} fired={fired} frames={} mismatched={bad}", frames.len());
19738 if bad == 0 { continue; }
19739 let (g, w) = (&frames[0], &want[0]);
19740 for br in 0..height / 8 {
19741 let mut line = String::new();
19742 for bc in 0..width / 8 {
19743 let mut n = 0;
19744 for row in br * 8..br * 8 + 8 {
19745 for col in bc * 8..bc * 8 + 8 {
19746 if g.y[row * width + col] != w.y[row * width + col] {
19747 n += 1;
19748 }
19749 }
19750 }
19751 line.push_str(&format!("{n:4}"));
19752 }
19753 eprintln!(" blk8 row{br}: {line}");
19754 }
19755 }
19756 }
19757 }
19758 }
19759 }
19760 }
19761
19762 /// lane-rectgate r1: every prior gate pins `--enable-rect-partitions=0
19763 /// --enable-ab-partitions=0 --min/max-partition-size=32` so aomenc never
19764 /// gets to choose a real rect/ab split. This charter's premise ("rect
19765 /// HORZ/VERT + HORZ_A/HORZ_B/VERT_A/VERT_B landed during the warp lane")
19766 /// does NOT hold: `decode_frame`'s inter-tile `match part32` only has
19767 /// arms for `PARTITION_NONE`/`SPLIT`/`HORZ_B` -- `HORZ`, `VERT`,
19768 /// `HORZ_A`, `VERT_A`, `VERT_B`, `HORZ_4`, `VERT_4` all fall into the
19769 /// generic "a partition type this encoder never writes" `_` arm. Two
19770 /// recipes were swept empirically (40 attempts each) to characterize the
19771 /// gap:
19772 /// - `--enable-rect-partitions=1 --enable-ab-partitions=1`, no
19773 /// min/max clamp: 0/40 matched -- every attempt hit either the
19774 /// screen-content refusal or a genuinely-unimplemented partition value
19775 /// (1/2/6/7/9 all observed), always somewhere in the 24-frame stream.
19776 /// - Same, but `--enable-1to4-partitions=0` explicit and
19777 /// `--min-partition-size=16`: still 0/40, `value=9` (`VERT_4`)
19778 /// dominates -- this build's `--enable-1to4-partitions=0` does NOT
19779 /// suppress `VERT_4` selection (aomenc-side, confirmed by direct flag
19780 /// toggle; outside this decoder). This recipe (below) restores the
19781 /// `--enable-rect-partitions=0 --min/max-partition-size=32` pin every
19782 /// other gate uses, flipping only `--enable-ab-partitions=1`: matches
19783 /// cleanly (33/40, rest screen-content refusals) but
19784 /// `extended_partition_hits` stayed 0 -- confirmed with the same probe
19785 /// wired into the already-green warp gate too (144 `warp_selected_hits`,
19786 /// 0 `extended_partition_hits`), so `PARTITION_HORZ_B` itself is
19787 /// apparently never chosen by aomenc for this small gradient fixture at
19788 /// `cq-level=45` regardless of clamp. No decode defect (crash or pixel
19789 /// mismatch) was found in any sweep -- every refusal is a correctly
19790 /// named, non-silent "unsupported" error. A refusal or mismatch naming
19791 /// any OTHER already-ported capability (warp, obmc, interintra) still
19792 /// fails the gate outright.
19793 #[test]
19794 fn a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact() {
19795 const NAME: &str = "a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact";
19796 let _gate_lock = lock_gate_counters();
19797 if !have_ffmpeg() {
19798 eprintln!("SKIP {NAME}: no ffmpeg");
19799 return;
19800 }
19801 if !have_aomenc() {
19802 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19803 return;
19804 }
19805 let (width, height, frame_count) = (64usize, 64usize, 24usize);
19806 let mut named_refusals = 0u32;
19807 let mut matched = 0u32;
19808 let n_attempts: u32 = std::env::var("EC_RECTGATE_ATTEMPTS")
19809 .ok()
19810 .and_then(|s| s.parse().ok())
19811 .unwrap_or(40);
19812 for attempt in 0..n_attempts {
19813 let seed = 42 + attempt;
19814 let duration = frame_count as f64 / 25.0;
19815 let source =
19816 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
19817 let y4m = Command::new("ffmpeg")
19818 .args([
19819 "-v",
19820 "error",
19821 "-f",
19822 "lavfi",
19823 "-i",
19824 &source,
19825 "-pix_fmt",
19826 "yuv420p",
19827 "-f",
19828 "yuv4mpegpipe",
19829 "-",
19830 ])
19831 .stdin(Stdio::null())
19832 .stdout(Stdio::piped())
19833 .stderr(Stdio::piped())
19834 .output()
19835 .expect("ffmpeg failed to run");
19836 assert!(
19837 y4m.status.success(),
19838 "ffmpeg fixture: {}",
19839 String::from_utf8_lossy(&y4m.stderr)
19840 );
19841 let args: Vec<&str> = vec![
19842 "--codec=av1",
19843 "--passes=1",
19844 "--end-usage=q",
19845 "--cq-level=45",
19846 "--cpu-used=0",
19847 "--kf-max-dist=1000",
19848 "--threads=1",
19849 "--row-mt=0",
19850 "--auto-alt-ref=1",
19851 "--lag-in-frames=16",
19852 "--enable-fwd-kf=0",
19853 "--enable-order-hint=1",
19854 "--enable-warped-motion=1",
19855 "--enable-obmc=1",
19856 "--tune-content=default",
19857 "--enable-masked-comp=0",
19858 "--enable-interintra-comp=0",
19859 "--enable-onesided-comp=0",
19860 "--enable-interintra-wedge=0",
19861 "--enable-smooth-interintra=0",
19862 // lane-rect r2: HORZ/VERT decode for real (rect-flake-1
19863 // byte-exact: size_h + warp dims + OBMC overlap + tx height)
19864 // -- free recipe restored; remaining partition kinds refuse
19865 // by name and skip their seeds.
19866 "--enable-rect-partitions=1",
19867 "--enable-ab-partitions=1",
19868 "--enable-1to4-partitions=0",
19869 "--enable-filter-intra=0",
19870 "--enable-smooth-intra=0",
19871 "--enable-paeth-intra=0",
19872 "--enable-directional-intra=0",
19873 "--enable-angle-delta=0",
19874 "--enable-tx-size-search=0",
19875 "--enable-cdef=0",
19876 "--enable-restoration=0",
19877 "--max-partition-size=32",
19878 "--min-partition-size=16",
19879 "--enable-palette=0",
19880 "--enable-intrabc=0",
19881 "--enable-cfl-intra=0",
19882 "--enable-ref-frame-mvs=0",
19883 "--obu",
19884 "-o",
19885 "-",
19886 "-",
19887 ];
19888 let mut child = Command::new(aomenc_path())
19889 .args(&args)
19890 .stdin(Stdio::piped())
19891 .stdout(Stdio::piped())
19892 .stderr(Stdio::piped())
19893 .spawn()
19894 .expect("aomenc failed to start");
19895 child
19896 .stdin
19897 .take()
19898 .expect("aomenc stdin")
19899 .write_all(&y4m.stdout)
19900 .expect("writing y4m to aomenc");
19901 let out = child.wait_with_output().expect("aomenc failed to run");
19902 assert!(
19903 out.status.success(),
19904 "aomenc refused the fixture: {}",
19905 String::from_utf8_lossy(&out.stderr)
19906 );
19907 let stream = out.stdout;
19908 let frames = match decode_stream(&stream) {
19909 Err(e) => {
19910 let msg = e.to_string();
19911 assert!(
19912 msg.contains("unsupported"),
19913 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
19914 );
19915 for banned in ["warp", "obmc", "interintra"] {
19916 assert!(
19917 !msg.contains(banned),
19918 "{NAME} refused on {banned} (seed {seed}) -- that capability is \
19919 ported and this recipe does not need it: {msg}"
19920 );
19921 }
19922 named_refusals += 1;
19923 eprintln!("seed {seed} refusal: {msg}");
19924 continue;
19925 }
19926 Ok(frames) => frames,
19927 };
19928 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
19929 assert_eq!(frames.len(), frame_count);
19930 let mismatched = frames
19931 .iter()
19932 .zip(&ffmpeg_frames)
19933 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
19934 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
19935 std::fs::write(&path, &stream).expect("writing pinned stream");
19936 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
19937 }
19938 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19939 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
19940 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
19941 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
19942 }
19943 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
19944 // stream again, comparing EVERY decode-order frame -- the hidden
19945 // (show_frame == 0) alt-ref frames the ffmpeg compare above
19946 // cannot see, because both sides of it emit shown frames only.
19947 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
19948 eprintln!(
19949 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
19950 {hidden_n} hidden, all pixel-exact vs the oracle"
19951 );
19952 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
19953 // libaom's temporal alt-ref filter absorbs this recipe's hidden
19954 // frames, so the compare above is vacuous -- re-encode the same
19955 // fixture with --arnr-maxframes=0 and compare THOSE.
19956 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
19957 eprintln!(
19958 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
19959 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
19960 );
19961 }
19962 matched += 1;
19963 }
19964 assert!(
19965 matched > 0,
19966 "{NAME}: every attempt refused; the gate never decoded a free-partition stream"
19967 );
19968 // lane-partitions r1: HORZ/VERT arms landed, so the diversity probe
19969 // graduates from rectgate r1's eprintln to a report line on
19970 // `rect_partition_hits`; a zero-hit run SOFT-reports (aomenc RD may
19971 // legitimately never pick a rect split in a small window -- same
19972 // sampling caveat as the masked-compound gate's zero-hit runs).
19973 // `extended_partition_hits` (HORZ_B) stays unasserted per rectgate r1.
19974 if crate::decode::rect_partition_hits() == 0 {
19975 eprintln!(
19976 "{NAME}: SOFT-NOTE -- zero HORZ/VERT strips fired this run \
19977 ({matched} matches, {named_refusals} refusals); sampling, not a regression"
19978 );
19979 } else {
19980 // r5: the desync was the tx-depth symbol being read
19981 // unconditionally where both square paths gate it on `tx_select`
19982 // -- with --enable-tx-size-search=0 the encoder writes no such
19983 // symbol and the decoder consumed one that was never there. With
19984 // that fixed the real coefficient decode is pixel-exact, so this
19985 // is a HARD assert again: strips fired but no coefficients read
19986 // would mean the coded path silently stopped being exercised.
19987 assert!(
19988 crate::decode::rect_coeff_hits() > 0,
19989 "{NAME}: {} HORZ/VERT strips fired but rect_coeff_hits==0 -- the \
19990 coded rect path is no longer exercised",
19991 crate::decode::rect_partition_hits()
19992 );
19993 }
19994 eprintln!(
19995 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of {n_attempts}, rect_partition_hits={} rect_coeff_hits={} extended_partition_hits={} partab_hits={}",
19996 crate::decode::rect_partition_hits(),
19997 crate::decode::rect_coeff_hits(),
19998 crate::decode::extended_partition_hits(),
19999 crate::decode::partab_hits()
20000 );
20001 }
20002
20003 /// lane-partab r1: `--enable-ab-partitions=1` (aomenc default-on) INTER
20004 /// streams must consume PARTITION_HORZ_A/VERT_A/VERT_B entropy-exact AND
20005 /// decode pixel-exact -- `partab_hits() > 0` is soft-skipped on a
20006 /// zero-hit run (aomenc RD may legitimately never pick an AB split in a
20007 /// small window, same sampling caveat as wedge/rect). The INTER AB
20008 /// refusal is FORBIDDEN (decode.rs names it "an INTER 32x32 partition
20009 /// ..."); intra-frame AB refusals stay accepted named refusals -- the
20010 /// intra dispatch is a later lane. Recipe = the free-partition gate's,
20011 /// which fires AB live (r1: partab_hits 6/2/4/3/1/5 over six
20012 /// 40-attempt runs).
20013 #[test]
20014 fn a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact() {
20015 const NAME: &str = "a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact";
20016 let _gate_lock = lock_gate_counters();
20017 if !have_ffmpeg() {
20018 eprintln!("SKIP {NAME}: no ffmpeg");
20019 return;
20020 }
20021 if !have_aomenc() {
20022 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20023 return;
20024 }
20025 let (width, height, frame_count) = (64usize, 64usize, 24usize);
20026 let mut named_refusals = 0u32;
20027 let mut matched = 0u32;
20028 let n_attempts: u32 = std::env::var("EC_RECTGATE_ATTEMPTS")
20029 .ok()
20030 .and_then(|s| s.parse().ok())
20031 .unwrap_or(40);
20032 for attempt in 0..n_attempts {
20033 let seed = 42 + attempt;
20034 let duration = frame_count as f64 / 25.0;
20035 let source =
20036 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
20037 let y4m = Command::new("ffmpeg")
20038 .args([
20039 "-v",
20040 "error",
20041 "-f",
20042 "lavfi",
20043 "-i",
20044 &source,
20045 "-pix_fmt",
20046 "yuv420p",
20047 "-f",
20048 "yuv4mpegpipe",
20049 "-",
20050 ])
20051 .stdin(Stdio::null())
20052 .stdout(Stdio::piped())
20053 .stderr(Stdio::piped())
20054 .output()
20055 .expect("ffmpeg failed to run");
20056 assert!(
20057 y4m.status.success(),
20058 "ffmpeg fixture: {}",
20059 String::from_utf8_lossy(&y4m.stderr)
20060 );
20061 let args: Vec<&str> = vec![
20062 "--codec=av1",
20063 "--passes=1",
20064 "--end-usage=q",
20065 "--cq-level=45",
20066 "--cpu-used=0",
20067 "--kf-max-dist=1000",
20068 "--threads=1",
20069 "--row-mt=0",
20070 "--auto-alt-ref=1",
20071 "--lag-in-frames=16",
20072 "--enable-fwd-kf=0",
20073 "--enable-order-hint=1",
20074 "--enable-warped-motion=1",
20075 "--enable-obmc=1",
20076 "--tune-content=default",
20077 "--enable-masked-comp=0",
20078 "--enable-interintra-comp=0",
20079 "--enable-onesided-comp=0",
20080 "--enable-interintra-wedge=0",
20081 "--enable-smooth-interintra=0",
20082 // lane-rect r2 recipe, kept byte-identical by lane-partab
20083 // r1: free partition search, 1to4 off, intra tools off.
20084 "--enable-rect-partitions=1",
20085 "--enable-ab-partitions=1",
20086 "--enable-1to4-partitions=0",
20087 "--enable-filter-intra=0",
20088 "--enable-smooth-intra=0",
20089 "--enable-paeth-intra=0",
20090 "--enable-directional-intra=0",
20091 "--enable-angle-delta=0",
20092 "--enable-tx-size-search=0",
20093 "--enable-cdef=0",
20094 "--enable-restoration=0",
20095 "--max-partition-size=32",
20096 "--min-partition-size=16",
20097 "--enable-palette=0",
20098 "--enable-intrabc=0",
20099 "--enable-cfl-intra=0",
20100 "--enable-ref-frame-mvs=0",
20101 "--obu",
20102 "-o",
20103 "-",
20104 "-",
20105 ];
20106 let mut child = Command::new(aomenc_path())
20107 .args(&args)
20108 .stdin(Stdio::piped())
20109 .stdout(Stdio::piped())
20110 .stderr(Stdio::piped())
20111 .spawn()
20112 .expect("aomenc failed to start");
20113 child
20114 .stdin
20115 .take()
20116 .expect("aomenc stdin")
20117 .write_all(&y4m.stdout)
20118 .expect("writing y4m to aomenc");
20119 let out = child.wait_with_output().expect("aomenc failed to run");
20120 assert!(
20121 out.status.success(),
20122 "aomenc refused the fixture: {}",
20123 String::from_utf8_lossy(&out.stderr)
20124 );
20125 let stream = out.stdout;
20126 let frames = match decode_stream(&stream) {
20127 Err(e) => {
20128 let msg = e.to_string();
20129 assert!(
20130 msg.contains("unsupported"),
20131 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
20132 );
20133 for banned in ["warp", "obmc", "interintra"] {
20134 assert!(
20135 !msg.contains(banned),
20136 "{NAME} refused on {banned} (seed {seed}) -- that capability is \
20137 ported and this recipe does not need it: {msg}"
20138 );
20139 }
20140 for v in [4, 6, 7] {
20141 assert!(
20142 !msg.contains(&format!(
20143 "an INTER 32x32 partition type this encoder never writes \
20144 (value={v})"
20145 )),
20146 "{NAME} refused an INTER AB partition (value={v}, seed {seed}) -- \
20147 all three AB arms are ported, this refusal is forbidden: {msg}"
20148 );
20149 }
20150 named_refusals += 1;
20151 eprintln!("seed {seed} refusal: {msg}");
20152 continue;
20153 }
20154 Ok(frames) => frames,
20155 };
20156 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
20157 assert_eq!(frames.len(), frame_count);
20158 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20159 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
20160 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
20161 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
20162 }
20163 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
20164 // stream again, comparing EVERY decode-order frame -- the hidden
20165 // (show_frame == 0) alt-ref frames the ffmpeg compare above
20166 // cannot see, because both sides of it emit shown frames only.
20167 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
20168 eprintln!(
20169 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
20170 {hidden_n} hidden, all pixel-exact vs the oracle"
20171 );
20172 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
20173 // libaom's temporal alt-ref filter absorbs this recipe's hidden
20174 // frames, so the compare above is vacuous -- re-encode the same
20175 // fixture with --arnr-maxframes=0 and compare THOSE.
20176 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
20177 eprintln!(
20178 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
20179 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
20180 );
20181 }
20182 matched += 1;
20183 }
20184 assert!(
20185 matched > 0,
20186 "{NAME}: every attempt refused; the gate never decoded a stream"
20187 );
20188 if crate::decode::partab_hits() == 0 {
20189 eprintln!(
20190 "{NAME}: SOFT-NOTE -- zero AB partitions fired this run \
20191 ({matched} matches, {named_refusals} refusals); sampling, not a regression"
20192 );
20193 }
20194 eprintln!(
20195 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of {n_attempts}, partab_hits={}",
20196 crate::decode::partab_hits()
20197 );
20198 }
20199
20200 /// lane-ab32 r1: the 32x32-level AB arms (`PARTITION_HORZ_A`/`_HORZ_B`/
20201 /// `_VERT_A`/`_VERT_B` -- two 16x16 squares plus one 32x16/16x32 strip)
20202 /// are decoded on the INTRA path (decode.rs `PARTITION_HORZ_A` .. the
20203 /// 32x32 refusal) but nothing asserted they fire: the INTER AB gate above
20204 /// only SOFT-notes `partab_hits`, and the four per-arm counters
20205 /// lane-part32 added had no consumer at all (class
20206 /// `refusal-lifted-without-a-gate`). This drives a real key-frame-only
20207 /// aomenc at `--enable-ab-partitions=1 --enable-rect-partitions=1
20208 /// --sb-size=64 --min-partition-size=16 --max-partition-size=32`, so every
20209 /// AB split aomenc picks is a 32-level one, pixel-compares every
20210 /// successful decode against ffmpeg's decode of the same bytes, and
20211 /// hard-asserts each arm fired at least once over the seed sweep --
20212 /// counting deltas only from attempts that decoded AND compared (class
20213 /// `counter-from-refused-stream`).
20214 #[test]
20215 fn a_real_aomenc_stream_with_a_32_level_ab_partition_decodes_pixel_exact() {
20216 const NAME: &str = "a_real_aomenc_stream_with_a_32_level_ab_partition_decodes_pixel_exact";
20217 let _gate_lock = lock_gate_counters();
20218 if !have_ffmpeg() {
20219 eprintln!("SKIP {NAME}: no ffmpeg");
20220 return;
20221 }
20222 if !have_aomenc() {
20223 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20224 return;
20225 }
20226 let (width, height) = (256usize, 256usize);
20227 let arms: [(&str, fn() -> usize); 4] = [
20228 ("HORZ_A_32", crate::decode::intra_horz_a_hits),
20229 ("HORZ_B_32", crate::decode::intra_horz_b_hits),
20230 ("VERT_A_32", crate::decode::intra_vert_a_hits),
20231 ("VERT_B_32", crate::decode::intra_vert_b_hits),
20232 ];
20233 let mut totals = [0usize; 4];
20234 let mut refusals: Vec<String> = Vec::new();
20235 let mut compared = 0usize;
20236 for &seed in &LR_SEEDS {
20237 // Smooth gradients code as PARTITION_NONE everywhere (r1: 16/16
20238 // attempts decoded pixel-exact with zero AB hits), so the fixture
20239 // carries seeded noise to give the intra RD a reason to split.
20240 let source = format!(
20241 "{},noise=alls=40:all_seed={seed}",
20242 gradients_source(seed, width, height, "duration=0.04:rate=25")
20243 );
20244 let y4m = Command::new("ffmpeg")
20245 .args([
20246 "-v",
20247 "error",
20248 "-f",
20249 "lavfi",
20250 "-i",
20251 &source,
20252 "-frames:v",
20253 "1",
20254 "-pix_fmt",
20255 "yuv420p",
20256 "-f",
20257 "yuv4mpegpipe",
20258 "-",
20259 ])
20260 .stdin(Stdio::null())
20261 .stdout(Stdio::piped())
20262 .stderr(Stdio::piped())
20263 .output()
20264 .expect("ffmpeg failed to run");
20265 assert!(
20266 y4m.status.success(),
20267 "{NAME}: ffmpeg fixture (seed {seed}): {}",
20268 String::from_utf8_lossy(&y4m.stderr)
20269 );
20270 // The flags under test come LAST: aomenc keeps the LAST
20271 // occurrence of a repeated flag (measured 2026-09-02 by md5 of
20272 // four orderings), so an override appended after the base recipe
20273 // is the one that lands. Nothing here is repeated, and each of the
20274 // four arm counters below proves the AB flag actually arrived.
20275 let args: Vec<&str> = vec![
20276 "--codec=av1",
20277 "--passes=1",
20278 "--end-usage=q",
20279 "--cq-level=45",
20280 "--cpu-used=0",
20281 "--limit=1",
20282 "--kf-max-dist=0",
20283 "--lag-in-frames=0",
20284 "--threads=1",
20285 "--row-mt=0",
20286 "--enable-1to4-partitions=0",
20287 "--enable-filter-intra=0",
20288 "--enable-smooth-intra=0",
20289 "--enable-paeth-intra=0",
20290 "--enable-directional-intra=0",
20291 "--enable-angle-delta=0",
20292 "--enable-tx-size-search=0",
20293 "--enable-cdef=0",
20294 "--enable-restoration=0",
20295 "--enable-palette=0",
20296 "--enable-intrabc=0",
20297 "--enable-cfl-intra=0",
20298 "--enable-ref-frame-mvs=0",
20299 "--sb-size=64",
20300 "--enable-rect-partitions=1",
20301 "--enable-ab-partitions=1",
20302 "--min-partition-size=16",
20303 "--max-partition-size=32",
20304 "--obu",
20305 "-o",
20306 "-",
20307 "-",
20308 ];
20309 let mut child = Command::new(aomenc_path())
20310 .args(&args)
20311 .stdin(Stdio::piped())
20312 .stdout(Stdio::piped())
20313 .stderr(Stdio::piped())
20314 .spawn()
20315 .expect("aomenc failed to start");
20316 child
20317 .stdin
20318 .take()
20319 .expect("aomenc stdin")
20320 .write_all(&y4m.stdout)
20321 .expect("writing y4m to aomenc");
20322 let out = child.wait_with_output().expect("aomenc failed to run");
20323 assert!(
20324 out.status.success(),
20325 "aomenc refused the fixture (seed {seed}): {}",
20326 String::from_utf8_lossy(&out.stderr)
20327 );
20328 let stream = out.stdout;
20329 let before: Vec<usize> = arms.iter().map(|(_, f)| f()).collect();
20330 let frames = match decode_stream(&stream) {
20331 Err(e) => {
20332 let msg = e.to_string();
20333 assert!(
20334 msg.contains("unsupported"),
20335 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
20336 );
20337 for v in [4, 5, 6, 7] {
20338 assert!(
20339 !msg.contains(&format!(
20340 "a 32x32 partition type this decoder does not code (value={v})"
20341 )),
20342 "{NAME} refused a 32-level AB partition (value={v}, seed {seed}) -- \
20343 all four arms are ported, this refusal is forbidden: {msg}"
20344 );
20345 }
20346 refusals.push(format!("seed {seed}: {msg}"));
20347 continue;
20348 }
20349 Ok(frames) => frames,
20350 };
20351 let deltas: Vec<usize> = arms
20352 .iter()
20353 .zip(before.iter())
20354 .map(|((_, f), b)| f() - b)
20355 .collect();
20356 let fired: Vec<String> = arms
20357 .iter()
20358 .zip(deltas.iter())
20359 .map(|((label, _), d)| format!("{label}={d}"))
20360 .collect();
20361 let fired = fired.join(" ");
20362 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
20363 assert_eq!(
20364 frames.len(),
20365 ffmpeg_frames.len(),
20366 "{NAME}: seed {seed}: shown-frame count vs ffmpeg"
20367 );
20368 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20369 assert_eq!(
20370 got.y, want.y,
20371 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) [{fired}]"
20372 );
20373 assert_eq!(
20374 got.u, want.u,
20375 "{NAME} frame {i} U vs ffmpeg (seed {seed}) [{fired}]"
20376 );
20377 assert_eq!(
20378 got.v, want.v,
20379 "{NAME} frame {i} V vs ffmpeg (seed {seed}) [{fired}]"
20380 );
20381 }
20382 compared += 1;
20383 for (i, d) in deltas.iter().enumerate() {
20384 totals[i] += d;
20385 }
20386 }
20387 assert!(
20388 compared > 0,
20389 "{NAME}: every attempt hit a named refusal:\n{}",
20390 refusals.join("\n")
20391 );
20392 for (i, (label, _)) in arms.iter().enumerate() {
20393 assert!(
20394 totals[i] > 0,
20395 "{NAME}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
20396 the gate would prove nothing about that arm. refusals:\n{}",
20397 refusals.join("\n")
20398 );
20399 }
20400 eprintln!(
20401 "{NAME}: {compared}/{} attempts pixel-exact, HORZ_A_32={} HORZ_B_32={} \
20402 VERT_A_32={} VERT_B_32={}, {} named refusals",
20403 LR_SEEDS.len(),
20404 totals[0],
20405 totals[1],
20406 totals[2],
20407 totals[3],
20408 refusals.len()
20409 );
20410 }
20411
20412 /// lane-ab32 r1: the 10-bit twin of the gate above -- his two films are
20413 /// yuv420p10le, so an 8-bit-only AB gate proves nothing about the streams
20414 /// that matter. Same recipe through [`ten_bit_tool_gate`], which sums the
20415 /// per-arm counters only over attempts that decoded and pixel-compared.
20416 #[test]
20417 fn a_real_aomenc_10bit_stream_with_a_32_level_ab_partition_decodes_pixel_exact() {
20418 const NAME: &str =
20419 "a_real_aomenc_10bit_stream_with_a_32_level_ab_partition_decodes_pixel_exact";
20420 if !have_ffmpeg() {
20421 eprintln!("SKIP {NAME}: no ffmpeg");
20422 return;
20423 }
20424 if !have_aomenc() {
20425 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20426 return;
20427 }
20428 ten_bit_tool_gate(
20429 NAME,
20430 256,
20431 256,
20432 1,
20433 &[
20434 "--ec-fixture-noise",
20435 "--cq-level=45",
20436 "--limit=1",
20437 "--kf-max-dist=0",
20438 "--enable-1to4-partitions=0",
20439 "--enable-filter-intra=0",
20440 "--enable-smooth-intra=0",
20441 "--enable-paeth-intra=0",
20442 "--enable-directional-intra=0",
20443 "--enable-angle-delta=0",
20444 "--enable-tx-size-search=0",
20445 "--enable-cdef=0",
20446 "--enable-restoration=0",
20447 "--enable-palette=0",
20448 "--enable-intrabc=0",
20449 "--enable-cfl-intra=0",
20450 "--enable-ref-frame-mvs=0",
20451 // last wins: the flags under test go after the base recipe
20452 "--enable-rect-partitions=1",
20453 "--enable-ab-partitions=1",
20454 "--min-partition-size=16",
20455 "--max-partition-size=32",
20456 ],
20457 &LR_SEEDS,
20458 &[
20459 ("HORZ_A_32", crate::decode::intra_horz_a_hits),
20460 ("HORZ_B_32", crate::decode::intra_horz_b_hits),
20461 ("VERT_A_32", crate::decode::intra_vert_a_hits),
20462 ("VERT_B_32", crate::decode::intra_vert_b_hits),
20463 ],
20464 );
20465 }
20466
20467 /// lane-cwarp r1: a real `--enable-global-motion=1 --enable-dist-wtd-comp=1`
20468 /// stream over a rotating/zooming source, so a `GLOBAL_GLOBALMV` compound
20469 /// block lands under a ROTZOOM/AFFINE model and each of its two references
20470 /// is predicted through its OWN global warp
20471 /// (`crate::warp::warp_affine_compound`, libaom `av1_warp_plane` with
20472 /// `conv_params->is_compound`) rather than translationally. Before r1 that
20473 /// path was SILENTLY WRONG -- no refusal named it, both taps went through
20474 /// `mc::predict_compound_intermediate`. `compound_warp_hits() > 0` is a
20475 /// hard assert: a run where the encoder never emitted one proves nothing.
20476 /// A decode error or a pixel mismatch is a FAILURE, never a skip.
20477 fn run_compound_global_warp_gate(name: &str, ten_bit: bool) {
20478 let _gate_lock = lock_gate_counters();
20479 assert!(have_ffmpeg(), "{name}: ffmpeg required");
20480 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
20481 let (width, height, frame_count) = (64usize, 64usize, 24usize);
20482 let before = crate::decode::compound_warp_hits();
20483 let mut matched = 0u32;
20484 let mut named_refusals = 0u32;
20485 let mut attempts = 0u32;
20486 for cq in [32u32, 45, 55] {
20487 for (i, rate) in [0.010f64, 0.022].iter().enumerate() {
20488 attempts += 1;
20489 let duration = frame_count as f64 / 25.0;
20490 // A rotation about the frame centre plus a slow zoom is what
20491 // aomenc's global-motion search fits a ROTZOOM/AFFINE model to;
20492 // mandelbrot gives it real, non-flat texture to track.
20493 let source = format!(
20494 "mandelbrot=size={w}x{h}:rate=25:start_x={sx}:start_y=-0.4,\
20495 rotate=a={rate}*n:ow={w}:oh={h}:c=black,scale={width}:{height}",
20496 w = width * 2,
20497 h = height * 2,
20498 sx = -0.6 + 0.01 * (i as f64),
20499 );
20500 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
20501 let y4m = Command::new("ffmpeg")
20502 .args([
20503 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
20504 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
20505 "-f", "yuv4mpegpipe", "-",
20506 ])
20507 .stdin(Stdio::null())
20508 .stdout(Stdio::piped())
20509 .stderr(Stdio::piped())
20510 .output()
20511 .expect("ffmpeg failed to run");
20512 assert!(
20513 y4m.status.success(),
20514 "ffmpeg fixture: {}",
20515 String::from_utf8_lossy(&y4m.stderr)
20516 );
20517 let cq_arg = format!("--cq-level={cq}");
20518 let mut args: Vec<&str> = vec![
20519 "--codec=av1",
20520 "--passes=1",
20521 "--end-usage=q",
20522 &cq_arg,
20523 "--cpu-used=0",
20524 "--kf-max-dist=1000",
20525 "--threads=1",
20526 "--row-mt=0",
20527 "--auto-alt-ref=1",
20528 "--lag-in-frames=25",
20529 "--enable-fwd-kf=0",
20530 "--enable-order-hint=1",
20531 // the two tools this gate exists for
20532 "--enable-global-motion=1",
20533 "--enable-dist-wtd-comp=1",
20534 "--enable-warped-motion=1",
20535 "--enable-obmc=1",
20536 "--enable-masked-comp=1",
20537 "--enable-onesided-comp=0",
20538 "--enable-interintra-comp=1",
20539 "--enable-interintra-wedge=0",
20540 "--enable-smooth-interintra=1",
20541 "--tune-content=default",
20542 // partition/intra tools this decoder does not code yet --
20543 // same exclusion list every compound gate carries.
20544 "--enable-rect-partitions=0",
20545 "--enable-ab-partitions=0",
20546 "--enable-1to4-partitions=0",
20547 "--enable-filter-intra=0",
20548 "--enable-smooth-intra=0",
20549 "--enable-paeth-intra=0",
20550 "--enable-directional-intra=0",
20551 "--enable-angle-delta=0",
20552 "--enable-tx-size-search=0",
20553 "--enable-cdef=0",
20554 "--enable-restoration=0",
20555 "--max-partition-size=32",
20556 "--min-partition-size=32",
20557 "--enable-palette=0",
20558 "--enable-intrabc=0",
20559 "--enable-cfl-intra=0",
20560 "--enable-ref-frame-mvs=0",
20561 ];
20562 if ten_bit {
20563 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
20564 }
20565 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
20566 let mut child = Command::new(aomenc_path())
20567 .args(&args)
20568 .stdin(Stdio::piped())
20569 .stdout(Stdio::piped())
20570 .stderr(Stdio::piped())
20571 .spawn()
20572 .expect("aomenc failed to start");
20573 child
20574 .stdin
20575 .take()
20576 .expect("aomenc stdin")
20577 .write_all(&y4m.stdout)
20578 .expect("writing y4m to aomenc");
20579 let out = child.wait_with_output().expect("aomenc failed to run");
20580 assert!(
20581 out.status.success(),
20582 "aomenc refused the fixture: {}",
20583 String::from_utf8_lossy(&out.stderr)
20584 );
20585 let stream = out.stdout;
20586 let frames = match decode_stream(&stream) {
20587 Err(e) => {
20588 let msg = e.to_string();
20589 assert!(
20590 msg.contains("unsupported"),
20591 "{name} failed outright, not a named refusal (cq {cq}): {msg}"
20592 );
20593 assert!(
20594 !msg.contains("warp"),
20595 "{name} refused on warp (cq {cq}) -- warp decode is ported: {msg}"
20596 );
20597 named_refusals += 1;
20598 eprintln!("{name} cq {cq} rate {rate} refusal: {msg}");
20599 continue;
20600 }
20601 Ok(frames) => frames,
20602 };
20603 let want = if ten_bit {
20604 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20605 } else {
20606 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20607 };
20608 assert_eq!(frames.len(), frame_count);
20609 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
20610 && frames
20611 .iter()
20612 .zip(&want)
20613 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
20614 {
20615 std::fs::write(&path, &stream).expect("writing pinned stream");
20616 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
20617 }
20618 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
20619 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq})");
20620 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq})");
20621 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq})");
20622 }
20623 matched += 1;
20624 }
20625 }
20626 let hits = crate::decode::compound_warp_hits() - before;
20627 eprintln!(
20628 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
20629 compound_warp_hits={hits}"
20630 );
20631 assert!(
20632 hits > 0,
20633 "{name}: no compound block was predicted through a per-ref global warp \
20634 ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
20635 );
20636 assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran");
20637 }
20638
20639 /// lane-fimv r1 (class `wrong-alphabet-same-value`): libaom
20640 /// `motion_mode_allowed` (blockd.h ~1484) only returns `WARPED_CAUSAL`
20641 /// when `!xd->cur_frame_force_integer_mv`, so on a frame whose header set
20642 /// `force_integer_mv` an otherwise warp-eligible block reads the 2-symbol
20643 /// `obmc_cdf`, not the 3-symbol `motion_mode_cdf`. This decoder read the
20644 /// 3-symbol alphabet there (silent tile desync, no refusal named it).
20645 ///
20646 /// The fixture is screen content that is mostly static with only
20647 /// whole-pixel motion, which is exactly what aomenc's own
20648 /// `av1_is_integer_mv` (`encoder_utils.c:1357`, >=80% of blocks matching
20649 /// their collocated block) needs to set `cur_frame_force_integer_mv`
20650 /// under `--tune-content=screen` (seq `force_integer_mv == 2`, adaptive:
20651 /// `encoder.c:4171`). Two hard asserts, both class
20652 /// `gate-blind-to-feature`: at least one decoded frame header carried
20653 /// `force_integer_mv = 1`, and at least one block took the 2-symbol
20654 /// alphabet where `allow_warped_motion = 1` and `num_proj_ref >= 1` would
20655 /// have picked the 3-symbol one. A decode error or a pixel mismatch is a
20656 /// FAILURE, never a skip.
20657 #[track_caller]
20658 fn run_fimv_motion_mode_gate(name: &str, ten_bit: bool) {
20659 let _gate_lock = lock_gate_counters();
20660 assert!(have_ffmpeg(), "{name}: ffmpeg required");
20661 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
20662 let (width, height, frame_count) = (64usize, 64usize, 20usize);
20663 let fimv_frames_before = crate::decode::fimv_frame_hits();
20664 let alphabet_before = crate::decode::fimv_alphabet_hits();
20665 let mut matched = 0u32;
20666 let mut named_refusals = 0u32;
20667 let mut attempts = 0u32;
20668 let mut refusals = Vec::new();
20669 for cq in [32u32, 45, 55] {
20670 for step in [4u32, 8] {
20671 attempts += 1;
20672 // lane-fimv r1: per-attempt snapshots. The aggregate
20673 // assertions below are satisfied by a single lucky cq/step
20674 // cell; these prove EVERY attempt that decoded and
20675 // pixel-compared really carried the header state and the
20676 // forced alphabet under test (class gate-blind-to-feature).
20677 let attempt_fimv_before = crate::decode::fimv_frame_hits();
20678 let attempt_alphabet_before = crate::decode::fimv_alphabet_hits();
20679 let duration = frame_count as f64 / 25.0;
20680 // Flat screen-content tiles with hard edges, translating by a
20681 // whole number of pixels per frame: static enough for
20682 // `av1_is_integer_mv`, moving enough for a real inter block
20683 // with overlappable neighbours.
20684 let source = format!(
20685 "color=c=black:s={width}x{height}:r=25,\
20686 drawbox=x='8+{step}*mod(trunc(t*25)\\,3)':y=8:w=20:h=20:color=white:t=fill,\
20687 drawbox=x=36:y='6+{step}*mod(trunc(t*25)+1\\,3)':w=16:h=16:color=0x808080:t=fill,\
20688 drawbox=x=4:y=44:w=56:h=12:color=0xC0C0C0:t=fill"
20689 );
20690 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
20691 let y4m = Command::new("ffmpeg")
20692 .args([
20693 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
20694 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
20695 "-f", "yuv4mpegpipe", "-",
20696 ])
20697 .stdin(Stdio::null())
20698 .stdout(Stdio::piped())
20699 .stderr(Stdio::piped())
20700 .output()
20701 .expect("ffmpeg failed to run");
20702 assert!(
20703 y4m.status.success(),
20704 "ffmpeg fixture: {}",
20705 String::from_utf8_lossy(&y4m.stderr)
20706 );
20707 let cq_arg = format!("--cq-level={cq}");
20708 let mut args: Vec<&str> = vec![
20709 "--codec=av1",
20710 "--passes=1",
20711 "--end-usage=q",
20712 &cq_arg,
20713 "--cpu-used=0",
20714 "--kf-max-dist=1000",
20715 "--threads=1",
20716 "--row-mt=0",
20717 // single reference only: the 10-bit compound MC defect
20718 // (see `a_real_compound_global_warp_10bit_stream_...`)
20719 // is unrelated to this lane and would mask it.
20720 "--auto-alt-ref=0",
20721 "--lag-in-frames=0",
20722 "--enable-fwd-kf=0",
20723 "--enable-order-hint=1",
20724 // the flag combination this gate exists for: warp allowed
20725 // by the header, OBMC available, global motion off (so the
20726 // GLOBALMV suppression is not what picks the alphabet).
20727 "--tune-content=screen",
20728 "--enable-warped-motion=1",
20729 "--enable-obmc=1",
20730 "--enable-global-motion=0",
20731 "--enable-masked-comp=0",
20732 "--enable-onesided-comp=0",
20733 "--enable-interintra-comp=0",
20734 "--enable-interintra-wedge=0",
20735 "--enable-smooth-interintra=0",
20736 "--enable-dist-wtd-comp=0",
20737 // partition/intra tools this decoder does not code yet --
20738 // the same exclusion list every inter gate here carries.
20739 "--enable-rect-partitions=0",
20740 "--enable-ab-partitions=0",
20741 "--enable-1to4-partitions=0",
20742 "--enable-filter-intra=0",
20743 "--enable-smooth-intra=0",
20744 "--enable-paeth-intra=0",
20745 "--enable-directional-intra=0",
20746 "--enable-angle-delta=0",
20747 "--enable-tx-size-search=0",
20748 "--enable-cdef=0",
20749 "--enable-restoration=0",
20750 "--max-partition-size=32",
20751 "--min-partition-size=32",
20752 "--enable-palette=0",
20753 "--enable-intrabc=0",
20754 "--enable-cfl-intra=0",
20755 "--enable-ref-frame-mvs=0",
20756 ];
20757 if ten_bit {
20758 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
20759 }
20760 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
20761 let mut child = Command::new(aomenc_path())
20762 .args(&args)
20763 .stdin(Stdio::piped())
20764 .stdout(Stdio::piped())
20765 .stderr(Stdio::piped())
20766 .spawn()
20767 .expect("aomenc failed to start");
20768 child
20769 .stdin
20770 .take()
20771 .expect("aomenc stdin")
20772 .write_all(&y4m.stdout)
20773 .expect("writing y4m to aomenc");
20774 let out = child.wait_with_output().expect("aomenc failed to run");
20775 assert!(
20776 out.status.success(),
20777 "aomenc refused the fixture: {}",
20778 String::from_utf8_lossy(&out.stderr)
20779 );
20780 let stream = out.stdout;
20781 let frames = match decode_stream(&stream) {
20782 Err(e) => {
20783 let msg = e.to_string();
20784 assert!(
20785 msg.contains("unsupported"),
20786 "{name} failed outright (cq {cq} step {step}): {msg}"
20787 );
20788 named_refusals += 1;
20789 refusals.push(format!("cq {cq} step {step}: {msg}"));
20790 continue;
20791 }
20792 Ok(frames) => frames,
20793 };
20794 let want = if ten_bit {
20795 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20796 } else {
20797 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20798 };
20799 assert_eq!(frames.len(), frame_count);
20800 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
20801 && frames
20802 .iter()
20803 .zip(&want)
20804 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
20805 {
20806 std::fs::write(&path, &stream).expect("writing pinned stream");
20807 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
20808 }
20809 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
20810 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq} step {step})");
20811 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq} step {step})");
20812 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq} step {step})");
20813 }
20814 assert!(
20815 crate::decode::fimv_frame_hits() > attempt_fimv_before,
20816 "{name} (cq {cq} step {step}): decoded and compared all \
20817 frames but no frame header had force_integer_mv=1 -- \
20818 this attempt is vacuous"
20819 );
20820 assert!(
20821 crate::decode::fimv_alphabet_hits() > attempt_alphabet_before,
20822 "{name} (cq {cq} step {step}): no block was forced onto the \
20823 2-symbol obmc alphabet by force_integer_mv while \
20824 allow_warped_motion=1 and num_proj_ref>=1 -- this attempt \
20825 is vacuous"
20826 );
20827 matched += 1;
20828 }
20829 }
20830 let fimv_frames = crate::decode::fimv_frame_hits() - fimv_frames_before;
20831 let alphabet = crate::decode::fimv_alphabet_hits() - alphabet_before;
20832 eprintln!(
20833 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
20834 force_integer_mv frames={fimv_frames}, forced-2-symbol blocks={alphabet}\n{}",
20835 refusals.join("\n")
20836 );
20837 assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran");
20838 assert!(
20839 fimv_frames > 0,
20840 "{name}: no decoded frame header had force_integer_mv=1 \
20841 ({matched} matches of {attempts}) -- gate vacuous"
20842 );
20843 assert!(
20844 alphabet > 0,
20845 "{name}: no block read the 2-symbol obmc alphabet where \
20846 allow_warped_motion=1 and num_proj_ref>=1 would have picked the \
20847 3-symbol motion_mode alphabet -- gate vacuous"
20848 );
20849 }
20850
20851 /// 8-bit arm of [`run_fimv_motion_mode_gate`].
20852 #[test]
20853 fn a_real_force_integer_mv_warp_stream_decodes_pixel_exact() {
20854 run_fimv_motion_mode_gate("a_real_force_integer_mv_warp_stream_decodes_pixel_exact", false);
20855 }
20856
20857 /// 10-bit arm of [`run_fimv_motion_mode_gate`] -- both of his films are
20858 /// `yuv420p10le`.
20859 #[test]
20860 fn a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact() {
20861 run_fimv_motion_mode_gate(
20862 "a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact",
20863 true,
20864 );
20865 }
20866
20867 /// 8-bit arm of [`run_compound_global_warp_gate`].
20868 #[test]
20869 fn a_real_compound_global_warp_stream_decodes_pixel_exact() {
20870 run_compound_global_warp_gate("a_real_compound_global_warp_stream_decodes_pixel_exact", false);
20871 }
20872
20873 /// 10-bit arm of [`run_compound_global_warp_gate`] -- both of his films are
20874 /// `yuv420p10le`, and `warp_affine`'s `bd` was hardcoded 8 before r1.
20875 ///
20876 /// 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
20877 /// very recipe: with `--enable-global-motion=0 --enable-warped-motion=0`
20878 /// (no warp of any kind reachable) the 10-bit stream STILL mismatches at
20879 /// frame 1 luma, cq 32; with `--auto-alt-ref=0 --lag-in-frames=0
20880 /// --enable-dist-wtd-comp=0` (single-reference 10-bit inter only) the same
20881 /// recipe is 6/6 pixel-exact. So: 10-bit single-ref inter is exact, 10-bit
20882 /// compound is not. `mc::diffwtd_mask`'s missing `(bd - 8)` round term was
20883 /// found and fixed while bisecting this, but is NOT the whole defect.
20884 /// The warp wiring under test here is bit-depth generic.
20885 #[test]
20886 fn a_real_compound_global_warp_10bit_stream_decodes_pixel_exact() {
20887 run_compound_global_warp_gate(
20888 "a_real_compound_global_warp_10bit_stream_decodes_pixel_exact",
20889 true,
20890 );
20891 }
20892
20893 /// lane-mcomp64 r1: at 64x64 `av1_is_wedge_used` is false
20894 /// (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`), so libaom's
20895 /// `read_compound_type` codes NO `compound_type` symbol and INFERS
20896 /// `COMPOUND_DIFFWTD`; only the 1-bit `mask_type` literal follows. This
20897 /// decoder used to refuse such a block by name ("a masked compound 64x64
20898 /// inter block..."), because reading the symbol would have desynced.
20899 ///
20900 /// The recipe pins every block to 64x64 (`--sb-size=64
20901 /// --max-partition-size=64 --min-partition-size=64`) with masked compound
20902 /// on and distance-weighted compound off, so the only way a
20903 /// `comp_group_idx == 1` block can be coded is through the inferred arm.
20904 /// `diffwtd_inferred_hits` is snapshotted PER ATTEMPT and only accumulated
20905 /// for attempts that decoded AND pixel-compared (class
20906 /// `counter-from-refused-stream`), and is hard-asserted at the end. A
20907 /// decode error or a pixel mismatch is a FAILURE, never a skip.
20908 #[track_caller]
20909 fn run_diffwtd_inferred_64x64_gate(name: &str, ten_bit: bool) {
20910 let _gate_lock = lock_gate_counters();
20911 assert!(have_ffmpeg(), "{name}: ffmpeg required");
20912 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
20913 let (width, height, frame_count) = (128usize, 128usize, 16usize);
20914 let mut matched = 0u32;
20915 let mut named_refusals = 0u32;
20916 let mut attempts = 0u32;
20917 let mut fired = 0usize;
20918 let mut refusals: Vec<String> = Vec::new();
20919 for cq in [32u32, 45, 55] {
20920 for (i, zoom) in [0.004f64, 0.010].iter().enumerate() {
20921 attempts += 1;
20922 let attempt_before = crate::decode::diffwtd_inferred_hits();
20923 let duration = frame_count as f64 / 25.0;
20924 // Hard-edged, moving content: a difference-weighted mask only
20925 // wins where the two references genuinely disagree over part
20926 // of a 64x64 block (a smooth `gradients` source measured
20927 // diffwtd_hits == 0, memory `gate-blind-to-feature`).
20928 let source = format!(
20929 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y=-0.4:\
20930 end_scale=0.3:maxiter=200,\
20931 noise=alls=6:allf=t+u:all_seed={seed}",
20932 sx = -0.6 + zoom * (i as f64 + 1.0),
20933 seed = 1000 + cq,
20934 );
20935 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
20936 let y4m = Command::new("ffmpeg")
20937 .args([
20938 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
20939 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
20940 "-f", "yuv4mpegpipe", "-",
20941 ])
20942 .stdin(Stdio::null())
20943 .stdout(Stdio::piped())
20944 .stderr(Stdio::piped())
20945 .output()
20946 .expect("ffmpeg failed to run");
20947 assert!(
20948 y4m.status.success(),
20949 "ffmpeg fixture: {}",
20950 String::from_utf8_lossy(&y4m.stderr)
20951 );
20952 let cq_arg = format!("--cq-level={cq}");
20953 let mut args: Vec<&str> = vec![
20954 "--codec=av1",
20955 "--passes=1",
20956 "--end-usage=q",
20957 &cq_arg,
20958 "--cpu-used=0",
20959 "--kf-max-dist=1000",
20960 "--threads=1",
20961 "--row-mt=0",
20962 "--auto-alt-ref=1",
20963 "--lag-in-frames=16",
20964 "--enable-fwd-kf=0",
20965 "--enable-order-hint=1",
20966 // the tools this gate exists for: masked compound on, the
20967 // difference-weighted arm on, the distance-weighted
20968 // competitor off so comp_group_idx==1 is the encoder's
20969 // only masked choice at a size where wedge does not exist.
20970 "--enable-masked-comp=1",
20971 "--enable-diff-wtd-comp=1",
20972 "--enable-dist-wtd-comp=0",
20973 "--enable-onesided-comp=0",
20974 "--enable-interintra-comp=0",
20975 "--enable-global-motion=0",
20976 "--enable-warped-motion=1",
20977 "--enable-obmc=1",
20978 "--tune-content=default",
20979 // partition/intra tools this decoder does not code yet --
20980 // same exclusion list every compound gate carries.
20981 "--enable-rect-partitions=0",
20982 "--enable-ab-partitions=0",
20983 "--enable-1to4-partitions=0",
20984 "--enable-filter-intra=0",
20985 "--enable-smooth-intra=0",
20986 "--enable-paeth-intra=0",
20987 "--enable-directional-intra=0",
20988 "--enable-angle-delta=0",
20989 "--enable-tx-size-search=0",
20990 "--enable-cdef=0",
20991 "--enable-restoration=0",
20992 "--enable-palette=0",
20993 "--enable-intrabc=0",
20994 "--enable-cfl-intra=0",
20995 "--enable-ref-frame-mvs=0",
20996 // every block is a whole 64x64 superblock: the ONLY size
20997 // where compound_type is inferred rather than coded.
20998 "--sb-size=64",
20999 "--max-partition-size=64",
21000 "--min-partition-size=64",
21001 ];
21002 if ten_bit {
21003 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
21004 }
21005 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
21006 let mut child = Command::new(aomenc_path())
21007 .args(&args)
21008 .stdin(Stdio::piped())
21009 .stdout(Stdio::piped())
21010 .stderr(Stdio::piped())
21011 .spawn()
21012 .expect("aomenc failed to start");
21013 child
21014 .stdin
21015 .take()
21016 .expect("aomenc stdin")
21017 .write_all(&y4m.stdout)
21018 .expect("writing y4m to aomenc");
21019 let out = child.wait_with_output().expect("aomenc failed to run");
21020 assert!(
21021 out.status.success(),
21022 "aomenc refused the fixture: {}",
21023 String::from_utf8_lossy(&out.stderr)
21024 );
21025 let stream = out.stdout;
21026 let frames = match decode_stream(&stream) {
21027 Err(e) => {
21028 let msg = e.to_string();
21029 assert!(
21030 msg.contains("unsupported"),
21031 "{name} failed outright, not a named refusal (cq {cq}): {msg}"
21032 );
21033 assert!(
21034 !msg.contains("masked compound 64x64"),
21035 "{name} refused the inferred-DIFFWTD 64x64 block (cq {cq}) -- \
21036 that refusal is lifted, this is forbidden: {msg}"
21037 );
21038 named_refusals += 1;
21039 refusals.push(msg.clone());
21040 eprintln!("{name} cq {cq} variant {i} refusal: {msg}");
21041 continue;
21042 }
21043 Ok(frames) => frames,
21044 };
21045 let want = if ten_bit {
21046 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
21047 } else {
21048 ffmpeg_decode_sequence(&stream, width, height, frame_count)
21049 };
21050 assert_eq!(frames.len(), frame_count);
21051 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
21052 && frames
21053 .iter()
21054 .zip(&want)
21055 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
21056 {
21057 std::fs::write(&path, &stream).expect("writing pinned stream");
21058 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
21059 }
21060 for (f, (got, want)) in frames.iter().zip(&want).enumerate() {
21061 assert_eq!(got.y, want.y, "{name} frame {f} luma vs ffmpeg (cq {cq})");
21062 assert_eq!(got.u, want.u, "{name} frame {f} U vs ffmpeg (cq {cq})");
21063 assert_eq!(got.v, want.v, "{name} frame {f} V vs ffmpeg (cq {cq})");
21064 }
21065 // decoded AND compared: only now does this attempt's own
21066 // inferred-DIFFWTD count mean anything.
21067 fired += crate::decode::diffwtd_inferred_hits() - attempt_before;
21068 matched += 1;
21069 }
21070 }
21071 eprintln!(
21072 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
21073 diffwtd_inferred_hits (decoded+compared attempts only)={fired}"
21074 );
21075 assert!(matched > 0, "{name}: every attempt refused ({refusals:?}) -- no pixel compare ran");
21076 assert!(
21077 fired > 0,
21078 "{name}: no inferred-DIFFWTD 64x64 block fired on a compared attempt \
21079 ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
21080 );
21081 }
21082
21083 /// 8-bit arm of [`run_diffwtd_inferred_64x64_gate`].
21084 #[test]
21085 fn a_real_aomenc_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact() {
21086 run_diffwtd_inferred_64x64_gate(
21087 "a_real_aomenc_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact",
21088 false,
21089 );
21090 }
21091
21092 /// 10-bit arm of [`run_diffwtd_inferred_64x64_gate`] -- both of his films
21093 /// are `yuv420p10le`.
21094 #[test]
21095 fn a_real_aomenc_10bit_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact() {
21096 run_diffwtd_inferred_64x64_gate(
21097 "a_real_aomenc_10bit_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact",
21098 true,
21099 );
21100 }
21101
21102 /// lane-maskcomp r2 / lane-wedge r3: `--enable-masked-comp=1` streams
21103 /// must consume `compound_type`/`wedge_idx`/`wedge_sign`/`mask_type`
21104 /// entropy-exact AND build the real blend, DIFFWTD or WEDGE --
21105 /// `masked_compound_hits() > 0` is a hard assert and BOTH
21106 /// `COMPOUND_DIFFWTD` and `COMPOUND_WEDGE` refusals are now FORBIDDEN
21107 /// (matches interintra's own gate). r3: `--enable-dist-wtd-comp=0`
21108 /// (forces the masked choice toward wedge when comp_group_idx==1) plus
21109 /// a hard-diagonal-edge `geq` source (wedge's OBLIQUE directions favor
21110 /// a real diagonal edge over the r2 gradients content) to fire
21111 /// COMPOUND_WEDGE live; `wedge_hits()` is soft-skipped (not hard
21112 /// asserted) on a zero-hit run -- the recipe search is not proven to
21113 /// converge every run, see charter's "if no recipe fires" fallback.
21114 #[test]
21115 fn a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact() {
21116 const NAME: &str = "a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact";
21117 let _gate_lock = lock_gate_counters();
21118 if !have_ffmpeg() {
21119 eprintln!("SKIP {NAME}: no ffmpeg");
21120 return;
21121 }
21122 if !have_aomenc() {
21123 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
21124 return;
21125 }
21126 let (width, height, frame_count) = (64usize, 64usize, 24usize);
21127 let mut named_refusals = 0u32;
21128 let mut matched = 0u32;
21129 let n_attempts: u32 = std::env::var("EC_MASKCOMP_GATE_ATTEMPTS")
21130 .ok()
21131 .and_then(|s| s.parse().ok())
21132 .unwrap_or(80);
21133 for attempt in 0..n_attempts {
21134 let seed = 42 + attempt;
21135 let duration = frame_count as f64 / 25.0;
21136 // lane-wedge r3: a hard diagonal edge (not a smooth gradient)
21137 // is the content wedge's OBLIQUE master masks are shaped for --
21138 // `mandelbrot`'s pan position varies the edge angle/position
21139 // across attempts the way the r2 gradients seed did.
21140 let source = format!(
21141 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
21142 sx = -0.6 + 0.005 * (attempt as f64),
21143 sy = -0.4 + 0.005 * (attempt as f64)
21144 );
21145 let y4m = Command::new("ffmpeg")
21146 .args([
21147 "-v",
21148 "error",
21149 "-f",
21150 "lavfi",
21151 "-i",
21152 &source,
21153 "-t",
21154 &duration.to_string(),
21155 "-pix_fmt",
21156 "yuv420p",
21157 "-f",
21158 "yuv4mpegpipe",
21159 "-",
21160 ])
21161 .stdin(Stdio::null())
21162 .stdout(Stdio::piped())
21163 .stderr(Stdio::piped())
21164 .output()
21165 .expect("ffmpeg failed to run");
21166 assert!(
21167 y4m.status.success(),
21168 "ffmpeg fixture: {}",
21169 String::from_utf8_lossy(&y4m.stderr)
21170 );
21171 let args: Vec<&str> = vec![
21172 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
21173 // occurrence, so overrides go before the base list).
21174 "--enable-diff-wtd-comp=1",
21175 "--codec=av1",
21176 "--passes=1",
21177 "--end-usage=q",
21178 "--cq-level=45",
21179 "--cpu-used=0",
21180 "--kf-max-dist=1000",
21181 "--threads=1",
21182 "--row-mt=0",
21183 "--auto-alt-ref=1",
21184 "--lag-in-frames=16",
21185 "--enable-fwd-kf=0",
21186 "--enable-order-hint=1",
21187 "--enable-warped-motion=1",
21188 // r3: mandelbrot's pan/zoom triggers aomenc's single-ref
21189 // GLOBALMV global-motion search (a capability distinct from
21190 // and outside this lane's scope) -- off, matching this
21191 // gate's own goal of exercising masked compound, not GM.
21192 "--enable-global-motion=0",
21193 "--enable-obmc=1",
21194 "--tune-content=default",
21195 "--enable-masked-comp=1",
21196 // r3: force the masked choice toward wedge (r2 always set
21197 // this =1; distance-weighted compound competes with the
21198 // wedge/diffwtd choice for the same comp_group_idx==1 slot).
21199 "--enable-dist-wtd-comp=0",
21200 "--enable-interintra-comp=1",
21201 "--enable-onesided-comp=0",
21202 "--enable-interintra-wedge=0",
21203 "--enable-smooth-interintra=1",
21204 "--enable-rect-partitions=0",
21205 "--enable-ab-partitions=0",
21206 "--enable-1to4-partitions=0",
21207 "--enable-filter-intra=0",
21208 "--enable-smooth-intra=0",
21209 "--enable-paeth-intra=0",
21210 "--enable-directional-intra=0",
21211 "--enable-angle-delta=0",
21212 "--enable-tx-size-search=0",
21213 "--enable-cdef=0",
21214 "--enable-restoration=0",
21215 "--max-partition-size=32",
21216 "--min-partition-size=32",
21217 "--enable-palette=0",
21218 "--enable-intrabc=0",
21219 "--enable-cfl-intra=0",
21220 "--enable-ref-frame-mvs=0",
21221 "--obu",
21222 "-o",
21223 "-",
21224 "-",
21225 ];
21226 let mut child = Command::new(aomenc_path())
21227 .args(&args)
21228 .stdin(Stdio::piped())
21229 .stdout(Stdio::piped())
21230 .stderr(Stdio::piped())
21231 .spawn()
21232 .expect("aomenc failed to start");
21233 child
21234 .stdin
21235 .take()
21236 .expect("aomenc stdin")
21237 .write_all(&y4m.stdout)
21238 .expect("writing y4m to aomenc");
21239 let out = child.wait_with_output().expect("aomenc failed to run");
21240 assert!(
21241 out.status.success(),
21242 "aomenc refused the fixture: {}",
21243 String::from_utf8_lossy(&out.stderr)
21244 );
21245 let stream = out.stdout;
21246 let frames = match decode_stream(&stream) {
21247 Err(e) => {
21248 let msg = e.to_string();
21249 assert!(
21250 msg.contains("unsupported"),
21251 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
21252 );
21253 assert!(
21254 !msg.contains("warp"),
21255 "{NAME} refused on warp (seed {seed}) -- warp decode is ported: {msg}"
21256 );
21257 assert!(
21258 !msg.contains("masked COMPOUND_REFERENCE"),
21259 "{NAME} refused a masked-compound block (seed {seed}) -- both DIFFWTD \
21260 and WEDGE blends are ported, this refusal is forbidden: {msg}"
21261 );
21262 assert!(
21263 !msg.contains("interintra"),
21264 "{NAME} refused on interintra (seed {seed}) -- non-wedge \
21265 interintra is ported: {msg}"
21266 );
21267 named_refusals += 1;
21268 eprintln!("seed {seed} refusal: {msg}");
21269 if std::env::var_os("EC_AV1_GATE_DUMP").is_some() {
21270 // r1's self-pin is armed via EC_AV1_GATE_DUMP=<path>
21271 // only for a real pixel MISMATCH below, not for this
21272 // still-expected named refusal.
21273 }
21274 continue;
21275 }
21276 Ok(frames) => frames,
21277 };
21278 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
21279 assert_eq!(frames.len(), frame_count);
21280 let mismatched = frames
21281 .iter()
21282 .zip(&ffmpeg_frames)
21283 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
21284 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
21285 std::fs::write(&path, &stream).expect("writing pinned stream");
21286 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
21287 }
21288 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21289 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
21290 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
21291 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
21292 }
21293 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
21294 // stream again, comparing EVERY decode-order frame -- the hidden
21295 // (show_frame == 0) alt-ref frames the ffmpeg compare above
21296 // cannot see, because both sides of it emit shown frames only.
21297 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
21298 eprintln!(
21299 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
21300 {hidden_n} hidden, all pixel-exact vs the oracle"
21301 );
21302 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
21303 // libaom's temporal alt-ref filter absorbs this recipe's hidden
21304 // frames, so the compare above is vacuous -- re-encode the same
21305 // fixture with --arnr-maxframes=0 and compare THOSE.
21306 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
21307 eprintln!(
21308 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
21309 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
21310 );
21311 }
21312 matched += 1;
21313 }
21314 // r1: observed flaky at 40 attempts -- aomenc's cpu-used=0 RD is
21315 // run-to-run nondeterministic in whether it ever picks
21316 // comp_group_idx == 1 for this synthetic gradients content, and
21317 // allow_screen_content_tools sometimes eats most of a small seed
21318 // window (class gate-recipe-confound / never-fired-gate, memory).
21319 // 80 attempts is the mitigation, not a fix; a still-zero run here
21320 // is that sampling flake, not a decode regression -- check
21321 // masked_compound_hits/named_refusals in the panic message before
21322 // assuming a real bug.
21323 // r2: DIFFWTD is ported and gated, so a zero-hit run is no longer
21324 // soft-skipped -- hard assert, matching the interintra gate.
21325 assert!(
21326 crate::decode::masked_compound_hits() > 0,
21327 "{NAME}: zero masked-compound blocks fired ({matched} matches, {named_refusals} \
21328 other refusals out of {n_attempts}) -- gate proved nothing this run"
21329 );
21330 // lane-defon r1: `--enable-diff-wtd-comp=1` is now spelled on this
21331 // recipe, so the DIFFWTD half of MASKED_COMPOUND_HITS must fire.
21332 assert!(
21333 crate::decode::diffwtd_hits() > 0,
21334 "{NAME}: zero COMPOUND_DIFFWTD blends ({matched} matches, {named_refusals} \
21335 other refusals out of {n_attempts}) -- --enable-diff-wtd-comp=1 proved nothing"
21336 );
21337 // r3: wedge_hits() is soft-skipped, not hard-asserted -- the recipe
21338 // search (dist-wtd-comp=0 + diagonal mandelbrot content) is not
21339 // proven to fire wedge on every run; charter's fallback is to land
21340 // the checksum-verified codebook + blend with this soft path.
21341 if crate::decode::wedge_hits() == 0 {
21342 eprintln!(
21343 "{NAME}: WARNING wedge_hits()==0 this run -- COMPOUND_WEDGE never fired \
21344 ({matched} matches, {named_refusals} refusals out of {n_attempts}); codebook \
21345 is checksum-verified but unexercised live this run"
21346 );
21347 }
21348 eprintln!(
21349 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
21350 out of {n_attempts}, masked_compound_hits={} wedge_hits={}",
21351 crate::decode::masked_compound_hits(),
21352 crate::decode::wedge_hits()
21353 );
21354 }
21355
21356
21357 /// lane-inter16ab r5: `COMPOUND_WEDGE` on a RECTANGULAR inter block --
21358 /// the shapes `av1_wedge_params_lookup` gives the `hgtw`/`hltw`
21359 /// codebooks (8x16/16x32/8x32 and 16x8/32x16/32x8), which this decoder
21360 /// refused by name until this round ("the wedge codebook is
21361 /// square-only"). `--enable-rect-partitions=1` with
21362 /// `--min-partition-size=16 --max-partition-size=32` is what makes
21363 /// aomenc's RD put a masked compound block on a 16x32/32x16 strip
21364 /// (measured: ~/.cache/inter16ab-tmp/rw2.sh, 24/24 streams at cq 50/55
21365 /// carry one and decode to the end at BOTH bit depths).
21366 ///
21367 /// Class `counter-from-refused-stream`: the per-shape counters are read
21368 /// as a DELTA around one attempt and only counted for attempts that
21369 /// decoded fully AND compared pixel-exact -- a refused attempt's hits
21370 /// are discarded. Every decode-order frame (including hidden alt-ref
21371 /// frames) is compared via [`decode_all_frames_vs_oracle`], and an
21372 /// attempt that mismatches while carrying NO rect wedge fails the gate
21373 /// through `oos_mismatch` rather than being blamed on this lane.
21374 #[test]
21375 fn a_real_aomenc_stream_with_a_rectangular_compound_wedge_decodes_pixel_exact() {
21376 const NAME: &str =
21377 "a_real_aomenc_stream_with_a_rectangular_compound_wedge_decodes_pixel_exact";
21378 let _gate_lock = lock_gate_counters();
21379 if !have_ffmpeg() {
21380 eprintln!("SKIP {NAME}: no ffmpeg");
21381 return;
21382 }
21383 if !have_aomenc() {
21384 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
21385 return;
21386 }
21387 let (width, height, frame_count) = (96usize, 96usize, 24usize);
21388 // Per rect shape (8x16, 16x8, 16x32, 32x16, 8x32, 32x8), summed over
21389 // the attempts that decoded AND matched.
21390 let mut shapes_proved = [0usize; 6];
21391 let (mut named_refusals, mut matched, mut oos_mismatch) = (0u32, 0u32, 0u32);
21392 let mut attempts = 0u32;
21393 for bit_depth in [8u32, 10u32] {
21394 for &cq in &[50u32, 55] {
21395 for a in 0..4u32 {
21396 attempts += 1;
21397 let duration = frame_count as f64 / 25.0;
21398 // Same hard-diagonal-edge content the square wedge gate
21399 // uses (wedge's masters are OBLIQUE), panned per attempt.
21400 let source = format!(
21401 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
21402 sx = -0.6 + 0.01 * (a as f64),
21403 sy = -0.4 + 0.01 * (a as f64)
21404 );
21405 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
21406 let y4m = Command::new("ffmpeg")
21407 .args([
21408 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
21409 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
21410 "-f", "yuv4mpegpipe", "-strict", "-1", "-",
21411 ])
21412 .stdin(Stdio::null())
21413 .stdout(Stdio::piped())
21414 .stderr(Stdio::piped())
21415 .output()
21416 .expect("ffmpeg failed to run");
21417 assert!(
21418 y4m.status.success(),
21419 "{NAME}: ffmpeg fixture: {}",
21420 String::from_utf8_lossy(&y4m.stderr)
21421 );
21422 let cq_arg = format!("--cq-level={cq}");
21423 let depth_arg = format!("--bit-depth={bit_depth}");
21424 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
21425 let args: Vec<&str> = vec![
21426 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
21427 &depth_arg, &input_depth_arg,
21428 "--kf-max-dist=1000", "--threads=1", "--row-mt=0", "--auto-alt-ref=1",
21429 "--lag-in-frames=16", "--enable-fwd-kf=0", "--enable-order-hint=1",
21430 "--enable-warped-motion=1", "--enable-global-motion=0",
21431 "--enable-obmc=1", "--enable-diff-wtd-comp=1",
21432 "--enable-interintra-comp=1", "--enable-onesided-comp=0",
21433 "--enable-interintra-wedge=1", "--enable-smooth-interintra=1",
21434 "--enable-ab-partitions=0", "--enable-1to4-partitions=0",
21435 "--enable-filter-intra=0", "--enable-smooth-intra=0",
21436 "--enable-paeth-intra=0", "--enable-directional-intra=0",
21437 "--enable-angle-delta=0", "--enable-tx-size-search=0",
21438 "--enable-cdef=0", "--enable-restoration=0", "--enable-palette=0",
21439 "--enable-intrabc=0", "--enable-cfl-intra=0",
21440 "--enable-ref-frame-mvs=0",
21441 // Per-arm overrides LAST (aomenc keeps the last
21442 // occurrence of a repeated --enable-* flag): masked
21443 // compound ON, distance-weighted OFF so the
21444 // comp_group_idx==1 slot goes to wedge/diffwtd, and
21445 // rectangular partitions ON at 16/32 -- the shapes
21446 // the hgtw/hltw codebooks exist for.
21447 "--enable-masked-comp=1", "--enable-dist-wtd-comp=0",
21448 "--enable-rect-partitions=1",
21449 "--min-partition-size=16", "--max-partition-size=32",
21450 "--obu", "-o", "-", "-",
21451 ];
21452 let mut child = Command::new(aomenc_path())
21453 .args(&args)
21454 .stdin(Stdio::piped())
21455 .stdout(Stdio::piped())
21456 .stderr(Stdio::piped())
21457 .spawn()
21458 .expect("aomenc failed to start");
21459 child
21460 .stdin
21461 .take()
21462 .expect("aomenc stdin")
21463 .write_all(&y4m.stdout)
21464 .expect("writing y4m to aomenc");
21465 let out = child.wait_with_output().expect("aomenc failed to run");
21466 assert!(
21467 out.status.success(),
21468 "aomenc refused the fixture: {}",
21469 String::from_utf8_lossy(&out.stderr)
21470 );
21471 let stream = out.stdout;
21472 let before = crate::stream::rect_wedge_hits();
21473 let frames = match decode_stream(&stream) {
21474 Err(e) => {
21475 let msg = e.to_string();
21476 assert!(
21477 msg.contains("unsupported"),
21478 "{NAME} failed outright, not a named refusal \
21479 ({bit_depth}-bit cq{cq} attempt {a}): {msg}"
21480 );
21481 assert!(
21482 !msg.contains("wedge codebook is square-only"),
21483 "{NAME}: the rect wedge codebook is ported -- this refusal is \
21484 forbidden ({bit_depth}-bit cq{cq} attempt {a}): {msg}"
21485 );
21486 named_refusals += 1;
21487 eprintln!("{bit_depth}-bit cq{cq} attempt {a} refusal: {msg}");
21488 continue;
21489 }
21490 Ok(frames) => frames,
21491 };
21492 let after = crate::stream::rect_wedge_hits();
21493 let fired: Vec<usize> =
21494 (0..6).map(|k| after[k] - before[k]).collect();
21495 let ffmpeg_frames = if bit_depth == 10 {
21496 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
21497 } else {
21498 ffmpeg_decode_sequence(&stream, width, height, frame_count)
21499 };
21500 assert_eq!(frames.len(), ffmpeg_frames.len());
21501 let mismatched = frames
21502 .iter()
21503 .zip(&ffmpeg_frames)
21504 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
21505 if fired.iter().sum::<usize>() == 0 {
21506 if mismatched {
21507 oos_mismatch += 1;
21508 eprintln!(
21509 "{NAME}: {bit_depth}-bit cq{cq} attempt {a} MISMATCHES with zero \
21510 rectangular wedge block -- another shape's defect"
21511 );
21512 }
21513 continue;
21514 }
21515 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21516 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit cq{cq} attempt {a}, shapes {fired:?})");
21517 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit cq{cq} attempt {a}, shapes {fired:?})");
21518 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit cq{cq} attempt {a}, shapes {fired:?})");
21519 }
21520 // class gate-blind-to-hidden-frames: the shown-frame
21521 // compare above cannot see the alt-ref frames this
21522 // recipe's --lag-in-frames=16 produces.
21523 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
21524 eprintln!(
21525 "{NAME}: {bit_depth}-bit cq{cq} attempt {a}: shapes {fired:?}, \
21526 {hidden_total} decode-order frames ({hidden_n} hidden) pixel-exact"
21527 );
21528 for k in 0..6 {
21529 shapes_proved[k] += fired[k];
21530 }
21531 m

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