forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mod.rs2695 lines, 134.2 KiBHistoryRawDownload
1//! The stream-level entry point a real decoder needs: walk a raw AV1 OBU
2//! stream (`Encoded::stream`, or any low-overhead-format bitstream this
3//! crate's own writers produce) via [`ec_av1_syntax::Av1Parser`] and dispatch
4//! each frame's tile payload to [`crate::decode::decode_key_frame_tile_with_cdfs`] /
5//! [`crate::decode::decode_inter_frame_tile_with_cdfs`], threading a
6//! single-slot picture DPB exactly as [`crate::encode::encode_sequence`] does
7//! on the write side, plus the full 8-slot *CDF* reference bank spec 7.20
8//! (`load_cdfs`) and 7.4 (the reference frame update) describe: a frame whose
9//! header names `primary_ref_frame != PRIMARY_REF_NONE` resumes from the
10//! adapted table a previous frame's `refresh_frame_flags` left in that slot,
11//! rather than the spec 8.4 defaults.
12//!
13//! This is the only reachable path for a caller that does not have the
14//! encoder's own `Encoded::tile`/`mi_cols`/`mi_rows`/`base_q_idx` fields (they
15//! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is
16//! an implementation detail of how this crate happens to build it).
17
18use ec_av1_syntax::{
19 Av1Parser, FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE,
20 SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, Tile, TxMode,
21};
22// Census-only: read outside `mod tests` only in comments; the non-test lib
23// target never touches them, so they ride in behind cfg(test) (via the test
24// module's `use super::*`).
25#[cfg(test)]
26use ec_av1_syntax::{SEG_LVL_ALT_Q, SEG_LVL_MAX};
27use ec_core::{Error, Result};
28
29use crate::cdf_state::Cdfs;
30use crate::decode;
31#[cfg(test)]
32use crate::decode::decode_key_frame_tile_lr;
33use crate::decode::{decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs, q_ctx_of};
34use crate::encode::Picture;
35
36/// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a
37/// mid-film mismatch splits into "reconstruction" (compare against
38/// `ffmpeg -c:v libdav1d -filmgrain 0`) and "grain synthesis" in one run.
39fn no_grain() -> bool {
40 std::env::var_os("EC_AV1_NO_GRAIN").is_some()
41}
42
43// lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the
44// current thread, overriding the environment variable. Every ffmpeg/aomdec
45// pixel gate in this repo compares SHOWN frames only (class
46// gate-blind-to-hidden-frames), so the hidden alt-ref frames a real aomenc
47// stream carries were never compared at all; the gate that does compare
48// them needs a dump path that cannot race a sibling test's decode on
49// another thread, which a process-global env var cannot give.
50thread_local! {
51 static FINAL_DUMP_PREFIX: std::cell::RefCell<Option<String>> =
52 const { std::cell::RefCell::new(None) };
53}
54
55/// Sets (or with `None` clears) this thread's `EC_AV1_FINAL_DUMP` prefix.
56#[allow(dead_code)]
57pub(crate) fn set_final_dump_prefix(prefix: Option<String>) {
58 FINAL_DUMP_PREFIX.with(|c| *c.borrow_mut() = prefix);
59}
60
61fn final_dump_prefix() -> Option<String> {
62 FINAL_DUMP_PREFIX
63 .with(|c| c.borrow().clone())
64 .or_else(|| std::env::var("EC_AV1_FINAL_DUMP").ok())
65}
66
67/// 32x32-level 1:4 strip counters, for `decode_probe`'s fixture search:
68/// (HORZ_4 strips, VERT_4 strips, strips that read coefficients).
69/// lane-inter4 r1: the INTER-frame partition counters this lane's gates
70/// assert -- `(32x8, 8x32, 64x32, 32x64, 64x16, 16x64)` strips decoded.
71pub fn inter_rect_counters() -> (usize, usize, usize, usize, usize, usize) {
72 (
73 crate::decode::rect4_32_horz_inter_hits(),
74 crate::decode::rect4_32_vert_inter_hits(),
75 crate::decode::inter_sb_horz_hits(),
76 crate::decode::inter_sb_vert_hits(),
77 crate::decode::inter_sb_horz4_hits(),
78 crate::decode::inter_sb_vert4_hits(),
79 )
80}
81
82/// lane-r14 r2: luma transform units of an inter strip with a 64-px axis,
83/// coded as the truncated low-32 coefficient corner.
84pub fn rect64_inter_tu_hits() -> usize {
85 crate::decode::rect64_inter_tu_hits()
86}
87
88/// lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
89/// inter strip (`TX_32X8`/`TX_8X32`), `[32x8, 8x32]`.
90pub fn rect32x8_inter_tu_hits() -> [usize; 2] {
91 crate::decode::rect32x8_inter_tu_hits()
92}
93
94/// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherited a
95/// `tx_type` different from the group's FIRST sub-block, i.e. groups that can
96/// only decode right under `av1_get_tx_type`'s chroma-reference rule.
97pub fn sub8_chroma_tx_from_ref_hits() -> usize {
98 crate::decode::sub8_chroma_tx_from_ref_hits()
99}
100
101/// lane-intra16x4: `(16x4, 4x16, chroma-reference)` INTRA strips decoded inside
102/// an inter 16x16-level 1:4 partition.
103pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
104 crate::decode::intra16x4_in_inter_hits()
105}
106
107/// lane-sub8intra: INTRA 8x4/4x8 leaves inside an inter frame's sub-8x8
108/// HORZ/VERT partition, `(8x4, 4x8, chroma-reference, mixed groups, split
109/// 4x4 leaves)`.
110pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
111 crate::decode::sub8_intra_rect_hits()
112}
113
114/// lane-r14 r3: RECTANGULAR var-tx leaf transform units, `[32x16, 16x32]` --
115/// the leaves `sub_tx_size_map` produces when a 1:4 strip with a 64-px axis
116/// splits its transform (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`).
117pub fn vartx_rect_leaf_hits() -> [usize; 2] {
118 crate::decode::vartx_rect_leaf_hits()
119}
120
121/// How many rect intra strips read the `use_intrabc` symbol on the last decode.
122pub fn rect_intrabc_reads() -> usize {
123 crate::decode::rect_intrabc_reads()
124}
125
126/// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma a lossless
127/// frame walked as per-4x4 inter units.
128pub fn intrabc_rect8_lossless_luma_hits() -> usize {
129 crate::decode::intrabc_rect8_lossless_luma_hits()
130}
131
132/// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a
133/// lossless 4:4:4 frame walked as per-4x4 `Chroma4` units.
134pub fn intrabc_rect8_lossless_chroma_hits() -> usize {
135 crate::decode::intrabc_rect8_lossless_chroma_hits()
136}
137
138/// Gate-side reset for the lane-av1-ibc444rect counters above.
139pub fn reset_ibc444rect_hits() {
140 crate::decode::reset_ibc444rect_hits()
141}
142
143/// lane-av1chromarect: 128-root intra-BC HORZ/VERT strips whose chroma plane
144/// block was sized `bw >> ss_x` by `bh >> ss_y` rather than the hardcoded
145/// 4:2:0 halving -- i.e. the 4:4:4 (and 4:4:0) cells, where
146/// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h:1372) applies no
147/// halving of its own. At 4:2:0 the two forms are the same arithmetic, so a
148/// `>= 1` witness can only come from a stream that is not 4:2:0. EXCLUSIVE to
149/// `decode_intrabc_owned_rect`: no other caller sizes a 128-root intra-BC
150/// strip's chroma plane block.
151pub fn ibc_owned_rect_chroma_footprint_444_hits() -> usize {
152 crate::decode::ibc_owned_rect_chroma_footprint_444_hits()
153}
154
155/// Gate-side reset for the lane-av1chromarect counter above.
156pub fn reset_ibc_owned_rect_chroma_footprint_444_hits() {
157 crate::decode::reset_ibc_owned_rect_chroma_footprint_444_hits()
158}
159
160/// lane-av1chromadc: chroma units of a skipped block whose intra-BC / UV
161/// palette override had to be windowed to the unit's own extent -- `cn_cols *
162/// cn_rows > 1`, which at 4:2:0 never happens and at 4:4:4 is every block of
163/// 64 and above. Counts UNITS. EXCLUSIVE to `decode_block`'s skipped square
164/// block chroma walk.
165pub fn skip_chroma_override_window_hits() -> usize {
166 crate::decode::skip_chroma_override_window_hits()
167}
168
169/// Gate-side reset for the lane-av1chromadc counter above.
170pub fn reset_skip_chroma_override_window_hits() {
171 crate::decode::reset_skip_chroma_override_window_hits()
172}
173
174/// lane-av1rectreach: the `chroma_tiled` walk's per-unit reach and grid-shape
175/// counters, as `(unit_reach_differs_from_block, 2x1 units, 1x2 units, other
176/// multi-unit units)`. See [`crate::decode::rect_tiled_chroma_grid_hits`].
177pub fn rect_tiled_chroma_grid_hits() -> (usize, usize, usize, usize) {
178 crate::decode::rect_tiled_chroma_grid_hits()
179}
180
181/// Gate-side reset for the lane-av1rectreach counters above.
182pub fn reset_rect_tiled_chroma_grid_hits() {
183 crate::decode::reset_rect_tiled_chroma_grid_hits()
184}
185
186/// `(y, uv)` palette blocks RECONSTRUCTED inside an inter frame (lane-t900
187/// r22) -- the counter a screen-content witness gate reads to prove it
188/// exercises the inter-frame palette path, not the key frame's.
189pub fn intra_in_inter_palette_hits() -> (usize, usize) {
190 crate::decode::intra_in_inter_palette_hits()
191}
192
193/// `(y, uv)` palette blocks reconstructed on an 8x8 LEAF inside an inter
194/// frame (lane-t900 r23) -- the site-specific half of
195/// [`intra_in_inter_palette_hits`], which a >=16 block also moves.
196pub fn inter8_palette_hits() -> (usize, usize) {
197 crate::decode::inter8_palette_hits()
198}
199
200/// lane-rect64port r1: coded 64-level HORZ/VERT intra strips whose luma
201/// transform unit is the un-split TX_64X32 (orient 0) / TX_32X64 (orient 1).
202pub fn rect64_corner_tu_hits(orient: usize) -> usize {
203 crate::decode::rect64_corner_tu_hits(orient)
204}
205
206/// lane-inter16ab r4: RECTANGULAR var-tx leaves with a 4-px axis, `[8x4, 4x8]`
207/// -- what `sub_tx_size_map[TX_16X4] == TX_8X4` produces when a 16x16-level
208/// 1:4 inter strip splits its transform.
209pub fn vartx_rect_leaf4_hits() -> [usize; 2] {
210 crate::decode::vartx_rect_leaf4_hits()
211}
212
213/// lane-inter16ab r5: COMPOUND_WEDGE / wedge-INTERINTRA blocks that used a
214/// RECTANGULAR wedge codebook row, per shape (`RECT_WEDGE_SHAPES` order:
215/// 8x16, 16x8, 16x32, 32x16, 8x32, 32x8).
216pub fn rect_wedge_hits() -> [usize; 6] {
217 crate::decode::rect_wedge_hits()
218}
219
220/// lane-inter16ab r5: the wedge-interintra half of [`rect_wedge_hits`].
221pub fn rect_wii_hits() -> [usize; 6] {
222 crate::decode::rect_wii_hits()
223}
224
225/// lane-sb128c r7: the 128 root's rect arms -- (gathered edge HORZ, gathered
226/// edge VERT, inter 128x64 blocks, inter 64x128 blocks).
227pub fn sb128_rect_counters() -> (usize, usize, usize, usize) {
228 (
229 crate::decode::part128_edge_horz_hits(),
230 crate::decode::part128_edge_vert_hits(),
231 crate::decode::inter_sb128_horz_hits(),
232 crate::decode::inter_sb128_vert_hits(),
233 )
234}
235
236/// lane-av1-ibcrect: the 128 root's interior partition arms plus the key-frame
237/// intra 128-axis blocks -- (split, none, horz, vert, ab[4], intra_horz,
238/// intra_vert). Non-zero horz/vert mean a stream carried real PARTITION_HORZ/
239/// VERT at the 128 root, so an intrabc-rect hunt can tell "the partition was
240/// never chosen" from "chosen and decoded intra (or refused)".
241pub fn part128_census() -> (usize, usize, usize, usize, [usize; 4], usize, usize) {
242 (
243 crate::decode::part128_split_hits(),
244 crate::decode::part128_none_hits(),
245 crate::decode::part128_horz_hits(),
246 crate::decode::part128_vert_hits(),
247 crate::decode::part128_ab_hits(),
248 crate::decode::intra_sb128_hits().0,
249 crate::decode::intra_sb128_hits().1,
250 )
251}
252
253/// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip whose
254/// reconstruction ([`crate::decode::decode_intrabc_128rect`]) ran -- the
255/// engagement counter the sb128 intrabc-rect gate asserts on.
256pub fn intrabc_128rect_hits() -> usize {
257 crate::decode::intrabc_128rect_hits()
258}
259
260/// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc strip's
261/// mu-chunk walk read, one per `read_inter_plane` chroma call. At 4:2:2 a
262/// 64x64 mu chunk's chroma plane block is 32x64 and holds TWO STACKED
263/// TX_32X32 units per plane; the square-cut walk this gate witnesses read
264/// one. Measured on the pinned witness: 8 before, 48 after.
265pub fn intrabc_128rect_chroma_chunk_hits() -> usize {
266 crate::decode::intrabc_128rect_chroma_chunk_hits()
267}
268
269/// lane-av1-ibc128chunk: the 128-root intrabc strip's per-axis chroma chunk
270/// extents as `(64 >> ss_x) << 8 | (64 >> ss_y)` on the last chunk walked --
271/// 32|32 at 4:2:0, 32|64 at 4:2:2, 64|64 at 4:4:4.
272pub fn intrabc_128rect_chunk_shape() -> usize {
273 crate::decode::intrabc_128rect_chunk_shape()
274}
275
276/// Blocks reconstructed with intra block copy at an 8x8 LEAF specifically
277/// (lane-kf900 r7's shape); [`crate::decode::intrabc_hits`] counts every shape.
278pub fn leaf8_intrabc_hits() -> usize {
279 crate::decode::leaf8_intrabc_hits()
280}
281
282/// Blocks whose `use_intrabc` symbol came out 1 and took the DV path, at ANY
283/// shape -- the engagement counter the intrabc gates assert on. It counts
284/// "read a `use_intrabc` DV", not "reconstructed": a block the rect-strip
285/// reader REFUSES for an unported shape bumps it too (the symbol and the DV
286/// are parsed before the refusal). [`leaf8_intrabc_hits`] is its 8x8-leaf
287/// subset.
288pub fn intrabc_hits() -> usize {
289 crate::decode::intrabc_hits()
290}
291
292/// lane-av1txbands: sub-8x8 group chroma-reference leaves that USED intrabc and
293/// were SKIPPED -- the route that armed [`crate::decode::intrabc_hits`]'s chroma
294/// transform slot and then read no chroma coefficient. A non-zero value is what
295/// makes the disarm at that route load-bearing on a real stream.
296pub fn skipped_intrabc_chroma_arm_hits() -> usize {
297 crate::decode::skipped_intrabc_chroma_arm_hits()
298}
299
300/// lane-sb128c r8: the 128 root's INTRA (key-frame) rect arm -- (128x64
301/// blocks, 64x128 blocks, blocks per resolved intra `tx_depth` 0/1/2).
302pub fn intra_sb128_counters() -> (usize, usize, [usize; 3]) {
303 crate::decode::intra_sb128_hits()
304}
305
306/// lane-inter128intra r1: the 128 root's HORZ/VERT half coded INTRA inside an
307/// INTER frame -- (128x64 blocks, 64x128 blocks).
308pub fn intra128_in_inter_counters() -> [usize; 2] {
309 crate::decode::intra128_in_inter_hits()
310}
311
312/// lane-lossless128: intra 128-axis blocks decoded on a LOSSLESS frame, where
313/// every plane is a TX_4X4 unit. The engagement counter for
314/// `a_lossless_sb128_rect_intra_block_decodes_sample_exact`.
315pub fn intra128_lossless_counters() -> usize {
316 crate::decode::intra128_lossless_hits()
317}
318
319/// lane-av1-128rectspan: chroma transform units re-stamped by
320/// `decode_block_128rect`'s end-of-block replay, and how many of those
321/// replays stamped a height that was not the unit's own.
322/// lane-av1422lift: the second half was described as "the 4:2:2 signature --
323/// zero on every stream this decoder admits, since 4:2:2 is refused by name
324/// at the sequence header", and that was TRUE. 4:2:2 is decoded now and the
325/// mismatch is NOT zero: measured on this branch's tip, the two
326/// `422_intrabc_sb128_strip*` pins each read `(72, 9)` while the other 19
327/// committed 4:2:2 cells read `(0, 0)`. Those two pins are byte-exact
328/// against ffmpeg, so the non-zero half counts the arm's own designed case
329/// and is not a defect. lane-av1422mismatch9: the predicate is
330/// `luma_span != luma_span_h` (`chroma_tx << ss_x` vs `<< ss_y`), true by
331/// CONSTRUCTION at ss (1,0), and the replay re-stamps with the same per-axis
332/// pair the in-loop walk used, so the counter is a 4:2:2 shape test, not a
333/// divergence test (`record_mi_chroma` writes only the left/above context
334/// arrays, never a pixel). One 4:2:2 gate now reads the pair and asserts the
335/// measured `(72, 9)`:
336/// `the_422_block_128rect_chroma_chunk_gather_stays_per_axis`; the other
337/// reader is on a 4:4:4 stream, where the mismatch half is structurally zero.
338pub fn sb128rect_chroma_replay_counters() -> (usize, usize) {
339 crate::decode::sb128rect_chroma_replay_hits()
340}
341
342/// lane-sb128c r9: the four AB shapes at the 128 root, in `PARTITION_HORZ_A`,
343/// `_HORZ_B`, `_VERT_A`, `_VERT_B` order (key and inter tile paths share the
344/// counter -- it is bumped where the root symbol resolves).
345pub fn sb128_ab_counters() -> [usize; 4] {
346 crate::decode::part128_ab_hits()
347}
348
349/// lane-obmcrec r1: OBMC neighbours taken from the second half of a 1:4-strip
350/// chroma pair -- the shape whose filter record the r1 fix re-sourced.
351pub fn obmc_pair_filter_hits() -> usize {
352 crate::decode::obmc_pair_filter_hits()
353}
354
355/// Gate counters for the 4x32/32x4 rectangular strips: `(horz, vert, coeff)` hits.
356pub fn rect4_32_counters() -> (usize, usize, usize) {
357 (
358 crate::decode::rect4_32_horz_hits(),
359 crate::decode::rect4_32_vert_hits(),
360 crate::decode::rect4_coeff_hits(),
361 )
362}
363
364/// lane-inter4 r4: rectangular inter transform units coded whole, rect
365/// var-tx trees that split, and OBMC blends run on a 16x8/8x16 leaf -- the
366/// three counters a recipe sweep needs to see from outside the crate.
367pub fn rect_inter_tu_counters() -> (usize, usize, usize) {
368 (
369 crate::decode::rect_inter_tu_hits(),
370 crate::decode::rect_inter_txsplit_hits(),
371 crate::decode::obmc_rect_leaf_hits(),
372 )
373}
374
375/// Decode every frame in a raw AV1 OBU stream, in coding order.
376///
377/// A key frame becomes the reference for the inter frames that follow it,
378/// until the next key frame resets the DPB — the same single-slot chain
379/// [`crate::encode::encode_sequence`] threads on the write side. Only a
380/// `Frame` OBU (an uncompressed header and its tile group in one OBU, which
381/// is all this crate's encoder ever writes) carries a tile payload; sequence
382/// headers and temporal delimiters are consumed for the state they carry (or
383/// skipped) and produce no picture.
384///
385/// # Errors
386/// Returns an error when the stream is truncated or malformed (as
387/// [`Av1Parser`] reports it), when a frame header names anything this
388/// crate's tile decoders do not reconstruct (see their own docs), or when an
389/// inter frame appears before any key frame has supplied a reference.
390pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
391 let mut pictures = Vec::new();
392 decode_stream_with(data, |picture, _decode_idx, shown| {
393 if shown {
394 pictures.push(picture.clone());
395 }
396 Ok(())
397 })?;
398 Ok(pictures)
399}
400
401/// Streaming form of [`decode_stream`]: hand every completed picture to
402/// `sink` the moment it exists and drop it right after, so peak memory is one
403/// output picture plus the 8-slot DPB instead of the whole decoded stream --
404/// a 4K long-GOP segment costs the same as a short one. `decode_stream`
405/// itself is this function collecting into a `Vec`.
406///
407/// `sink` is called with the picture, the decode-order index of the coded
408/// frame it came from, and whether it is output: a hidden reference frame
409/// (`show_frame == 0`) is reported with `shown == false` and is NOT part of
410/// `decode_stream`'s output, a `show_existing_frame` output with `true`.
411/// The grain-synthesised picture is what a shown frame's sink sees; the
412/// reference bank keeps the clean one (spec 7.18.3.1). An `Err` the sink
413/// returns aborts the decode and is returned unchanged.
414///
415/// # Errors
416/// As [`decode_stream`], plus whatever `sink` returns.
417pub fn decode_stream_with(
418 data: &[u8],
419 sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
420) -> Result<()> {
421 decode_stream_with_layers(data, LayerOutput::default(), sink)
422}
423
424/// Which shown frames a sink receives when a temporal unit carries more than
425/// one (spatial layers). Mirrors libaom's `output_all_layers` control.
426#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
427pub enum LayerOutput {
428 /// libaom's default (`output_all_layers == 0`): within one temporal unit
429 /// (delimited by `OBU_TEMPORAL_DELIMITER`) only the last shown frame is
430 /// output, which is the highest spatial layer. Only streams whose OBUs
431 /// carry a spatial layer id above 0 are affected; every other stream
432 /// delivers exactly what [`LayerOutput::AllShown`] does.
433 #[default]
434 LastShownPerTemporalUnit,
435 /// Every shown frame, in decode order (libaom `output_all_layers == 1`).
436 AllShown,
437}
438
439/// [`decode_stream_with`] with the output policy named (see [`LayerOutput`]).
440/// Hidden frames (`shown == false`) are always forwarded, as before.
441///
442/// # Errors
443/// As [`decode_stream_with`].
444pub fn decode_stream_with_layers(
445 data: &[u8],
446 layers: LayerOutput,
447 mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
448) -> Result<()> {
449 let keep = match layers {
450 LayerOutput::AllShown => None,
451 LayerOutput::LastShownPerTemporalUnit => last_shown_per_temporal_unit(data),
452 };
453 let Some(keep) = keep else {
454 return decode_stream_with_threads(data, decode_threads(), sink);
455 };
456 let mut shown_index = 0usize;
457 decode_stream_with_threads(data, decode_threads(), |picture, decode_idx, shown| {
458 if !shown {
459 return sink(picture, decode_idx, shown);
460 }
461 let k = shown_index;
462 shown_index += 1;
463 // A plan shorter than the decode (never expected) forwards the rest.
464 if keep.get(k).copied().unwrap_or(true) {
465 sink(picture, decode_idx, shown)
466 } else {
467 Ok(())
468 }
469 })
470}
471
472/// The output plan of [`LayerOutput::LastShownPerTemporalUnit`]: one flag per
473/// shown frame in stream order, `true` for the last shown frame of each
474/// temporal unit. `None` when the stream has no spatial layer above 0 (so the
475/// policy does not apply) or no temporal delimiter (its units are unknown).
476///
477/// Only OBU headers and the first payload byte of frame OBUs are read (the
478/// `show_existing_frame` and `show_frame` bits of spec 5.9.2), so the plan
479/// costs no decode state.
480fn last_shown_per_temporal_unit(data: &[u8]) -> Option<Vec<bool>> {
481 const OBU_TEMPORAL_DELIMITER: u8 = 2;
482 const OBU_FRAME_HEADER: u8 = 3;
483 const OBU_FRAME: u8 = 6;
484 // (temporal unit index, spatial_id) of each shown frame, in stream order.
485 let mut shown: Vec<(usize, u8)> = Vec::new();
486 let mut tu = 0usize;
487 let mut saw_td = false;
488 let mut spatial_layers = false;
489 let mut pos = 0usize;
490 while pos < data.len() {
491 let b0 = data[pos];
492 let obu_type = (b0 >> 3) & 0xf;
493 let extension = b0 & 0x04 != 0;
494 let has_size = b0 & 0x02 != 0;
495 let mut header_len = 1usize;
496 let mut spatial_id = 0u8;
497 if extension {
498 let b1 = *data.get(pos + 1)?;
499 spatial_id = (b1 >> 3) & 0x3;
500 header_len = 2;
501 }
502 let (payload_start, payload_len) = if has_size {
503 let mut value = 0usize;
504 let mut len = 0usize;
505 loop {
506 let byte = *data.get(pos + header_len + len)?;
507 value |= usize::from(byte & 0x7f) << (7 * len);
508 len += 1;
509 if byte & 0x80 == 0 || len == 8 {
510 break;
511 }
512 }
513 (pos + header_len + len, value)
514 } else {
515 (pos + header_len, data.len().checked_sub(pos + header_len)?)
516 };
517 let payload_end = payload_start.checked_add(payload_len)?.min(data.len());
518 if extension && spatial_id > 0 {
519 spatial_layers = true;
520 }
521 match obu_type {
522 OBU_TEMPORAL_DELIMITER => {
523 if saw_td {
524 tu += 1;
525 }
526 saw_td = true;
527 }
528 OBU_FRAME_HEADER | OBU_FRAME => {
529 // uncompressed_header: show_existing_frame (1 bit), then
530 // frame_type (2 bits) and show_frame (1 bit).
531 if let Some(&first) = data
532 .get(payload_start)
533 .filter(|_| payload_start < payload_end)
534 {
535 let shown_frame = if first & 0x80 != 0 {
536 true
537 } else {
538 first & 0x10 != 0
539 };
540 if shown_frame {
541 shown.push((tu, spatial_id));
542 }
543 }
544 }
545 _ => {}
546 }
547 pos = payload_end;
548 }
549 if !spatial_layers || !saw_td {
550 return None;
551 }
552 Some(
553 shown
554 .iter()
555 .enumerate()
556 .map(|(k, &(unit, _))| shown.get(k + 1).is_none_or(|&(next, _)| next != unit))
557 .collect(),
558 )
559}
560
561/// lane-thread2: how many threads [`decode_stream_with`] decodes with --
562/// `EC_AV1_THREADS`, default `min(cores, 6)` (lane-av1threads, see
563/// [`crate::autothreads`]). `EC_AV1_THREADS=1` is the single-threaded decoder
564/// unchanged, which is what keeps every gate that reads this crate's
565/// per-thread counters meaningful.
566fn decode_threads() -> usize {
567 static N: std::sync::LazyLock<usize> = std::sync::LazyLock::new(|| {
568 crate::autothreads::decode_threads_from(
569 crate::envflags::var("EC_AV1_THREADS").ok().as_deref(),
570 )
571 });
572 *N
573}
574
575/// lane-thread2: output-order queue. A leaf frame decoded on a worker
576/// finishes whenever it finishes; `sink` must still see every picture in the
577/// order the stream codes them, so each sink call gets an `emit_seq` when the
578/// main thread reaches its frame header and is held here until every earlier
579/// one has been emitted. (The decode index the sink is TOLD is unchanged, and
580/// is deliberately not unique: a `show_existing_frame` re-output reports the
581/// count of frames decoded before it, per this function's contract.)
582#[derive(Default)]
583struct Reorder {
584 next: usize,
585 // lane-pool1: the picture is shared, not owned -- a decoded frame that
586 // refreshes a reference slot is already behind an `Arc` for the slot, and
587 // handing the output an owned `Picture` meant copying every plane of it
588 // (24 MB per 4K 10-bit frame) purely to put it in this queue.
589 pending: std::collections::BTreeMap<usize, (std::sync::Arc<Picture>, usize, bool)>,
590}
591
592impl Reorder {
593 fn push(
594 &mut self,
595 seq: usize,
596 picture: std::sync::Arc<Picture>,
597 decode_idx: usize,
598 shown: bool,
599 ) {
600 self.pending.insert(seq, (picture, decode_idx, shown));
601 }
602
603 /// Emits every queued picture whose turn has come. An `Err` from `sink`
604 /// aborts the decode, unchanged, exactly as the serial path did.
605 fn drain(&mut self, sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>) -> Result<()> {
606 while let Some((picture, decode_idx, shown)) = self.pending.remove(&self.next) {
607 self.next += 1;
608 sink(&picture, decode_idx, shown)?;
609 crate::timeline::output(decode_idx);
610 }
611 Ok(())
612 }
613}
614
615/// lane-thread2/3: how many coded frames this PROCESS has dispatched to a
616/// worker thread (see [`decode_stream_with_threads`]). Process-global and
617/// atomic on purpose: it is the only counter here a caller can read after a
618/// threaded decode, and it is what keeps a "decodes identically with 4
619/// threads" gate from silently proving nothing because every frame ran
620/// inline. (lane-thread2 counted only LEAF frames, the only ones it could
621/// dispatch; lane-thread3 dispatches every non-key, non-`show_existing_frame`
622/// frame, hence the rename.)
623static FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
624
625/// Reads [`FRAMES_DISPATCHED`].
626pub fn frames_dispatched() -> usize {
627 FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed)
628}
629
630/// lane-thread3: what one decoded frame stores into every reference slot its
631/// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated
632/// object -- so a slot costs an `Arc` clone instead of a picture copy.
633struct SlotValue {
634 /// lane-twostage: this frame's FILTERED pixels, still being produced
635 /// when the rest of this value is published.
636 pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>>,
637 /// The size those pixels will have, known from the tile decode.
638 width: usize,
639 height: usize,
640 cdfs: Cdfs,
641 motion_field: crate::motion_field::MotionField,
642 seg_map: Vec<u8>,
643 order_hint: u32,
644}
645
646/// lane-thread3: a reference slot's contents as a FUTURE. At `threads > 1`
647/// the 8-slot bank holds these instead of values: a slot refreshed by a frame
648/// that is still decoding on a worker holds the promise from the moment the
649/// parsing thread DISPATCHES that frame, so the next frame can be dispatched
650/// straight away and waits, on its own worker, for exactly the slots it
651/// reads. This is what makes a pyramid stream (aomenc's default, where nearly
652/// every coded frame refreshes a slot, so lane-thread2's leaf rule dispatched
653/// almost nothing) decode in parallel.
654///
655/// DEADLOCK ARGUMENT. A promise is installed into a slot on the parsing
656/// thread, in decode order, when its producer is dispatched; a consumer
657/// captures the promises of the slots it reads at ITS dispatch, which is
658/// strictly later in decode order. Every wait therefore points from a later
659/// coded frame to an earlier one -- the wait graph is the reference DAG, and
660/// is acyclic. The parsing thread waits only for a `show_existing_frame`
661/// output (again an earlier frame) and at the in-flight bound, where it waits
662/// for ANY worker to answer: the earliest in-flight frame has no earlier
663/// in-flight producer, so it is always runnable and the bound always clears.
664/// Each dispatched frame gets its own thread, so a blocked waiter never holds
665/// a resource its producer needs. A producer that errors or panics marks its
666/// promise `Failed`, so no consumer can wait for a value that never comes.
667struct SlotPromise<T = std::sync::Arc<SlotValue>> {
668 state: std::sync::Mutex<PromiseState<T>>,
669 ready: std::sync::Condvar,
670}
671
672enum PromiseState<T> {
673 Pending,
674 Ready(T),
675 Failed,
676}
677
678impl<T: Clone> SlotPromise<T> {
679 /// The state lock, poison-tolerant (lane-av1panichang): a panic while it
680 /// was held must not turn every later `fulfil`/`fail`/`wait` into a second
681 /// panic, which would leave a waiter behind it unreleased.
682 fn lock(&self) -> std::sync::MutexGuard<'_, PromiseState<T>> {
683 self.state
684 .lock()
685 .unwrap_or_else(std::sync::PoisonError::into_inner)
686 }
687
688 fn pending() -> std::sync::Arc<Self> {
689 std::sync::Arc::new(Self {
690 state: std::sync::Mutex::new(PromiseState::Pending),
691 ready: std::sync::Condvar::new(),
692 })
693 }
694
695 /// A slot filled by a frame the parsing thread decoded itself.
696 fn ready(value: T) -> std::sync::Arc<Self> {
697 std::sync::Arc::new(Self {
698 state: std::sync::Mutex::new(PromiseState::Ready(value)),
699 ready: std::sync::Condvar::new(),
700 })
701 }
702
703 fn fulfil(&self, value: T) {
704 *self.lock() = PromiseState::Ready(value);
705 self.ready.notify_all();
706 }
707
708 /// lane-twostage: fulfils only a promise the stage-1 sink did not
709 /// already fill (a superres frame, or a key frame, whose meta is
710 /// published here as it always was).
711 fn fulfil_if_pending(&self, value: impl FnOnce() -> T) {
712 let mut state = self.lock();
713 if matches!(*state, PromiseState::Pending) {
714 *state = PromiseState::Ready(value());
715 }
716 self.ready.notify_all();
717 }
718
719 fn fail(&self) {
720 let mut state = self.lock();
721 if matches!(*state, PromiseState::Pending) {
722 *state = PromiseState::Failed;
723 }
724 self.ready.notify_all();
725 }
726
727 /// Blocks until the producing frame has published this slot.
728 fn wait(&self) -> Result<T> {
729 let mut state = self.lock();
730 loop {
731 match &*state {
732 PromiseState::Ready(value) => return Ok(value.clone()),
733 PromiseState::Failed => {
734 return Err(Error::corrupt(
735 "AV1 decode_stream: a reference frame this frame depends on failed to decode",
736 ));
737 }
738 PromiseState::Pending => {
739 state = self
740 .ready
741 .wait(state)
742 .unwrap_or_else(std::sync::PoisonError::into_inner);
743 }
744 }
745 }
746 }
747}
748
749/// Answers one dispatched job exactly once and releases its promises
750/// (lane-av1panichang). The frame thread blocks in `collect_one` for exactly
751/// one answer per job, so a job that unwinds without sending one would hang
752/// the whole decode. `send` answers on the normal path; `Drop` answers with an
753/// error if the job is still unanswered, which is the only way a job ends
754/// when it unwinds past its own `catch_unwind`.
755///
756/// The error is queued BEFORE the promises fail. A consumer learns of the
757/// failure only by waking on `fail()`, so its own "a reference frame ...
758/// failed" reply is then queued strictly after this frame's real reason.
759/// Failing first let a consumer's secondary error win the race to the channel
760/// under load, and the caller then saw the wrong reason.
761struct JobAnswer {
762 tx: Option<std::sync::mpsc::Sender<LeafResult>>,
763 seq: usize,
764 decode_job: bool,
765 /// The frame's stage-1 promise (its slot meta), when it refreshes slots.
766 stage1: Option<std::sync::Arc<SlotPromise>>,
767 /// The frame's stage-2 promise (its filtered pixels).
768 stage2: Option<std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>>>,
769}
770
771impl JobAnswer {
772 fn new(
773 tx: std::sync::mpsc::Sender<LeafResult>,
774 seq: usize,
775 decode_job: bool,
776 stage1: Option<std::sync::Arc<SlotPromise>>,
777 stage2: Option<std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>>>,
778 ) -> Self {
779 Self {
780 tx: Some(tx),
781 seq,
782 decode_job,
783 stage1,
784 stage2,
785 }
786 }
787
788 /// Answers with `reply`; a failed reply also fails both promises.
789 fn send(&mut self, reply: Result<(std::sync::Arc<Picture>, usize, bool)>) {
790 let failed = reply.is_err();
791 if let Some(tx) = self.tx.take() {
792 let _ = tx.send((self.seq, self.decode_job, reply));
793 }
794 if failed {
795 self.fail_promises();
796 }
797 }
798
799 fn fail_promises(&self) {
800 // Neither stage may leave a consumer waiting for a value that will
801 // never come. `fail` only moves a still-pending promise.
802 if let Some(p) = &self.stage1 {
803 p.fail();
804 }
805 if let Some(p) = &self.stage2 {
806 p.fail();
807 }
808 }
809}
810
811impl Drop for JobAnswer {
812 fn drop(&mut self) {
813 // Still unanswered: the job unwound before it could answer.
814 if let Some(tx) = self.tx.take() {
815 let _ = tx.send((
816 self.seq,
817 self.decode_job,
818 Err(Error::corrupt(
819 "AV1 decode_stream: a worker thread panicked decoding a frame",
820 )),
821 ));
822 self.fail_promises();
823 }
824 }
825}
826
827/// One finished frame from a worker: its output position, whether the job was
828/// a frame DECODE (as opposed to a `show_existing_frame` output, which only
829/// waits for a slot and synthesises grain -- lane-thread3 counts the two
830/// against separate in-flight bounds, since a waiting output job costs no
831/// CPU), and either the (grain-synthesised) picture with the decode index to
832/// report or the error that aborts the stream.
833type LeafResult = (usize, bool, Result<(std::sync::Arc<Picture>, usize, bool)>);
834
835/// Waits for one in-flight job and emits whatever that unblocks.
836fn collect_one(
837 rx: &std::sync::mpsc::Receiver<LeafResult>,
838 decodes: &mut usize,
839 shows: &mut usize,
840 reorder: &mut Reorder,
841 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,
842) -> Result<()> {
843 // Every dispatched worker answers exactly once, panic included (it is
844 // caught and turned into an error below), so the sender count cannot
845 // reach zero while `in_flight > 0`.
846 let (seq, decode_job, result) = rx
847 .recv()
848 .map_err(|_| Error::corrupt("AV1 decode_stream: a worker thread vanished"))?;
849 if decode_job {
850 *decodes -= 1;
851 } else {
852 *shows -= 1;
853 }
854 let (picture, decode_idx, shown) = result?;
855 reorder.push(seq, picture, decode_idx, shown);
856 reorder.drain(sink)
857}
858
859/// A persistent AV1 stream decoder: feed it temporal units in decode order.
860pub struct StreamDecoder {
861 threads: usize,
862 final_dump: Option<String>,
863 parser: Av1Parser,
864 pictures_shown: usize,
865 pictures_decoded: usize,
866 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
867 // previous frame's `refresh_frame_flags` stored into it, exactly like the
868 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
869 // not simply "the previous frame decoded"; a frame whose own predecessor
870 // didn't refresh that slot (an altref/hidden frame, or any GOP with more
871 // than one live reference) must keep predicting from whatever picture is
872 // still sitting there. Round 7's cdffwd hunt: a global `reference`
873 // overwritten every frame silently always used "the most recent decode"
874 // instead, producing a bit-exact motion vector into the WRONG picture --
875 // luma-only (chroma coincidentally shares this fixture's flat regions)
876 // and small-magnitude (the two pictures mostly agree), which is exactly
877 // what made it look like a rounding bug rather than a wrong reference.
878 // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy
879 // its whole picture k times, and its output a (k+1)-th time.
880 ref_slots: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES],
881 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
882 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
883 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
884 // decoded with -- `Picture` itself carries neither, so both ride
885 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
886 motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES],
887 order_hint_slots: [u32; NUM_REF_FRAMES],
888 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
889 // previous frame's `refresh_frame_flags` stored into it -- the frame's
890 // own end-of-tile adapted table, or (when the frame set
891 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
892 cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES],
893 // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also
894 // remembers the segment map the frame stored there decoded, which is what
895 // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`
896 // (spec `load_previous_segment_ids`) for temporal segment-id prediction
897 // and for a `segmentation_update_map == 0` frame's inherited map.
898 seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES],
899 // lane-thread2: output plumbing (inert at `threads == 1`, where nothing
900 // is ever dispatched and `reorder` emits each picture the moment it is
901 // pushed).
902 emit_seq: usize,
903 reorder: Reorder,
904 // lane-thread3: frame decodes and `show_existing_frame` outputs are
905 // bounded separately -- an output job is a promise wait plus a memcpy, so
906 // letting it eat a decode's budget just idles a core (measured: sharing
907 // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%).
908 in_flight_decodes: usize,
909 in_flight_shows: usize,
910 tx: std::sync::mpsc::Sender<LeafResult>,
911 rx: std::sync::mpsc::Receiver<LeafResult>,
912 // lane-thread3: at `threads > 1` THIS is the reference bank -- one
913 // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled
914 // itself and pending for one an in-flight frame will fill. The owned
915 // arrays above are then untouched (and the single-threaded path never
916 // creates a promise: it stays exactly the decoder it was, which is what
917 // keeps every counter-reading gate meaningful).
918 slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES],
919 // lane-timeline: which decoded frame installed each slot's promise, so
920 // the timeline records a dependency EDGE (frame -> producing frame) and
921 // not just a slot number. `usize::MAX` = nobody yet.
922 slot_owner: [usize; NUM_REF_FRAMES],
923 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
924 // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone
925 // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no
926 // tile payload of its own -- `OBU_FRAME` (the `ObuKind::Frame` arm below)
927 // only ever folds ONE tile group into the header's own OBU. Stash the
928 // header here and accumulate tiles from each `OBU_TILE_GROUP` that
929 // follows until every tile of the frame has arrived.
930 pending_header: Option<Box<FrameHeader>>,
931 pending_tiles: Vec<Tile>,
932 // lane-thread1: this stream's per-frame decode state (was 38 thread_local
933 // statics in decode.rs) -- one object, threaded down the decode call graph.
934 fctx: crate::decode::FrameCtx,
935}
936impl StreamDecoder {
937 /// A decoder with `threads` frame workers (see [`decode_stream_with_threads`]).
938 pub fn new(threads: usize) -> Self {
939 let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
940 Self {
941 threads,
942 final_dump: final_dump_prefix(),
943 parser: Av1Parser::new(),
944 pictures_shown: 0,
945 pictures_decoded: 0,
946 ref_slots: std::array::from_fn(|_| None),
947 motion_field_slots: std::array::from_fn(|_| None),
948 order_hint_slots: [0; NUM_REF_FRAMES],
949 cdf_slots: std::array::from_fn(|_| None),
950 seg_map_slots: std::array::from_fn(|_| None),
951 emit_seq: 0,
952 reorder: Reorder::default(),
953 in_flight_decodes: 0,
954 in_flight_shows: 0,
955 tx,
956 rx,
957 slot_promises: std::array::from_fn(|_| None),
958 slot_owner: [usize::MAX; NUM_REF_FRAMES],
959 pending_header: None,
960 pending_tiles: Vec::new(),
961 fctx: crate::decode::FrameCtx::new(),
962 }
963 }
964
965 /// Decode one temporal unit and return its shown pictures.
966 ///
967 /// # Errors
968 /// As [`decode_stream`]. After an error, start a new decoder at a key frame.
969 pub fn decode_temporal_unit(&mut self, data: &[u8]) -> Result<Vec<Picture>> {
970 let mut pictures = Vec::new();
971 self.decode(data, |picture, _decode_idx, shown| {
972 if shown {
973 pictures.push(picture.clone());
974 }
975 Ok(())
976 })?;
977 Ok(pictures)
978 }
979
980 /// Decode whole frames from `data` (one or more temporal units), handing
981 /// every picture to `sink` as [`decode_stream_with`] does, before returning.
982 ///
983 /// # Errors
984 /// As [`decode_stream_with`].
985 pub fn decode(
986 &mut self,
987 data: &[u8],
988 mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
989 ) -> Result<()> {
990 let mut pictures_shown = self.pictures_shown;
991 let mut pictures_decoded = self.pictures_decoded;
992 let mut emit_seq = self.emit_seq;
993 let mut in_flight_decodes = self.in_flight_decodes;
994 let mut in_flight_shows = self.in_flight_shows;
995 let mut order_hint_slots = self.order_hint_slots;
996 let mut slot_owner = self.slot_owner;
997 let mut reorder = std::mem::take(&mut self.reorder);
998 let mut pending_header = self.pending_header.take();
999 let mut pending_tiles = std::mem::take(&mut self.pending_tiles);
1000 let threads = self.threads;
1001 let StreamDecoder {
1002 final_dump,
1003 parser,
1004 ref_slots,
1005 motion_field_slots,
1006 cdf_slots,
1007 seg_map_slots,
1008 tx,
1009 rx,
1010 slot_promises,
1011 fctx,
1012 ..
1013 } = self;
1014 // lane-pool1: this replaced a `std::thread::scope` -- frame workers now
1015 // come from a persistent pool (one per submitting thread, workers reused
1016 // across frames, so their `thread_local!` decode scratch survives the
1017 // frame). `jobs` is declared here and dropped at the end of the function,
1018 // including on `?`, so no job outlives the data it borrows.
1019 let jobs = crate::par::Batch::new("ec-av1-frame");
1020 // lane-av1recon: at more than one decode thread the recon wavefront and
1021 // the filter bands default on (an explicit env value still wins).
1022 let _split = crate::par::DecodeSplit::install(threads);
1023 let in_flight_cap = threads + 2;
1024 let mut pos = 0usize;
1025 while pos < data.len() {
1026 let obu = parser.parse_obu(&data[pos..])?;
1027 let obu_offset = pos;
1028 pos += obu.total_size;
1029
1030 if let ObuKind::FrameHeader(header) = &obu.kind {
1031 if !header.show_existing_frame {
1032 // Before this fix, this branch fired unconditionally for
1033 // EVERY `FrameHeader` OBU (including this one), so a
1034 // standalone header always fell into the `show_existing_frame`
1035 // slot lookup below and misreported "a show_existing_frame
1036 // header naming an empty reference slot" for a frame that was
1037 // never a show_existing_frame header at all.
1038 pending_header = Some(header.clone());
1039 pending_tiles = Vec::new();
1040 continue;
1041 }
1042 // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
1043 // OBU only names a DPB slot to output again -- the coded-frame
1044 // count and the shown-picture count are different things (a
1045 // hidden altref's own `Frame` OBU below is never pushed to
1046 // `pictures` on its own; it is only pushed here, later, when a
1047 // `show_existing_frame` header names its slot). Before r15 this
1048 // arm didn't exist at all: every `ObuKind::Frame` was pushed
1049 // unconditionally regardless of `show_frame`, so a hidden altref
1050 // was emitted (wrongly, in decode order) and its real
1051 // `show_existing_frame` output was silently dropped.
1052 let slot = header.frame_to_show_map_idx as usize;
1053 // lane-hdrlossless: libaom errors on the same stream
1054 // (`decodeframe.c:4651`: `if (frame_to_show == NULL)
1055 // aom_internal_error(... AOM_CODEC_UNSUP_BITSTREAM, "Buffer does
1056 // not contain a decoded frame")`) -- a spec-conformant guard.
1057 let empty_slot = || {
1058 Error::unsupported(
1059 "AV1 decode_stream",
1060 "a show_existing_frame header naming an empty reference slot",
1061 )
1062 };
1063 if threads > 1 {
1064 // lane-thread3: the named slot may still be decoding on a
1065 // worker, and the copy into the slots this header refreshes
1066 // is then just the promise -- no value needed. The OUTPUT
1067 // does need the picture, so it is produced on a worker too:
1068 // waiting for it here would stall the parsing thread, and a
1069 // stalled parser dispatches nothing (measured before this
1070 // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of
1071 // 23.3 s at 4K, spent in this one wait). The wait still
1072 // points at an earlier coded frame, so the argument in
1073 // [`SlotPromise`] is unchanged.
1074 let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?;
1075 for i in 0..NUM_REF_FRAMES {
1076 if header.refresh_frame_flags & (1 << i) != 0 {
1077 slot_promises[i] = Some(promise.clone());
1078 slot_owner[i] = slot_owner[slot];
1079 }
1080 }
1081 let cap_t0 = crate::timeline::now();
1082 let capped = in_flight_shows >= in_flight_cap;
1083 while in_flight_shows >= in_flight_cap {
1084 collect_one(
1085 &rx,
1086 &mut in_flight_decodes,
1087 &mut in_flight_shows,
1088 &mut reorder,
1089 &mut sink,
1090 )?;
1091 }
1092 if capped {
1093 crate::timeline::cap_wait("show", cap_t0, crate::timeline::now());
1094 }
1095 let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
1096 emit_seq += 1;
1097 pictures_shown += 1;
1098 let grain = header.film_grain;
1099 let seq = SeqFlags::read(&parser);
1100 let tx = tx.clone();
1101 jobs.submit(move || {
1102 let mut answer = JobAnswer::new(tx, job_seq, false, None, None);
1103 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1104 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1105 let value = promise.wait()?;
1106 let shown_picture = value.pixels.wait()?;
1107 let output = if grain.apply_grain && !no_grain() {
1108 std::sync::Arc::new(crate::film_grain::apply_grain(
1109 &shown_picture,
1110 &grain,
1111 seq.mc_identity,
1112 u32::from(seq.bit_depth),
1113 &crate::decode::FrameCtx::new(),
1114 ))
1115 } else {
1116 std::sync::Arc::clone(&shown_picture)
1117 };
1118 Ok((output, decode_idx, true))
1119 }))
1120 .unwrap_or_else(|_| {
1121 Err(Error::corrupt(
1122 "AV1 decode_stream: a worker thread panicked on a show_existing_frame output",
1123 ))
1124 });
1125 answer.send(reply);
1126 }));
1127 });
1128 in_flight_shows += 1;
1129 while let Ok((seq, decode_job, result)) = rx.try_recv() {
1130 if decode_job {
1131 in_flight_decodes -= 1;
1132 } else {
1133 in_flight_shows -= 1;
1134 }
1135 let (picture, decode_idx, shown) = result?;
1136 reorder.push(seq, picture, decode_idx, shown);
1137 reorder.drain(&mut sink)?;
1138 }
1139 continue;
1140 }
1141 let picture = {
1142 let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?;
1143 for i in 0..NUM_REF_FRAMES {
1144 if header.refresh_frame_flags & (1 << i) != 0 {
1145 cdf_slots[i] = cdf_slots[slot].clone();
1146 ref_slots[i] = Some(picture.clone());
1147 motion_field_slots[i] = motion_field_slots[slot].clone();
1148 seg_map_slots[i] = seg_map_slots[slot].clone();
1149 order_hint_slots[i] = order_hint_slots[slot];
1150 }
1151 }
1152 picture
1153 };
1154 let output = if header.film_grain.apply_grain && !no_grain() {
1155 // lane-hbd10 r1: grain synthesis is bit-depth generic
1156 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
1157 let bit_depth = parser
1158 .sequence_header()
1159 .map_or(8, |seq| seq.color_config.bit_depth);
1160 let mc_identity = parser
1161 .sequence_header()
1162 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
1163 std::sync::Arc::new(crate::film_grain::apply_grain(
1164 &picture,
1165 &header.film_grain,
1166 mc_identity,
1167 bit_depth as u32,
1168 fctx,
1169 ))
1170 } else {
1171 picture
1172 };
1173 reorder.push(emit_seq, output, pictures_decoded, true);
1174 emit_seq += 1;
1175 reorder.drain(&mut sink)?;
1176 pictures_shown += 1;
1177 continue;
1178 }
1179 // `tiles_base_offset` is added to every `Tile::offset` below to reach
1180 // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to
1181 // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s
1182 // may span several different OBUs (each at a different offset in
1183 // `data`), so those tiles are normalised to an absolute offset the
1184 // moment they are appended to `pending_tiles`, and `tiles_base_offset`
1185 // is 0 for that case.
1186 let (header, tiles, tiles_base_offset): (Box<FrameHeader>, Vec<Tile>, usize) =
1187 match obu.kind {
1188 ObuKind::Frame(header, tiles) => (header, tiles, obu_offset),
1189 ObuKind::TileGroup(new_tiles) => {
1190 let header = pending_header.clone().ok_or_else(|| {
1191 Error::corrupt(
1192 "AV1 decode_stream: a tile group OBU with no preceding frame header",
1193 )
1194 })?;
1195 let expected = header.tile_info.cols * header.tile_info.rows;
1196 pending_tiles.extend(new_tiles.into_iter().map(|mut t| {
1197 t.offset += obu_offset;
1198 t
1199 }));
1200 if (pending_tiles.len() as u32) < expected {
1201 continue;
1202 }
1203 pending_header = None;
1204 (header, std::mem::take(&mut pending_tiles), 0)
1205 }
1206 _ => continue,
1207 };
1208 // Every tile is decoded below through `tile_bufs`; this only rejects a
1209 // frame OBU that carries no tile group at all.
1210 if tiles.is_empty() {
1211 return Err(Error::unsupported(
1212 "AV1 decode_stream",
1213 "a frame OBU with no tile group",
1214 ));
1215 }
1216 // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
1217 // block of each 64x64) only reads a literal `cdef_idx` when
1218 // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a
1219 // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is
1220 // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into
1221 // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so
1222 // a `cdef_bits > 0` stream no longer needs this refusal.
1223 // Both frame types now read their transform size under
1224 // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads
1225 // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's
1226 // `decode_inter_block`/`decode_inter_block8` read the recursive
1227 // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the
1228 // blanket inter-frame refusal that used to stand here is gone. What
1229 // remains refused is named at its own site in `read_block_tx_size`.
1230 // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
1231 // libaom decodemv.c): three more per-block/per-SB symbols this crate
1232 // never reads at all, each gated by a header field this decoder
1233 // otherwise accepts uncomplaining -- the same silent-desync shape
1234 // `use_filter_intra` was. `allow_screen_content_tools` gates both
1235 // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
1236 // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
1237 // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
1238 // before desyncing rather than silently miscode, the same pattern as
1239 // the CDEF/TxMode::Select refusals above.
1240 // lane-screen r2: key frames consume (not reconstruct) palette/
1241 // intrabc syntax via read_intra_mode, and decode_inter_block/
1242 // decode_inter_block8's own intra-sub-block branches now consume
1243 // palette the same way (libaom's read_intra_block_mode_info has no
1244 // intrabc call at all -- that symbol is intra-frame-only). A
1245 // genuine palette/intrabc use still refuses by name deeper in the
1246 // block readers, so no whole-frame refusal is needed here anymore.
1247 // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX)
1248 // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF ->
1249 // Neighbours::delta_lf_grid -> lf_level) are now read and applied;
1250 // no whole-frame refusal needed here anymore.
1251 //
1252 // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an
1253 // earlier round), `BIT_DEPTH` is wired from this frame's own sequence
1254 // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10`
1255 // stream decodes pixel-exact against ffmpeg's own decode of the same
1256 // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The
1257 // blanket refusal that used to be here is gone; `film_grain.rs` and
1258 // `superres.rs` still refuse narrowly by name (their own hardcoded
1259 // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
1260 // will show up as a real pixel mismatch, not a silent truncation --
1261 // the whole reason the widen (and this wiring) happened.
1262 // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9,
1263 // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the
1264 // per-segment quantizer (spec 7.12.2) and loop-filter level
1265 // (spec 7.14.4). The three features that instead REWRITE a block's
1266 // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the
1267 // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress
1268 // symbols `decode_inter_block` unconditionally reads) -- have no
1269 // reader on the inter path, so they still refuse by name rather than
1270 // desyncing. aomenc's `--aq-mode` segmentation only ever sets
1271 // `SEG_LVL_ALT_Q` (census gate
1272 // `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`:
1273 // 1-pass, alt-ref-lag and two-pass arms, every frame header parsed).
1274 let tile_bufs: Vec<&[u8]> = tiles
1275 .iter()
1276 .map(|t| {
1277 data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size)
1278 .ok_or(Error::NeedMore)
1279 })
1280 .collect::<Result<_>>()?;
1281 let seq = SeqFlags::read(&parser);
1282 // lane-thread3: at `threads > 1` every coded frame that is not a key
1283 // frame is decoded on a worker -- frames that refresh reference slots
1284 // included, which on a pyramid stream is nearly all of them. Its
1285 // inputs are taken as promises and its output is published as one,
1286 // installed into the slots it refreshes HERE, on the parsing thread,
1287 // in decode order, so the next frame's dependencies are known without
1288 // waiting for this one to finish (see [`SlotPromise`] for the
1289 // deadlock argument). A key frame stays inline: it resets the whole
1290 // bank and reads nothing, so there is nothing to gain.
1291 if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
1292 let cap_t0 = crate::timeline::now();
1293 let capped = in_flight_decodes >= in_flight_cap;
1294 while in_flight_decodes >= in_flight_cap {
1295 collect_one(
1296 &rx,
1297 &mut in_flight_decodes,
1298 &mut in_flight_shows,
1299 &mut reorder,
1300 &mut sink,
1301 )?;
1302 }
1303 if capped {
1304 crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now());
1305 }
1306 // Exactly the slots this frame reads: `ref_frame_idx` names its
1307 // references, and its `primary_ref_frame` CDFs/segment map, its
1308 // reference order hints and every field `setup_motion_field`
1309 // projects all come from those same slots. Nothing else is
1310 // waited on.
1311 let mut deps: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
1312 std::array::from_fn(|_| None);
1313 for i in 0..7 {
1314 let slot = header.ref_frame_idx[i] as usize;
1315 deps[slot] = slot_promises[slot].clone();
1316 }
1317 let dep_owner = slot_owner;
1318 let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending);
1319 if let Some(promise) = &produces {
1320 for i in 0..NUM_REF_FRAMES {
1321 if header.refresh_frame_flags & (1 << i) != 0 {
1322 slot_promises[i] = Some(promise.clone());
1323 slot_owner[i] = pictures_decoded;
1324 }
1325 }
1326 }
1327 let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);
1328 emit_seq += 1;
1329 pictures_decoded += 1;
1330 let shown = header.show_frame;
1331 if shown {
1332 pictures_shown += 1;
1333 }
1334 let tx = tx.clone();
1335 let dump = final_dump.clone();
1336 crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);
1337 // The job outlives this call, so it owns its tile bytes (a copy of
1338 // this frame's compressed tiles) instead of borrowing `data`.
1339 let owned_tiles: Vec<Vec<u8>> = tile_bufs.iter().map(|t| t.to_vec()).collect();
1340 jobs.submit(move || {
1341 let tile_views: Vec<&[u8]> = owned_tiles.iter().map(Vec::as_slice).collect();
1342 let promise = produces;
1343 // lane-twostage: stage 2 -- this frame's filtered pixels. Its
1344 // consumers hold this promise from the moment stage 1 (CDFs,
1345 // segment map, motion field, size) is published at the tile
1346 // boundary, and wait on it at their first prediction.
1347 let pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>> =
1348 SlotPromise::pending();
1349 let mut answer = JobAnswer::new(
1350 tx,
1351 job_seq,
1352 true,
1353 promise.clone(),
1354 Some(pixels.clone()),
1355 );
1356 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1357 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1358 crate::fault::point("frame");
1359 crate::timeline::start(decode_idx);
1360 // The wait happens HERE, off the parsing thread, and only
1361 // for this frame's own references.
1362 let mut resolved: [Option<std::sync::Arc<SlotValue>>; NUM_REF_FRAMES] =
1363 std::array::from_fn(|_| None);
1364 for (slot, dep) in deps.iter().enumerate() {
1365 if let Some(dep) = dep {
1366 let t0 = crate::timeline::now();
1367 resolved[slot] = Some(dep.wait()?);
1368 crate::timeline::ref_wait(
1369 decode_idx,
1370 slot,
1371 dep_owner[slot],
1372 crate::timeline::now().saturating_sub(t0),
1373 );
1374 }
1375 }
1376 crate::timeline::refs_ready();
1377 // Fresh per-thread state: every field this path reads is
1378 // written from this frame's own header before it is read.
1379 let fctx = crate::decode::FrameCtx::new();
1380 // lane-twostage: the pictures behind this frame's own
1381 // references, waited for at the first `ref_planes` call
1382 // inside the tile decode rather than here.
1383 let ref_metas: [Option<std::sync::Arc<SlotValue>>; 8] =
1384 std::array::from_fn(|i| {
1385 if i == 0 {
1386 None
1387 } else {
1388 resolved
1389 .get(header.ref_frame_idx[i - 1] as usize)
1390 .cloned()
1391 .flatten()
1392 }
1393 });
1394 let pix_cell: std::sync::OnceLock<
1395 [Option<std::sync::Arc<Picture>>; 8],
1396 > = std::sync::OnceLock::new();
1397 let wait_pixels = || -> Result<[Option<&Picture>; 8]> {
1398 if pix_cell.get().is_none() {
1399 let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
1400 Default::default();
1401 for (i, meta) in ref_metas.iter().enumerate() {
1402 if let Some(meta) = meta {
1403 let slot = header.ref_frame_idx[i - 1] as usize;
1404 let t0 = crate::timeline::now();
1405 pics[i] = Some(meta.pixels.wait()?);
1406 crate::timeline::ref_wait(
1407 decode_idx,
1408 slot,
1409 dep_owner[slot],
1410 crate::timeline::now().saturating_sub(t0),
1411 );
1412 }
1413 }
1414 let _ = pix_cell.set(pics);
1415 }
1416 let pics = pix_cell.get().expect("the pictures were just set");
1417 Ok(std::array::from_fn(|i| pics[i].as_deref()))
1418 };
1419 let ref_dims: [Option<(usize, usize)>; 8] =
1420 std::array::from_fn(|i| {
1421 ref_metas[i].as_ref().map(|m| (m.width, m.height))
1422 });
1423 // The same references for the recon workers, which wait
1424 // for the pictures themselves (off the parse thread).
1425 let shared_refs = {
1426 let metas = ref_metas.clone();
1427 let ref_idx = header.ref_frame_idx;
1428 let owners = dep_owner;
1429 decode::SharedRefs {
1430 dims: ref_dims,
1431 wait: std::sync::Arc::new(move || {
1432 let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
1433 Default::default();
1434 for (i, meta) in metas.iter().enumerate() {
1435 if let Some(meta) = meta {
1436 let slot = ref_idx[i - 1] as usize;
1437 let t0 = crate::timeline::now();
1438 pics[i] = Some(meta.pixels.wait()?);
1439 crate::timeline::ref_wait(
1440 decode_idx,
1441 slot,
1442 owners[slot],
1443 crate::timeline::now().saturating_sub(t0),
1444 );
1445 }
1446 }
1447 Ok(pics)
1448 }),
1449 }
1450 };
1451 let refpix =
1452 decode::RefPix::lazy(ref_dims, &wait_pixels, Some(shared_refs));
1453 // Stage 1: published at this frame's tile boundary, before
1454 // its filters run (`take_segment_ids` copies the map, so
1455 // the filters that read it are unaffected).
1456 let stage1 = |cdfs: Cdfs,
1457 motion_field: crate::motion_field::MotionField,
1458 width: usize,
1459 height: usize| {
1460 if let Some(promise) = &promise {
1461 promise.fulfil(std::sync::Arc::new(SlotValue {
1462 pixels: pixels.clone(),
1463 width,
1464 height,
1465 cdfs,
1466 motion_field,
1467 seg_map: decode::take_segment_ids(&fctx),
1468 order_hint: header.order_hint,
1469 }));
1470 crate::timeline::slot_fulfil();
1471 }
1472 };
1473 // spec 7.9's `av1_setup_motion_field` runs inside
1474 // `RefSnapshot::take`, i.e. here, after those waits --
1475 // it reads the referenced slots' saved motion fields.
1476 let motion_fields =
1477 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field));
1478 let snap = RefSnapshot::take(
1479 &header,
1480 seq,
1481 &refpix,
1482 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),
1483 std::array::from_fn(|i| {
1484 resolved[i].as_ref().map(|v| v.seg_map.as_slice())
1485 }),
1486 &motion_fields,
1487 std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)),
1488 );
1489 let out = decode_frame(
1490 &fctx,
1491 &header,
1492 &tile_views,
1493 seq,
1494 snap,
1495 decode_idx,
1496 shown_idx,
1497 dump.as_deref(),
1498 // lane-twostage publishes a frame's meta at its tile
1499 // boundary instead of after its filters, so a consumer
1500 // parses over its producer's filter tail. It is ON by
1501 // default since lane-sub8group: with every reference
1502 // pixel read deferred to the recon workers, the
1503 // consumer parses its WHOLE tile before it needs a
1504 // pixel, and the 4K critical chain shortens by 11-14%
1505 // in three interleaved pairs (14450/10594/14407 ms off
1506 // vs 12790/9207/12463 ms on) where it moved 3-7%
1507 // before. `EC_AV1_TWO_STAGE=0` turns it back off.
1508 (crate::envflags::var("EC_AV1_TWO_STAGE").as_deref() != Ok("0"))
1509 .then_some(&stage1 as &dyn Fn(_, _, _, _)),
1510 )?;
1511 // Publish before grain synthesis: every frame waiting on
1512 // this slot can start the moment the clean picture exists
1513 // (spec 7.18.3.1 -- the bank never stores grain).
1514 let picture = std::sync::Arc::new(out.picture);
1515 pixels.fulfil(picture.clone());
1516 if let Some(promise) = &promise {
1517 // Only a frame whose stage-1 sink never fired (a
1518 // superres frame) still has meta to publish here.
1519 promise.fulfil_if_pending(|| {
1520 std::sync::Arc::new(SlotValue {
1521 pixels: pixels.clone(),
1522 width: picture.width,
1523 height: picture.height,
1524 cdfs: out.stored_cdfs,
1525 motion_field: out.motion_field.expect(
1526 "a frame that published no stage 1 carries its motion field back",
1527 ),
1528 seg_map: out.seg_map,
1529 order_hint: header.order_hint,
1530 })
1531 });
1532 crate::timeline::slot_fulfil();
1533 }
1534 // Grain is synthesised for OUTPUT only: a hidden frame is
1535 // reported to the sink clean, exactly as the inline path
1536 // below reports it (spec 7.18.3.1).
1537 let output = if shown && header.film_grain.apply_grain && !no_grain() {
1538 std::sync::Arc::new(crate::film_grain::apply_grain(
1539 &picture,
1540 &header.film_grain,
1541 seq.mc_identity,
1542 u32::from(seq.bit_depth),
1543 &fctx,
1544 ))
1545 } else {
1546 picture
1547 };
1548 crate::timeline::grain_done();
1549 Ok((output, decode_idx, shown))
1550 }))
1551 .unwrap_or_else(|_| {
1552 Err(Error::corrupt(
1553 "AV1 decode_stream: a worker thread panicked decoding a frame",
1554 ))
1555 });
1556 crate::fault::point("frame-after");
1557 answer.send(reply);
1558 }));
1559 });
1560 in_flight_decodes += 1;
1561 FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1562 // Anything that finished while this frame was being set up.
1563 while let Ok((seq, decode_job, result)) = rx.try_recv() {
1564 if decode_job {
1565 in_flight_decodes -= 1;
1566 } else {
1567 in_flight_shows -= 1;
1568 }
1569 let (picture, decode_idx, shown) = result?;
1570 reorder.push(seq, picture, decode_idx, shown);
1571 reorder.drain(&mut sink)?;
1572 }
1573 continue;
1574 }
1575 // lane-twostage: the inline path's references are decoded already,
1576 // so its handle never waits.
1577 let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| {
1578 if i == 0 {
1579 None
1580 } else {
1581 ref_slots
1582 .get(header.ref_frame_idx[i - 1] as usize)
1583 .and_then(|p| p.as_deref())
1584 }
1585 }));
1586 let snap = RefSnapshot::take(
1587 &header,
1588 seq,
1589 &inline_refpix,
1590 std::array::from_fn(|i| cdf_slots[i].as_ref()),
1591 std::array::from_fn(|i| seg_map_slots[i].as_deref()),
1592 &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
1593 order_hint_slots,
1594 );
1595 let bit_depth = seq.bit_depth;
1596 let FrameOutput {
1597 picture,
1598 stored_cdfs,
1599 motion_field,
1600 seg_map: decoded_seg_map,
1601 } = decode_frame(
1602 fctx,
1603 &header,
1604 &tile_bufs,
1605 seq,
1606 snap,
1607 pictures_decoded,
1608 pictures_shown,
1609 final_dump.as_deref(),
1610 None,
1611 )?;
1612 let motion_field = motion_field.expect("the inline path passes no stage-1 sink");
1613 pictures_decoded += 1;
1614 // lane-pool1: one allocation, then every slot store and the output
1615 // itself are refcount bumps instead of plane copies.
1616 let picture = std::sync::Arc::new(picture);
1617 if threads > 1 {
1618 // lane-thread3: only a key frame reaches this inline path at
1619 // `threads > 1`, and the bank it fills is the promise array --
1620 // already resolved, since the picture exists right here.
1621 if header.refresh_frame_flags != 0 {
1622 let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
1623 pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)),
1624 width: picture.width,
1625 height: picture.height,
1626 cdfs: stored_cdfs,
1627 motion_field,
1628 seg_map: decoded_seg_map,
1629 order_hint: header.order_hint,
1630 }));
1631 for i in 0..NUM_REF_FRAMES {
1632 if header.refresh_frame_flags & (1 << i) != 0 {
1633 slot_promises[i] = Some(promise.clone());
1634 slot_owner[i] = pictures_decoded - 1;
1635 }
1636 }
1637 }
1638 } else {
1639 for i in 0..NUM_REF_FRAMES {
1640 if header.refresh_frame_flags & (1 << i) != 0 {
1641 cdf_slots[i] = Some(stored_cdfs.clone());
1642 // Spec 7.18.3.1: synthesized grain is never stored for
1643 // later prediction -- the reference bank always keeps the
1644 // clean, pre-grain decode, even though the frame pushed
1645 // onto the caller's output below carries the grained
1646 // picture.
1647 ref_slots[i] = Some(std::sync::Arc::clone(&picture));
1648 motion_field_slots[i] = Some(motion_field.clone());
1649 seg_map_slots[i] = Some(decoded_seg_map.clone());
1650 order_hint_slots[i] = header.order_hint;
1651 }
1652 }
1653 }
1654 // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a
1655 // KEY frame coded with `show_frame == 0`, output later by a
1656 // `show_existing_frame` header -- counted only once its tiles have
1657 // decoded, so the gate's assert covers decoded-and-compared frames.
1658 if header.frame_type == FrameType::Key && !header.show_frame {
1659 decode::note_fwd_kf();
1660 }
1661 if header.show_frame {
1662 let output = if header.film_grain.apply_grain && !no_grain() {
1663 let mc_identity = seq.mc_identity;
1664 std::sync::Arc::new(crate::film_grain::apply_grain(
1665 &picture,
1666 &header.film_grain,
1667 mc_identity,
1668 bit_depth as u32,
1669 fctx,
1670 ))
1671 } else {
1672 picture
1673 };
1674 reorder.push(emit_seq, output, pictures_decoded - 1, true);
1675 emit_seq += 1;
1676 reorder.drain(&mut sink)?;
1677 pictures_shown += 1;
1678 } else {
1679 // Hidden (alt-ref/forward-key) frames never reach
1680 // `decode_stream`'s output, but a decode-order consumer -- the
1681 // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs
1682 // them, so they are reported too, with `shown == false`.
1683 reorder.push(emit_seq, picture, pictures_decoded - 1, false);
1684 emit_seq += 1;
1685 reorder.drain(&mut sink)?;
1686 }
1687 }
1688 while in_flight_decodes + in_flight_shows > 0 {
1689 collect_one(
1690 &rx,
1691 &mut in_flight_decodes,
1692 &mut in_flight_shows,
1693 &mut reorder,
1694 &mut sink,
1695 )?;
1696 }
1697 self.pictures_shown = pictures_shown;
1698 self.pictures_decoded = pictures_decoded;
1699 self.emit_seq = emit_seq;
1700 self.in_flight_decodes = in_flight_decodes;
1701 self.in_flight_shows = in_flight_shows;
1702 self.order_hint_slots = order_hint_slots;
1703 self.slot_owner = slot_owner;
1704 self.reorder = reorder;
1705 self.pending_header = pending_header;
1706 self.pending_tiles = pending_tiles;
1707 Ok(())
1708 }
1709}
1710
1711/// [`decode_stream_with`] with an explicit worker count (lane-thread2).
1712///
1713/// `threads == 1` is the serial decoder. Above that, frames that no later
1714/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags`
1715/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads
1716/// while the main thread keeps parsing headers and decoding the frames that
1717/// DO feed the reference banks; `sink` still sees every picture in coded
1718/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot
1719/// of the banks taken before dispatch, so no decode state is shared.
1720///
1721/// The per-decode counters this crate's gates read are thread-local, so at
1722/// `threads > 1` a leaf frame's counts land on the worker and are invisible
1723/// to the caller; that is why the default is 1.
1724///
1725/// # Errors
1726/// As [`decode_stream_with`]; a worker's error aborts the stream.
1727pub fn decode_stream_with_threads(
1728 data: &[u8],
1729 threads: usize,
1730 sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
1731) -> Result<()> {
1732 let mut decoder = StreamDecoder::new(threads);
1733 decoder.decode(data, sink)?;
1734 debug_assert!(
1735 decoder.reorder.pending.is_empty(),
1736 "a frame was never emitted"
1737 );
1738 crate::timeline::dump();
1739 Ok(())
1740}
1741
1742/// lane-thread2: the sequence-header bits a single frame's decode needs,
1743/// read once on the parsing thread so that [`decode_frame`] never touches the
1744/// [`Av1Parser`] (a worker thread has no access to it).
1745#[derive(Clone, Copy)]
1746pub(crate) struct SeqFlags {
1747 pub(crate) enable_filter_intra: bool,
1748 pub(crate) enable_dual_filter: bool,
1749 pub(crate) enable_edge_filter: bool,
1750 pub(crate) enable_masked_compound: bool,
1751 pub(crate) enable_jnt_comp: bool,
1752 pub(crate) enable_interintra_compound: bool,
1753 pub(crate) use_sb128: bool,
1754 pub(crate) bit_depth: u8,
1755 /// lane-av1mono: `color_config.mono_chrome` (spec 5.5.2):
1756 /// `NumPlanes == 1`, no chroma is coded or reconstructed.
1757 pub(crate) mono_chrome: bool,
1758 pub(crate) order_hint_bits: u32,
1759 pub(crate) mc_identity: bool,
1760 /// lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2). These used
1761 /// to exist only for the sequence-level refusal -- the decoder hardcoded
1762 /// 4:2:0 at every chroma extent. lane-av1422lift: that is no longer true
1763 /// and these are load-bearing on the DECODE path: `decode_stream_with`
1764 /// publishes both through `decode::set_subsampling` into `FrameCtx`, and
1765 /// every chroma extent, plane allocation, output crop, deblock/CDEF crop
1766 /// and restoration grid below reads them PER AXIS. A monochrome header
1767 /// parses as 1,1 and is unaffected. The only shape these cannot carry is
1768 /// (0,1) 4:4:0, which the header cannot code.
1769 pub(crate) subsampling_x: u8,
1770 pub(crate) subsampling_y: u8,
1771}
1772
1773impl SeqFlags {
1774 fn read(parser: &Av1Parser) -> Self {
1775 let seq = parser.sequence_header();
1776 Self {
1777 enable_filter_intra: seq.is_some_and(|s| s.enable_filter_intra),
1778 enable_dual_filter: seq.is_some_and(|s| s.enable_dual_filter),
1779 enable_edge_filter: seq.is_some_and(|s| s.enable_intra_edge_filter),
1780 enable_masked_compound: seq.is_some_and(|s| s.enable_masked_compound),
1781 enable_jnt_comp: seq.is_some_and(|s| s.enable_jnt_comp),
1782 enable_interintra_compound: seq.is_some_and(|s| s.enable_interintra_compound),
1783 use_sb128: seq.is_some_and(|s| s.use_128x128_superblock),
1784 bit_depth: seq.map_or(8, |s| s.color_config.bit_depth),
1785 mono_chrome: seq.is_some_and(|s| s.color_config.mono_chrome),
1786 order_hint_bits: seq.map_or(0, |s| s.order_hint_bits),
1787 mc_identity: seq.is_some_and(|s| s.color_config.matrix_coefficients == 0),
1788 subsampling_x: seq.map_or(1, |s| s.color_config.subsampling_x),
1789 subsampling_y: seq.map_or(1, |s| s.color_config.subsampling_y),
1790 }
1791 }
1792}
1793
1794/// lane-thread2: everything one frame's decode reads out of the cross-frame
1795/// banks `decode_stream_with` owns -- taken on the parsing thread, before any
1796/// later frame can overwrite a slot, so a frame can be decoded anywhere.
1797pub(crate) struct RefSnapshot<'a> {
1798 /// lane-twostage: this frame's references, indexed by `ref_frame`
1799 /// (`LAST_FRAME` = 1) -- sizes now, pixels at the first prediction.
1800 pub(crate) refpix: &'a decode::RefPix<'a>,
1801 /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame
1802 /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the
1803 /// second case is the refusal [`decode_frame`] raises where it always
1804 /// did, so the error order over a malformed stream is unchanged).
1805 pub(crate) primary_cdfs: Option<Cdfs>,
1806 /// Spec `load_previous_segment_ids`, from the same slot.
1807 pub(crate) prev_seg_map: Option<Vec<u8>>,
1808 /// Spec 7.9's projection, already run against `motion_field_slots`.
1809 pub(crate) tpl_field: Option<crate::motion_field::TplField>,
1810 /// `order_hint_slots[ref_frame_idx[i]]` for `LAST_FRAME + i`.
1811 pub(crate) ref_order_hints: [u32; 7],
1812}
1813
1814impl<'a> RefSnapshot<'a> {
1815 /// Reads the banks for `header`. Every slot is passed in by reference so
1816 /// that the single-threaded path can borrow the DPB in place while a
1817 /// worker borrows the resolved [`SlotPromise`] values it waited on --
1818 /// spec 7.9's `setup_motion_field` therefore runs on the DECODING thread
1819 /// (lane-thread3), after those waits.
1820 fn take(
1821 header: &FrameHeader,
1822 seq: SeqFlags,
1823 refpix: &'a decode::RefPix<'a>,
1824 cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],
1825 seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],
1826 motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],
1827 order_hint_slots: [u32; NUM_REF_FRAMES],
1828 ) -> Self {
1829 let primary = (header.primary_ref_frame != PRIMARY_REF_NONE)
1830 .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize);
1831 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1832 // this frame's header asks for it, and never for a key frame (which
1833 // codes no inter block at all).
1834 let tpl_field =
1835 (header.frame_type != FrameType::Key && header.use_ref_frame_mvs).then(|| {
1836 crate::motion_field::setup_motion_field(
1837 motion_field_slots,
1838 header.ref_frame_idx,
1839 header.order_hint,
1840 seq.order_hint_bits,
1841 header.mi_rows as usize,
1842 header.mi_cols as usize,
1843 )
1844 });
1845 if std::env::var_os("EC_TPL").is_some() {
1846 eprintln!(
1847 "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}",
1848 header.order_hint,
1849 header.use_ref_frame_mvs,
1850 tpl_field
1851 .as_ref()
1852 .map_or(0, crate::motion_field::TplField::filled_cells)
1853 );
1854 }
1855 Self {
1856 refpix,
1857 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
1858 prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),
1859 tpl_field,
1860 ref_order_hints: std::array::from_fn(|i| {
1861 order_hint_slots[header.ref_frame_idx[i] as usize]
1862 }),
1863 }
1864 }
1865}
1866
1867/// lane-thread2: what one decoded frame contributes back to the stream --
1868/// its picture (clean, pre-grain: spec 7.18.3.1) plus the three pieces a
1869/// `refresh_frame_flags` bit stores into a reference slot.
1870pub(crate) struct FrameOutput {
1871 pub(crate) picture: Picture,
1872 pub(crate) stored_cdfs: Cdfs,
1873 /// lane-twostage: `None` when this frame handed its motion field to the
1874 /// stage-1 sink at its tile boundary instead of carrying it back here.
1875 pub(crate) motion_field: Option<crate::motion_field::MotionField>,
1876 pub(crate) seg_map: Vec<u8>,
1877}
1878
1879/// Spec 7.20's own `save_cdfs`: what a frame's `refresh_frame_flags` slots
1880/// keep -- the frame's INITIAL table when `disable_frame_end_update_cdf`,
1881/// otherwise the adapted end-of-tile table with every symbol counter zeroed
1882/// (libaom `av1_reset_cdf_symbol_counters`). lane-twostage: shared with the
1883/// stage-1 publish, which hands a consumer the same table it always got.
1884fn stored_cdfs_for(header: &FrameHeader, end_cdfs: Cdfs, started_from: Option<Cdfs>) -> Cdfs {
1885 if header.disable_frame_end_update_cdf {
1886 started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
1887 } else {
1888 let mut end_cdfs = end_cdfs;
1889 end_cdfs.reset_counts();
1890 end_cdfs
1891 }
1892}
1893
1894/// lane-thread2: one coded frame, decoded from its header, its tile payload
1895/// and a snapshot of the reference banks -- and from nothing else. Lifted
1896/// verbatim out of [`decode_stream_with`]'s loop so that the same code can
1897/// run on the parsing thread (a frame that refreshes a reference slot) or on
1898/// a worker (a leaf frame, see `decode_stream_with_threads`).
1899///
1900/// `fctx` is the DECODING thread's context: a worker uses a fresh one, which
1901/// is sound because every field this path reads is written by this function
1902/// (or by the tile decoders it calls) before it is read -- see the
1903/// `a_worker_context_starts_where_the_stream_context_would` gate.
1904///
1905/// # Errors
1906/// As [`decode_stream_with`], for this one frame.
1907#[allow(clippy::too_many_arguments)]
1908fn decode_frame(
1909 fctx: &crate::decode::FrameCtx,
1910 header: &FrameHeader,
1911 tile_bufs: &[&[u8]],
1912 seq: SeqFlags,
1913 snap: RefSnapshot<'_>,
1914 decode_idx: usize,
1915 shown_idx: usize,
1916 final_dump: Option<&str>,
1917 // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`.
1918 stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
1919) -> Result<FrameOutput> {
1920 crate::census::frame_start(header, tile_bufs.iter().map(|t| t.len()).sum(), decode_idx);
1921 if header.segmentation.enabled {
1922 // lane-hdrlossless: libaom IMPLEMENTS these three -- they rewrite a
1923 // block's reference / skip / mode BEFORE the symbols are read
1924 // (`decodemv.c:431` SEG_LVL_SKIP, `:437` SEG_LVL_REF_FRAME /
1925 // SEG_LVL_GLOBALMV, `:1071` in `read_ref_frames`, `:1350` in
1926 // `read_is_inter_block`), so a conformant stream CAN carry them and
1927 // this is a capability gap, not a spec-conformant guard. Reachability
1928 // from `aomenc` is nil, for three independent reasons (lane-av1seglvl
1929 // census): the AQ modules clear the table then set `SEG_LVL_ALT_Q`
1930 // only (`aq_variance.c:61` clear + `:89` enable, `aq_complexity.c:74`
1931 // + `:118`, `aq_cyclicrefresh.c:616` + `:630`); the one other setter,
1932 // `configure_static_seg_features` (`encoder_utils.c:315`, which would
1933 // set ALT_LF/REF_FRAME/SKIP around alt-ref groups), is gated on
1934 // `hl_sf.static_segmentation` -- a speed feature libaom's own
1935 // `speed_features.h` documents as "Always set to 0" -- AND on the
1936 // second pass of a two-pass encode (`encoder_utils.c:738`); and
1937 // ROI/active-map maps are control-API only (`av1_apply_roi_map`,
1938 // `av1_apply_active_map`: the CLI exposes no flag for either). Kept as
1939 // a named gap: the lift is an INTER-block-path change (ref/skip/mode
1940 // selection) outside this lane's region. See `lanes/av1hdr.report.md`
1941 // §4.1 and `lanes/av1seglvl.report.md`.
1942 for segment in 0..MAX_SEGMENTS {
1943 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
1944 if header.segmentation.feature_enabled[segment][feature] {
1945 return Err(Error::unsupported(
1946 "AV1 decode_stream",
1947 "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)",
1948 ));
1949 }
1950 }
1951 }
1952 }
1953 // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
1954 // primary reference frame's slot, and is all-zero without one.
1955 decode::set_segmentation(
1956 header.segmentation,
1957 header.mi_rows as usize,
1958 header.mi_cols as usize,
1959 snap.prev_seg_map.as_deref(),
1960 fctx,
1961 );
1962 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
1963 // symbol (spec 7.16's upscaling is a pixel-domain post-process
1964 // libaom's `decodeframe.c` runs between CDEF and loop restoration,
1965 // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile
1966 // reads stay bit-exact in sync and `crate::superres::upscale_picture`
1967 // (below, after decode) makes its `Picture` the spec-correct
1968 // `upscaled_width` instead of silently staying at `frame_width`.
1969 // lane-superres r10: an INTER frame under `use_superres` no longer
1970 // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3)
1971 // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/
1972 // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes
1973 // at the downscaled `frame_width` and upscales its own output the
1974 // same way the key-frame branch above does (see the inter branch
1975 // below). The combinations `predict_scaled` does not cover
1976 // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8
1977 // leaf) still refuse by name, deep in `decode.rs`, rather than
1978 // silently mispredicting -- see `refusal_inventory.rs`.
1979 // Loop restoration carries per-restoration-unit symbols in the tile
1980 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
1981 // superblock walk) -- lane-lr r2 ported the reader
1982 // (`crate::restoration`), r3 moved this refusal check to AFTER the
1983 // tile decode call below (was here, before it, in r2 -- meaning
1984 // `read_lr` was NEVER actually reached through `decode_stream`, the
1985 // gap the r3 gate caught live: 40/40 attempts hit this refusal with
1986 // zero `read_lr_unit` hits). Checking post-decode instead proves the
1987 // superblock walk actually survived `read_lr` (no desync) before
1988 // refusing on the true remaining gap: decoded Wiener/SGR filters are
1989 // stored per unit but never applied to pixels.
1990 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
1991 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
1992 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
1993 // zero vector only under `GmType == IDENTITY` -- any other warp
1994 // model needs the full affine/translation MV derivation this
1995 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
1996 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
1997 // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
1998 // to every one of the 7 single-reference slots `decode_inter_block`
1999 // can now select.
2000 //
2001 // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal
2002 // exposed a real pixel mismatch --
2003 // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact
2004 // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20
2005 // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring
2006 // is not yet provably correct end to end; keeping the refusal
2007 // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and
2008 // root-caused rather than shipping a wrong decode.
2009 //
2010 // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not
2011 // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac
2012 // RANGE at the first divergent block (mi=(8,0), frame 1) matches
2013 // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides),
2014 // and this decoder's own `gm_get_motion_vector` for that block
2015 // (ROTZOOM, seed 43's own header) computes the spec-correct
2016 // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`,
2017 // which found and fixed a real `- 1` omission in `warp.rs` --
2018 // harmless for THIS block's rounding but a genuine spec bug fixed
2019 // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a
2020 // `global_warp_allowed` branch (`warp_types.global_warp_allowed =
2021 // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts
2022 // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8)
2023 // with the FULL per-pixel affine global-motion warp, independent
2024 // of `motion_mode` -- this decoder only ever builds a warp
2025 // prediction for local `WARPED_CAUSAL` motion mode and falls back
2026 // to plain translational MC with the block-centre mv for every
2027 // other GLOBALMV block, which is only a centre-point approximation
2028 // of the true per-pixel warp. That is the entire remaining gap.
2029 // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into
2030 // `crate::warp::global_warp_params` for every single-ref
2031 // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s
2032 // `global_warp_allowed` branch -- ROTZOOM is pin-verified
2033 // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already
2034 // worked (`gm_get_motion_vector`'s translation-only mv, no warp
2035 // needed). AFFINE is untested this round (no aomenc fixture in the
2036 // wedge gate reached a 6-parameter model) -- keep refusing it by
2037 // name rather than shipping an unverified decode.
2038 // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom
2039 // can never write a 6-parameter model -- its encoder-side search is
2040 // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`,
2041 // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) --
2042 // which is why four rounds of `--enable-global-motion=1` recipes
2043 // never reached the case. `scripts/build-aom-affine-oracle.sh` widens
2044 // exactly that search range in a side build, and
2045 // `a_real_affine_global_motion_stream_decodes_pixel_exact` below
2046 // decodes its output pixel-exact against ffmpeg with
2047 // `affine_gm_hits() > 0`, i.e. real blocks predicted through the
2048 // 6-parameter warp. Nothing in the decoder needed changing: the
2049 // header reader already reads params 4/5 with their own subexp refs
2050 // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s
2051 // shear-validity check + `warp_affine` are model-agnostic.
2052 // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two
2053 // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and
2054 // refused the shape by name rather than guess-fix it. r5 localized
2055 // the mismatch to an ordinary NEWMV/GOLDEN block, not the new
2056 // global-warp branch at all -- proving "two active slots" was a
2057 // correlated symptom, not the cause. r6 range-laddered that block
2058 // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after
2059 // mode info -- symbol consumption bit-exact) and found the real
2060 // defect in `mvstack.rs`'s single-reference predictor fallback:
2061 // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real
2062 // neighbour scan left short with this block's OWN global motion
2063 // vector for its ref (`gm_get_motion_vector`), not zero -- invisible
2064 // whenever the live ref's global motion is itself
2065 // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE
2066 // and the querying block's own stack comes up short (frame 14's
2067 // mi=(0,0), the very first block decoded, has no neighbours at
2068 // all). Fixed at the predictor fallback; the refusal above (single
2069 // untested shape: AFFINE on a single-ref frame) stays, but the
2070 // *multi-slot* refusal this comment used to guard is lifted -- the
2071 // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames
2072 // byte-exact with it gone.
2073 // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
2074 // `comp_mode` per block whenever this frame's own `reference_select`
2075 // header bit is set (spec 5.11.25), and refuse by name the blocks
2076 // that pick `COMPOUND_REFERENCE` -- two-reference motion
2077 // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
2078 // is wired at the block level too (forced NEAREST_NEARESTMV compound
2079 // of `skip_mode_frame`, plain average blend), so the old blanket
2080 // `skip_mode_present` refusal is gone.
2081 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
2082 // which tile's end-of-tile adapted CDFs become the frame's own.
2083 // lane-tiles r8: this comment used to claim a `!= 0` refusal existed
2084 // "further down" -- it did not (`decode.rs` reads
2085 // `tile_info.context_update_tile_id` generically at both the
2086 // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites,
2087 // never hardcoded to tile 0); stale documentation, not a real gap.
2088 // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact`
2089 // hard-asserts a live aomenc stream naming tile 1/2/3 decodes
2090 // pixel-exact, so the capability is now proven as well as described
2091 // correctly.
2092 //
2093 // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped,
2094 // not blanket. `decode_key_frame_tile_with_cdfs` and (r6)
2095 // `decode_inter_frame_tile_with_cdfs` both genuinely loop every
2096 // tile, `mvstack.rs`'s `MiGrid` is bounded per tile
2097 // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1`
2098 // origin receives real values at every call site (r6's
2099 // `set_tile_origin` sweep). r7 proved the two remaining
2100 // tile-*column* gaps closed (inter frames, >2 columns with loop
2101 // filtering on). r8 proved tile *rows* the same way: the per-tile
2102 // loop's row math (`tile_num / tile_info.cols`,
2103 // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly
2104 // symmetric with the column path already proven, and
2105 // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact`
2106 // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact.
2107 // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_
2108 // stream` below re-proves it through this entry point. Tile columns
2109 // and tile rows (any count, loop filter on) are no longer capped.
2110 // `Tile::offset` is relative to the buffer `parse_obu` was handed
2111 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
2112 // to `obu_offset`, not to `data` as a whole.
2113 let enable_filter_intra = seq.enable_filter_intra;
2114 let enable_dual_filter = seq.enable_dual_filter;
2115 let enable_edge_filter = seq.enable_edge_filter;
2116 // Inter frames' intra blocks read this through a thread-local that only
2117 // the key-frame tile path used to set; without this call a stream whose
2118 // inter frames are decoded on a thread that previously decoded a
2119 // different sequence would inherit that sequence's bit.
2120 crate::decode::set_enable_edge_filter(enable_edge_filter, fctx);
2121 // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the
2122 // key-frame and the inter tile path read the 128 partition root and
2123 // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and
2124 // libaom's quadrant visit order into the inter loop too). A frame at
2125 // most 64x64 decodes identically either way (its 128 root reads no
2126 // symbol -- neither half is in frame, so SPLIT is inferred), so the
2127 // flag is only armed for frames bigger than one 64x64 superblock.
2128 let use_sb128 = seq.use_sb128;
2129 let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);
2130 crate::decode::set_sb128(sb128_active, fctx);
2131 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
2132 // which every dequant/inverse-transform clamp reads -- set per frame,
2133 // not once per process, for the same cross-sequence-on-one-thread
2134 // reason as `set_enable_edge_filter` above. Defaults to 8 when no
2135 // sequence header has been seen yet, matching every existing fixture.
2136 let bit_depth = seq.bit_depth;
2137 // lane-av112bit: the blanket 12-bit refusal is LIFTED for the paths the
2138 // lane's witnesses prove byte-exact against ffmpeg on real `aomenc
2139 // --bit-depth=12` streams (key frame and inter sequence, CDEF and loop
2140 // restoration ON, grain off -- gates
2141 // `a_real_aomenc_12bit_stream_decodes_pixel_exact` and
2142 // `a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact`). The
2143 // rounding sites that move at 12 bits are parameterised from libaom's
2144 // own rule (`mc.rs`'s `round_pair` -- convolve.h:81..86's `intbufrange`
2145 // delta: round_0 += bd-10, non-compound round_1 -= bd-10; the Wiener
2146 // pair via `get_conv_params_wiener`; the compound post-rounds absorb
2147 // the CONV_BUF gain), and CDEF/deblock/quant tables/SGR/palette reads/
2148 // superres upscale were already bit-depth generic (10-bit-proven).
2149 // Everything no 12-bit witness reached stays refused BY NAME at its own
2150 // site: warp (decode.rs, warp's reduce bits inherit the 12-bit round_0)
2151 // and any per-feature gap the witnesses' counters prove unreached -- see
2152 // the 12-bit refusals in decode.rs and `refusal_inventory.rs`.
2153 // lane-av112bitg: film grain joined the witnessed set (`grain_refusal`
2154 // deleted; the two-arm witness is
2155 // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
2156 // lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2) are parsed by
2157 // `ec-av1-syntax`. This block used to REFUSE every `ss_x != ss_y` header by
2158 // name, on the theory that every chroma extent was hardcoded 4:2:0
2159 // (`bw / 2, bh / 2` at every rect site, `chroma_side = side / 2` in
2160 // `decode_block`). Both halves of that theory are now false: the per-axis
2161 // port replaced every one of those extents with `>> ss_x` / `>> ss_y`
2162 // reads, and 4:4:4 (0,0) already decoded through them.
2163 // lane-av1422lift: 4:2:2 (1,0) is DECODED. The refusal string, its
2164 // `refusal_inventory.rs` row and its `Proof::NegativeGate` pairing are
2165 // deleted in this commit -- a refused format that decodes is a false
2166 // claim, and the gate that asserted the refusal could not fail on a tree
2167 // where 4:2:2 decode was completely broken.
2168 // lane-av1odd440, kept as an ASSERTION: `subsampling_y` is coded ONLY when
2169 // `subsampling_x` is 1 (spec 5.5.2's `color_config`; libaom
2170 // `av1_read_color_config`, `av1/decoder/decodeframe.c:4171-4175`, and its
2171 // writer's own `assert(seq_params->subsampling_y == 0 && "4:4:0
2172 // subsampling not allowed in AV1")`, `av1/encoder/bitstream.c:2467-2468`),
2173 // so a parsed header can carry (1,1), (1,0) or (0,0) and never (0,1):
2174 // 4:4:0 is not a cell a decoder can be handed at all. That used to be a
2175 // comment plus a refusal string naming the shape; with the refusal gone
2176 // the residual is an unreachable arm, and this repo closes those with an
2177 // assertion, never prose. The gate `the_440_cell_is_not_a_codable_chroma_
2178 // shape` proves the whole reachable set through this crate's own writer
2179 // AND reader.
2180 assert!(
2181 !(seq.subsampling_x == 0 && seq.subsampling_y == 1),
2182 "AV1 decode_stream: a parsed color_config carried 4:4:0 (subsampling_x=0, \
2183 subsampling_y=1); subsampling_y is coded only when subsampling_x is 1 \
2184 (spec 5.5.2), so this shape cannot be produced by ec-av1-syntax's \
2185 sequence_header -- the parser is wrong, not the caller"
2186 );
2187 // lane-av1-qmatrix: `quantization_params.using_qmatrix` + `qm_y`/`qm_u`/
2188 // `qm_v` (spec 5.9.12) select per-plane INVERSE QUANTISATION MATRICES --
2189 // spec 7.12.3's per-position `dqv` scale, libaom `get_dqv` over
2190 // `iwt_matrix_ref`. The parsed 4-bit values ARE the table levels
2191 // (libaom `quant_params->qmatrix_level_y/u/v`); 15 is libaom's flat
2192 // NULL-table sentinel, and a `using_qmatrix == 0` frame keeps all three
2193 // parked there, selecting no matrix. Frame-constant: recorded here (the
2194 // spot where this decoder refused such frames until this lane), read by
2195 // every dequantisation call site through [`crate::decode::block_iqmatrix`].
2196 // A real `aomenc --enable-qm=1` stream (`using_qmatrix = 1`, levels 5)
2197 // decodes byte-exact vs ffmpeg; the witness is
2198 // `a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact` below.
2199 let q = &header.quantization;
2200 // When the bit is UNSET the parsed 4-bit fields read 0 but mean nothing
2201 // (spec: they are not even coded): libaom parks the level at
2202 // `NUM_QM_LEVELS - 1`, its flat NULL-table sentinel
2203 // (`setup_segmentation_dequant`: `use_qmatrix ? qmatrix_level_y : 15`),
2204 // so a matrix-free frame selects no matrix.
2205 let flat = crate::qm::NUM_QM_LEVELS as u8 - 1;
2206 let levels = if q.using_qmatrix {
2207 [q.qm_y, q.qm_u, q.qm_v]
2208 } else {
2209 [flat; 3]
2210 };
2211 crate::decode::set_qm_levels(levels, fctx);
2212 // lane-av112bit's screen-content refusal is LIFTED by lane-av1screen12.
2213 // The claim it carried -- "a 12-bit frame with screen content tools
2214 // (allow_screen_content_tools=1: neither palette nor intrabc has a
2215 // 12-bit witness)" -- named a gap WIDER than the one it was written for:
2216 // `allow_screen_content_tools` only decides whether an intra block reads
2217 // the `palette_y_mode`/`palette_uv_mode` symbols and whether a leaf reads
2218 // `use_intrabc`, and BOTH of those reconstructions read their colours and
2219 // their frame copy at the frame's own `bit_depth` (`read_palette_colors_y`
2220 // / `_uv` take `bit_depth(fctx)`, the colour-index map writes u16 samples).
2221 // Nothing about them is 8/10-bit-shaped.
2222 //
2223 // Measured, with this guard lifted, all three arms decode BYTE-EXACT
2224 // against the instrumented `aomdec --rawvideo` AND against ffmpeg, each
2225 // with a +1 control on the oracle's own bytes:
2226 //
2227 // | arm | pin | frames | screen | allow_intrabc | palette / palette-UV / intrabc |
2228 // | --- | --- | --- | --- | --- | --- |
2229 // | palette | `screen12_palette.obu` | 2 | 2 | 0 | 76 / 43 / 0 |
2230 // | palette+intrabc | `screen12_intrabc.obu` | 1 | 1 | 1 | 36 / 34 / 11 |
2231 // | lossless+palette | `screen12_lossless_palette.obu` | 2 | 2 | 0 | 80 / 59 / 0 |
2232 //
2233 // Gates: `a_real_aomenc_12bit_screen_content_palette_stream_decodes_pixel_exact`,
2234 // `a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact`,
2235 // `a_real_aomenc_12bit_lossless_screen_content_stream_decodes_pixel_exact`.
2236 //
2237 // ON THE OLD "INTRABC IS UNPRODUCIBLE" NOTE: the earlier claim that
2238 // 12-bit `allow_intrabc` has no producer was a RECIPE artefact, not an
2239 // encoder limit. libaom decides that frame-header bit from its own
2240 // content detector (`encoder.c:2404`), not from `--tune-content=screen`:
2241 // an untiled `smptebars=size=128x96` source reads `allow_intrabc = 0`
2242 // with AND without the flag, while the 256x192 `-vf tile=2x2` source the
2243 // 8/10-bit intrabc census already uses reads `allow_intrabc = 1` with
2244 // and without it -- at 8, at 10 AND at 12 bits (measured).
2245 // lane-dpm1: a LOSSLESS frame (`qindex == 0` with zero deltas, spec 5.9.12)
2246 // is a different tile syntax, and this decoder has none of it: libaom
2247 // forces TX_4X4 with the WALSH-HADAMARD transform over every block (so no
2248 // `tx_depth` symbol is coded at all), and `is_cfl_allowed` narrows to
2249 // `plane_bsize == BLOCK_4X4` instead of the 32x32 rule, which changes the
2250 // `uv_mode` ALPHABET. Measured on his own screen-capture row at libaom
2251 // `-crf 5` (base_q_idx 0): the very first block, mi(0,0) BLOCK_32X32,
2252 // reads `uv_mode` off the CfL alphabet where libaom reads the plain one
2253 // (ours 12 = UV_CFL_PRED, aomdec 1 = V_PRED) and the tile desyncs at
2254 // symbol four of the frame. Refuse by name rather than return a picture
2255 // that is silently wrong from luma sample 0 (class `refusal-hides-a-defect`
2256 // read the other way: a silent wrong decode is worse than a named gap).
2257 // lane-lossless: `CodedLossless` (spec 5.9.12) -- every segment at
2258 // `qindex == 0` with zero plane deltas. The tile reader then forces TX_4X4
2259 // with the Walsh-Hadamard transform on every plane, codes no `tx_type`
2260 // symbol and narrows `is_cfl_allowed` to `plane_bsize == BLOCK_4X4`
2261 // (libaom `read_tx_size`/`read_tx_type`/`is_cfl_allowed`).
2262 //
2263 // lane-av1mixloss: PER-SEGMENT lossless (libaom `decodeframe.c:5205`) --
2264 // the header parser computes `lossless[segment_id]` for all 8 segments
2265 // (`qindex == 0` with zero plane deltas, `segment_qindex` applying that
2266 // segment's own `SEG_LVL_ALT_Q`) and `coded_lossless` = every segment
2267 // lossless. Everything FRAME-level already keys on the header's fields,
2268 // exactly as libaom gates them on `features->coded_lossless`/
2269 // `all_lossless`: `tx_mode` is `Only4x4` only when EVERY segment is
2270 // lossless, CDEF and the loop-filter levels are forced to 0 only then,
2271 // and loop restoration only on `all_lossless`. What this decoder lacked
2272 // was the BLOCK level: every block-decoder rule -- `read_tx_size`'s TX_4X4
2273 // early return, the suppressed `tx_type`, the Walsh-Hadamard,
2274 // `is_cfl_allowed`'s narrowing, the 4x4 chroma rasters -- indexes
2275 // `xd->lossless[segment_id]`, so a frame whose segments DISAGREE codes
2276 // lossless blocks inside a lossy frame. aomenc WRITES one:
2277 // `--end-usage=q --cq-level=0 --aq-mode=1` (variance AQ over a lossless
2278 // base) gives a high-variance segment a positive `SEG_LVL_ALT_Q` while a
2279 // flat one stays at `qindex == 0`. The table goes in whole and
2280 // [`decode::lossless`] resolves it per block through the block's own
2281 // `segment_id` (set by the spec-order `segment_id` read that precedes
2282 // every mode/transform symbol). Witness:
2283 // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact`.
2284 crate::decode::set_lossless_per_seg(header.lossless, fctx);
2285 crate::decode::set_bit_depth(bit_depth, fctx);
2286 // lane-av1mono: the sequence header's `mono_chrome`, set per frame like
2287 // the bit depth so a mono frame decoded on a thread that last saw a
2288 // 4:2:0 one never inherits the wrong plane count.
2289 crate::decode::set_mono(seq.mono_chrome, fctx);
2290 crate::decode::set_subsampling(seq.subsampling_x, seq.subsampling_y, fctx);
2291 // lane-av1readcensus: the coefficient-unit census is armed here, off the
2292 // same sequence-header subsampling. lane-av1422census422 widened it from
2293 // 4:4:4-only to "any format with an unsubsampled luma axis", so a 4:2:2
2294 // cell's per-plane unit counts are readable and a 4:2:2 gate can assert
2295 // a non-vacuous walk; 4:2:0 still reads zero, so the 4:2:0 control in
2296 // `a_pixel_exact_444_stream_walks_the_same_coefficient_units_the_oracle_does`
2297 // keeps asserting exactly that.
2298 crate::decode::set_census_nonsub(seq.subsampling_x, seq.subsampling_y);
2299 // lane-av1txr: spec 5.9.2 `disable_cdf_update` -- a frame that sets it
2300 // codes every tile symbol against the CDFs it started with, so the tile
2301 // readers must not adapt (libaom `decodeframe.c:2909`:
2302 // `allow_update_cdf = allow_update_cdf && !cm->features.disable_cdf_update`).
2303 crate::decode::set_disable_cdf_update(header.disable_cdf_update, fctx);
2304 // spec 7.16: this frame's superres state, for the filter chain --
2305 // `decode.rs` upscales between CDEF and loop restoration and sizes
2306 // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
2307 // unscaled frame so a later frame never inherits it.
2308 crate::decode::set_superres(
2309 if header.use_superres {
2310 header.upscaled_width
2311 } else {
2312 0
2313 },
2314 u32::from(header.superres_denom),
2315 fctx,
2316 );
2317 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
2318 let enable_masked_compound = seq.enable_masked_compound;
2319 let enable_jnt_comp = seq.enable_jnt_comp;
2320 // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's
2321 // read site doc.
2322 let enable_interintra_compound = seq.enable_interintra_compound;
2323 let interp_fixed = match header.interpolation_filter {
2324 ec_av1_syntax::InterpolationFilter::Switchable => None,
2325 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
2326 };
2327 // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
2328 // from that reference slot's saved CDF state instead of the spec 8.4
2329 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
2330 // builds.
2331 // lane-hdrlossless: libaom errors on the same stream (`decodeframe.c:5075`:
2332 // `if (features->primary_ref_frame != PRIMARY_REF_NONE &&
2333 // get_primary_ref_frame_buf(cm) == NULL) aom_internal_error(...,
2334 // AOM_CODEC_CORRUPT_FRAME, "Reference frame containing this frame's
2335 // initial frame context is unavailable.")`) -- a spec-conformant guard.
2336 let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
2337 None
2338 } else {
2339 Some(snap.primary_cdfs.clone().ok_or_else(|| {
2340 Error::unsupported(
2341 "AV1 decode_stream",
2342 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
2343 )
2344 })?)
2345 };
2346 let started_from = initial_cdfs.clone();
2347 // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.
2348 decode::set_coeff_trace_frame(decode_idx);
2349 // lane-t900 r9: one line per DECODE-order frame naming the header
2350 // fields a desync cliff is usually keyed on (frame type, base q,
2351 // primary_ref, the 7 ref slots, refresh mask, order hints).
2352 if std::env::var_os("EC_PROBE_HDR").is_some() {
2353 eprintln!(
2354 "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={:?}",
2355 header.frame_type,
2356 header.show_frame,
2357 header.show_existing_frame,
2358 header.quantization.base_q_idx,
2359 header.primary_ref_frame,
2360 header.ref_frame_idx,
2361 header.refresh_frame_flags,
2362 header.order_hint,
2363 header.tile_info.cols,
2364 header.tile_info.rows,
2365 header.tx_mode,
2366 header.interpolation_filter,
2367 header.reduced_tx_set,
2368 header.allow_warped_motion,
2369 header.is_motion_mode_switchable,
2370 header.use_ref_frame_mvs,
2371 header.skip_mode_present,
2372 header.cdef.bits,
2373 header.loop_restoration.frame_restoration_type,
2374 );
2375 }
2376
2377 let order_hint_bits = seq.order_hint_bits;
2378 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
2379 // of the picture sitting in each of its 7 single references' DPB
2380 // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
2381 // (a later frame projects from it) whether or not this frame itself
2382 // reads temporal candidates.
2383 let ref_order_hints = snap.ref_order_hints;
2384
2385 crate::timeline::bind(
2386 decode_idx,
2387 if header.frame_type == FrameType::Key {
2388 'K'
2389 } else if header.show_frame {
2390 'P'
2391 } else {
2392 'A'
2393 },
2394 header.show_frame,
2395 );
2396 crate::timeline::hdr_done();
2397 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
2398 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
2399 tile_bufs,
2400 &header.tile_info,
2401 header.mi_cols,
2402 header.mi_rows,
2403 header.quantization.base_q_idx,
2404 crate::quant::QuantDeltas {
2405 y_dc: i32::from(header.quantization.delta_q_y_dc),
2406 u_dc: i32::from(header.quantization.delta_q_u_dc),
2407 u_ac: i32::from(header.quantization.delta_q_u_ac),
2408 v_dc: i32::from(header.quantization.delta_q_v_dc),
2409 v_ac: i32::from(header.quantization.delta_q_v_ac),
2410 },
2411 header.frame_width,
2412 header.frame_height,
2413 enable_filter_intra,
2414 enable_edge_filter,
2415 &header.cdef,
2416 &header.loop_filter,
2417 &header.loop_restoration,
2418 initial_cdfs,
2419 header.tx_mode == TxMode::Select,
2420 header.reduced_tx_set,
2421 header.allow_screen_content_tools,
2422 header.allow_intrabc,
2423 header.delta,
2424 fctx,
2425 )?;
2426 // A key frame codes no inter blocks -- its own saved motion
2427 // field has no cells set, matching libaom's own "intra frame
2428 // contributes nothing to a later projection" behaviour, but
2429 // still carries `order_hint`/`ref_order_hints` for the distance
2430 // arithmetic a later frame's projection needs.
2431 let motion_field = crate::motion_field::MotionField::new(
2432 header.mi_cols as usize,
2433 header.mi_rows as usize,
2434 header.order_hint,
2435 ref_order_hints,
2436 // `frame_type` for the DPB slot: a key (or intra-only) frame is
2437 // never a projection source, and never spends a `ref_stamp`.
2438 true,
2439 );
2440 (picture, end_cdfs, Some(motion_field))
2441 } else {
2442 let last_slot = header.ref_frame_idx[0] as usize;
2443 let _ = last_slot;
2444 // lane-hdrlossless: libaom errors on the same stream -- a stream may
2445 // OPEN on an intra-only frame, but a reference resolving to a slot
2446 // that is still NULL is `AOM_CODEC_CORRUPT_FRAME "Inter frame
2447 // requests nonexistent reference"` (`decodeframe.c:5008-5031`) -- a
2448 // spec-conformant guard.
2449 if snap.refpix.dims(1).is_none() {
2450 return Err(Error::unsupported(
2451 "AV1 decode_stream",
2452 "an inter frame with no key frame before it",
2453 ));
2454 }
2455 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
2456 // (spec 7.8/7.20). Any of them having no picture yet is not a
2457 // stream error on its own: `decode_inter_block` only needs a
2458 // given slot when a block actually selects that reference, and
2459 // refuses by name there if the slot is still empty -- widened
2460 // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
2461 // one of the 7 single-reference slots.
2462 // lane-fimv r1: record the header state the fimv gate asserts on
2463 // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
2464 if header.force_integer_mv {
2465 decode::note_force_integer_mv_frame();
2466 }
2467 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
2468 // this frame's header actually asks for temporal candidates --
2469 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
2470 // behaviour bit for bit when this is `None` (see its own doc).
2471 // lane-twostage: the stage-1 sink is handed the table a consumer
2472 // would have read out of the slot, not the raw end-of-tile one.
2473 let started_from_stage1 = started_from.clone();
2474 let stage1_adapter = stage1.map(|sink| {
2475 move |end_cdfs: Cdfs,
2476 motion_field: crate::motion_field::MotionField,
2477 width: usize,
2478 height: usize| {
2479 sink(
2480 stored_cdfs_for(header, end_cdfs, started_from_stage1.clone()),
2481 motion_field,
2482 width,
2483 height,
2484 )
2485 }
2486 });
2487 let tpl_field = &snap.tpl_field;
2488 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
2489 tile_bufs,
2490 &header.tile_info,
2491 header.mi_cols,
2492 header.mi_rows,
2493 header.quantization.base_q_idx,
2494 crate::quant::QuantDeltas {
2495 y_dc: i32::from(header.quantization.delta_q_y_dc),
2496 u_dc: i32::from(header.quantization.delta_q_u_dc),
2497 u_ac: i32::from(header.quantization.delta_q_u_ac),
2498 v_dc: i32::from(header.quantization.delta_q_v_dc),
2499 v_ac: i32::from(header.quantization.delta_q_v_ac),
2500 },
2501 header.frame_width,
2502 header.frame_height,
2503 snap.refpix,
2504 &header.cdef,
2505 &header.loop_filter,
2506 &header.loop_restoration,
2507 initial_cdfs,
2508 header.allow_high_precision_mv,
2509 header.force_integer_mv,
2510 header.ref_frame_sign_bias,
2511 header.global_motion,
2512 interp_fixed,
2513 enable_dual_filter,
2514 order_hint_bits,
2515 header.order_hint,
2516 ref_order_hints,
2517 tpl_field.as_ref(),
2518 header.reference_select,
2519 enable_masked_compound,
2520 enable_jnt_comp,
2521 enable_interintra_compound,
2522 header.skip_mode_present,
2523 header.skip_mode_frame,
2524 header.reduced_tx_set,
2525 header.tx_mode == TxMode::Select,
2526 header.is_motion_mode_switchable,
2527 header.allow_warped_motion,
2528 header.allow_screen_content_tools,
2529 header.delta,
2530 enable_filter_intra,
2531 stage1_adapter
2532 .as_ref()
2533 .map(|f| f as &dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)),
2534 fctx,
2535 )?;
2536 (picture, end_cdfs, motion_field)
2537 };
2538 // lane-lr r4: the Wiener/self-guided pixel filters are wired
2539 // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
2540 // `uses_lr` frames now decode all the way to pixels.
2541 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
2542 // *initial* table into the slots it refreshes, not the adapted
2543 // end-of-tile one.
2544 let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from);
2545 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
2546 // lane-av1dumploud: loud on a short write. This one is APPEND-mode and
2547 // spans every frame of a run, so there is no total length to declare
2548 // (`append_unknown` says so on the failure line rather than guessing
2549 // one); the per-line writes are still checked, so an ENOSPC halfway
2550 // through a table no longer passes as a complete one.
2551 let mut f = crate::dumpio::LoudDump::append_unknown("EC_AV1_DUMP_TABLES", &path);
2552 let mut line = |s: String| f.write(s.as_bytes());
2553 line(format!("=== frame idx={shown_idx} ===\n"));
2554 line(format!("partition_w64 {:?}\n", stored_cdfs.partition_w64));
2555 line(format!("partition_w32 {:?}\n", stored_cdfs.partition_w32));
2556 line(format!("partition_w16 {:?}\n", stored_cdfs.partition_w16));
2557 line(format!("skip {:?}\n", stored_cdfs.skip));
2558 line(format!("new_mv {:?}\n", stored_cdfs.new_mv));
2559 line(format!("zero_mv {:?}\n", stored_cdfs.zero_mv));
2560 line(format!("ref_mv {:?}\n", stored_cdfs.ref_mv));
2561 line(format!("mv_joint {:?}\n", stored_cdfs.mv_joint));
2562 f.finish();
2563 }
2564 // lane-comppin r3: decode-order (not display-order) dump of every
2565 // frame's own post-deblock buffer -- the pre-existing pixel diff
2566 // (`scratch_isolate_pinned_mismatch`) only ever compares *shown*
2567 // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a
2568 // later shown frame is otherwise invisible; diff this byte-for-byte
2569 // against `EC_AV1_POSTDEBLOCK_DUMP.fN` from the instrumented aomdec build
2570 // (rung 6, `scripts/instrument-aom-oracle.sh`; 1 byte per sample, so it is
2571 // byte-comparable only at 8-bit -- for HBD use rung 12 `EC_AV1_FINAL_DUMP`)
2572 // to isolate whether the defect is in a hidden frame's own
2573 // reconstruction or downstream of it.
2574 if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") {
2575 // lane-hbd r4: debug dump narrows to u8 -- this diagnostic
2576 // predates 10-bit support and is an 8-bit-oracle comparison
2577 // only (aomdec's own dump is 8-bit here too).
2578 //
2579 // lane-av1dumploud: loud on a short write; expected length is the three
2580 // planes' own lengths (narrowing is 1 byte per sample, so the count is
2581 // unchanged).
2582 let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
2583 crate::dumpio::write_planes(
2584 "EC_AV1_DECODE_ORDER_DUMP",
2585 format!("{path}.f{decode_idx}"),
2586 &[
2587 &narrow(&picture.y),
2588 &narrow(&picture.u),
2589 &narrow(&picture.v),
2590 ],
2591 );
2592 }
2593 // lane-hidden r1: the frame exactly as it is about to be stored into
2594 // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
2595 // order, hidden (`show_frame == 0`) alt-ref frames included, and
2596 // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
2597 // u8-narrowing diagnostic dumps above. Matches the instrumented
2598 // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
2599 // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
2600 // hidden frame's pixels comparable at all.
2601 // lane-unwritten-dep: the census AT the output point, beside the dump that
2602 // defines "the output" -- the same bytes, so the claim is about the frame the
2603 // caller receives rather than about an intermediate stage.
2604 //
2605 // WHAT THIS IS FOR, corrected: an earlier revision of this comment said the
2606 // pre-deblock plane was byte-identical plain-vs-sentinel and that deblock
2607 // creates the dependence. That was wrong, and it was `dump_stage16`'s fault:
2608 // it cropped chroma as `(fw/2, fh/2)`, a 4:2:0 assumption, so on a 64x64
2609 // 4:2:2 frame 2048 chroma samples appeared in no stage dump at all -- exactly
2610 // the region the difference lives in. With per-axis extents the corrected
2611 // measurement on `440_request_is_422` is that the PRE-DEBLOCK dump already
2612 // differs by 2158 bytes and an exact u16 census finds 224 unwritten samples
2613 // (U 112, V 112, rows 36..63) -- the same count `lanes/av1unwritten.report.md`
2614 // reports. The hole is present before any filter runs, and the pre-deblock
2615 // census SEES it.
2616 //
2617 // So this second census is not a patch for a blind pre-deblock scan. It is
2618 // the measurement taken where the reference-bank bytes are taken, which
2619 // covers the whole span from the tile walk to those bytes: every filter
2620 // writes IN PLACE into the very buffer this scans, so nothing a later
2621 // filter does can open a hole outside its extent.
2622 //
2623 // lane-av1graincensus, the scope correction this comment needed: "to the
2624 // caller's frame" was WRONG, and this call is not what makes it right.
2625 // `apply_grain` runs after this and ALLOCATES a fresh picture
2626 // (`film_grain::uninit_plane`, `with_capacity` + `set_len`, no fill), so
2627 // that destination never passes through here. The claim over the PRE-GRAIN
2628 // planes -- the bytes the reference bank stores and every later frame
2629 // predicts from -- is what this line supports; the grained picture the
2630 // caller receives is censused by `decode::census_unwritten_grained`, at
2631 // `apply_grain`'s own return, over its own counters.
2632 decode::census_unwritten_final(&picture.y, &picture.u, &picture.v);
2633 if let Some(prefix) = final_dump {
2634 // lane-av1dumploud: this is the site that produced the 13 320 192-byte
2635 // truncated frame in `lanes/unwritten-dep.report.md` -- `let _ =
2636 // f.write_all(&buf)` swallowed the ENOSPC. Expected length is derived
2637 // from the PLANES and the sample width, independently of `buf`, so a
2638 // writer that builds the wrong buffer still gets caught.
2639 let sample_width = if bit_depth == 8 { 1 } else { 2 };
2640 let expected = (picture.y.len() + picture.u.len() + picture.v.len()) * sample_width;
2641 let mut f = crate::dumpio::LoudDump::create(
2642 "EC_AV1_FINAL_DUMP",
2643 format!("{prefix}.f{decode_idx}"),
2644 expected,
2645 );
2646 for plane in [&picture.y, &picture.u, &picture.v] {
2647 if bit_depth == 8 {
2648 f.write(&plane.iter().map(|&s| s as u8).collect::<Vec<u8>>());
2649 } else {
2650 let mut row = Vec::with_capacity(plane.len() * 2);
2651 for &s in plane {
2652 row.extend_from_slice(&s.to_le_bytes());
2653 }
2654 f.write(&row);
2655 }
2656 }
2657 f.finish();
2658 }
2659 if let Some(why) = fctx.corrupt.get() {
2660 return Err(Error::corrupt(format!("AV1 frame {decode_idx}: {why}")));
2661 }
2662 Ok(FrameOutput {
2663 picture,
2664 stored_cdfs,
2665 motion_field,
2666 seg_map: decode::take_segment_ids(fctx),
2667 })
2668}
2669
2670/// lane-intra14 r1: INTRA-coded 1:4 strips decoded on the INTER block path
2671/// (64x16, 16x64, 32x8, 8x32) -- the counters a recipe sweep needs from
2672/// outside the crate.
2673pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) {
2674 (
2675 crate::decode::intra_rect4_strip_in_inter_hits(0),
2676 crate::decode::intra_rect4_strip_in_inter_hits(1),
2677 crate::decode::intra_rect4_strip_in_inter_hits(2),
2678 crate::decode::intra_rect4_strip_in_inter_hits(3),
2679 )
2680}
2681
2682/// lane-av1recipehunt: the recipe sweep's view of the `delta_q` story from
2683/// OUTSIDE the crate -- `(delta_q symbol groups read, rect64 dequant calls that
2684/// saw `CURRENT_Q_IDX != base_q_idx`)`. A recipe that reads delta_q but never
2685/// lands one inside a rect64 root is a different failure from one that reads
2686/// neither, and the gate can only tell them apart with both numbers.
2687pub fn rect64_qidx_drift_counters() -> (usize, usize) {
2688 (
2689 crate::decode::delta_q_hits(),
2690 crate::decode::rect64_qidx_drift_hits(),
2691 )
2692}
2693
2694#[cfg(test)]
2695pub(crate) mod tests;