forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

decode.rs7455 lines, 298.3 KiBHistoryRawDownload
1//! Software decoder for this crate's own key-frame tile payloads (spec 5.11),
2//! the reader half of [`crate::tile`]'s writer.
3//!
4//! `tile.rs` is another lane's territory this round (`lane-av1-rect` is
5//! touching its partition search), so nothing here imports its private
6//! helpers: the handful of `pub(crate)` items it already exposes
7//! ([`crate::tile::block_grid`], [`crate::tile::has_half`],
8//! [`crate::tile::INTRA_MODE_CTX`], [`crate::tile::write_golomb`]) are reused,
9//! and everything else (the partition/coefficient context arithmetic, the
10//! scan table) is a from-spec reimplementation kept in step with the writer by
11//! the gate tests below rather than by sharing code with it.
12//!
13//! # Scope (round 1)
14//! Key frames only, and only the shapes the encoder actually still needs to
15//! prove itself against: every coded block is `DC_PRED` (this crate's mode
16//! search names other intra modes, but a decoder for those needs the
17//! directional-prediction edge-reach plumbing [`crate::intra::predict`]
18//! already carries; wiring it up is round 2), never skipped, and every
19//! superblock is a whole number of 64x64 units (a frame whose true edge falls
20//! inside one, forcing the gathered-CDF partial-superblock path, is round 2
21//! too). Anything outside that refuses with [`Error::unsupported`] rather than
22//! silently miscoding.
23
24use ec_av1_syntax::{CdefParams, LoopFilterParams};
25use ec_core::{Error, Result};
26
27use crate::cdf;
28use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
29use crate::encode::{Picture, Reach};
30use crate::intra::predict;
31use crate::mc;
32use crate::msac::SymbolDecoder;
33use crate::mvstack::{
34 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
35 MiGrid, MiInfo, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
36 find_mv_stack, find_mv_stack_with_sign_bias, reference_mode_ctx, single_ref_ctx,
37 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
38 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
39};
40use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
41use crate::transform::{TxType, dequant_and_inverse_typed};
42
43const PARTITION_NONE: usize = 0;
44const PARTITION_SPLIT: usize = 3;
45const SB_MI: u32 = 16;
46const BLOCK_MI: u32 = 8;
47
48/// How many `use_filter_intra` symbols this decoder has read as `1`, across
49/// every call in the process -- the cheap counter [`filter_intra_hits`] gate
50/// tests read (before/after, not the absolute value) to prove a stream
51/// actually exercised the filter-intra predictor rather than silently
52/// skipping it.
53static FILTER_INTRA_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
54
55/// Current value of [`FILTER_INTRA_HITS`].
56pub(crate) fn filter_intra_hits() -> usize {
57 FILTER_INTRA_HITS.load(std::sync::atomic::Ordering::Relaxed)
58}
59
60/// How many 4-pixel deblocking edge groups [`edge_params`] has actually
61/// selected for filtering, across every call in the process -- the same
62/// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
63/// exercised `apply_deblock` rather than every edge landing on level 0.
64static DEBLOCK_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
65
66/// Current value of [`DEBLOCK_HITS`].
67pub(crate) fn deblock_hits() -> usize {
68 DEBLOCK_HITS.load(std::sync::atomic::Ordering::Relaxed)
69}
70
71/// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
72/// the block's own side, across every call in the process -- the same
73/// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
74/// actually exercised a *split* transform under `TxMode::Select` rather than
75/// every block coincidentally resolving `depth=0` (indistinguishable from
76/// `TxMode::Largest` pixel-wise).
77static TX_DEPTH_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
78
79/// Current value of [`TX_DEPTH_HITS`].
80pub(crate) fn tx_depth_hits() -> usize {
81 TX_DEPTH_HITS.load(std::sync::atomic::Ordering::Relaxed)
82}
83
84/// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
85/// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
86/// call in the process -- the same before/after counter pattern as
87/// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
88/// `eob_pt`/1D-neighbour context path rather than every block coincidentally
89/// landing on `DCT_DCT`.
90static TX_CLASS1_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
91
92/// How many `uv_mode` reads resolved to a directional chroma mode (neither
93/// `DC_PRED` nor `UV_CFL_PRED`), across every call in the process -- the same
94/// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
95/// actually exercised chroma's own directional predictor.
96static DIRECTIONAL_UV_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
97
98/// Current value of [`DIRECTIONAL_UV_HITS`].
99pub(crate) fn directional_uv_hits() -> usize {
100 DIRECTIONAL_UV_HITS.load(std::sync::atomic::Ordering::Relaxed)
101}
102
103/// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
104/// something other than [`ANGLE_DELTA_ZERO`], across every call in the
105/// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
106/// proving a stream actually exercised a nonzero angle delta.
107static ANGLE_DELTA_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
108
109/// How many [`read_single_ref`] reads resolved to a reference other than
110/// `LAST_FRAME`, across every call in the process -- the same before/after
111/// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
112/// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
113/// only other supported one so far) rather than every block coincidentally
114/// resolving `LAST_FRAME`.
115static NON_LAST_REF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
116
117/// Current value of [`NON_LAST_REF_HITS`].
118pub(crate) fn non_last_ref_hits() -> usize {
119 NON_LAST_REF_HITS.load(std::sync::atomic::Ordering::Relaxed)
120}
121
122/// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
123/// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
124/// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
125/// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
126/// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
127/// `GOLDEN_FRAME` draw it did not ask for.
128static LAST2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
129static LAST3_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
130static GOLDEN_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
131static BWDREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
132static ALTREF2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
133static ALTREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
134
135/// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
136/// -- proves a `reference_select` stream actually reached a block that picked
137/// compound, not just that the header bit was set. Every such block is
138/// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
139/// so this only ever counts attempted reads, never a completed decode.
140static COMP_MODE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
141
142/// Current value of [`COMP_MODE_HITS`].
143pub(crate) fn comp_mode_hits() -> usize {
144 COMP_MODE_HITS.load(std::sync::atomic::Ordering::Relaxed)
145}
146
147/// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
148/// proves a real `skip_mode_present` stream actually reached a block that
149/// picked it, not just that the frame header bit was set.
150static SKIP_MODE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
151
152/// Current value of [`SKIP_MODE_HITS`].
153pub(crate) fn skip_mode_hits() -> usize {
154 SKIP_MODE_HITS.load(std::sync::atomic::Ordering::Relaxed)
155}
156
157/// How many [`read_inter_compound_mode`] reads actually happened
158/// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
159/// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
160/// mvstack build), not just that `comp_mode` fired. Still refused right
161/// after (no MV assignment or MC wired), so this only counts attempted
162/// reads.
163static COMPOUND_MODE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
164
165/// Current value of [`COMPOUND_MODE_HITS`].
166pub(crate) fn compound_mode_hits() -> usize {
167 COMPOUND_MODE_HITS.load(std::sync::atomic::Ordering::Relaxed)
168}
169
170/// How many query blocks folded in at least one temporal MV candidate
171/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
172/// temporal-MV gate's own firing counter (lane-av1tmvp).
173///
174/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
175/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
176/// this file (`decode_inter_block`) still passes `tpl: None` -- this
177/// counter compiles and the projection math it counts is unit-tested
178/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
179/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
180/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
181/// against any real stream today. See the module doc on
182/// `crate::motion_field` and this crate's ledger for the remaining wiring.
183pub(crate) fn tmv_hits() -> usize {
184 crate::mvstack::tmv_hits()
185}
186
187/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
188/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
189/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
190/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
191/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
192/// needs to turn a query block's own resolved `ref_frame` into
193/// `TplArgs::cur_offset_0` (spec 7.9.3).
194pub(crate) struct TplFrameArgs<'a> {
195 pub field: &'a crate::motion_field::TplField,
196 pub order_hint_bits: u32,
197 pub order_hint: u32,
198 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
199 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
200 /// frame's own `ref_frame_idx` names for each single reference.
201 pub ref_order_hints: [u32; 7],
202}
203
204/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
205/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
206/// decoded `grid`: every 4x4 unit an inter block covers reads the same
207/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
208/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
209/// exact — every block this crate ever codes is at least 8x8, so no 8x8
210/// cell straddles two different blocks' values.
211pub(crate) fn build_motion_field(
212 grid: &MiGrid,
213 mi_cols: usize,
214 mi_rows: usize,
215 order_hint: u32,
216 ref_order_hints: [u32; 7],
217) -> crate::motion_field::MotionField {
218 let mut field =
219 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
220 for row in 0..mi_rows {
221 for col in 0..mi_cols {
222 if let Some(info) = grid.get(row, col)
223 && info.is_inter
224 && info.ref_frame > 0
225 {
226 field.set(
227 row,
228 col,
229 crate::motion_field::SavedMv {
230 mv: info.mv,
231 ref_frame: info.ref_frame,
232 },
233 );
234 }
235 }
236 }
237 field
238}
239
240/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
241/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
242pub(crate) fn ref_hits(ref_frame: i8) -> usize {
243 let c = match ref_frame {
244 LAST2_FRAME => &LAST2_HITS,
245 LAST3_FRAME => &LAST3_HITS,
246 GOLDEN_FRAME => &GOLDEN_HITS,
247 BWDREF_FRAME => &BWDREF_HITS,
248 ALTREF2_FRAME => &ALTREF2_HITS,
249 ALTREF_FRAME => &ALTREF_HITS,
250 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
251 };
252 c.load(std::sync::atomic::Ordering::Relaxed)
253}
254
255thread_local! {
256 /// The sequence header's `enable_intra_edge_filter`, set once per
257 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
258 /// own read of it, kept off the call stack (see that function's own doc
259 /// comment for why) rather than threaded through every `read_plane`/
260 /// `decode_block`/`decode_leaf8` call between here and there.
261 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
262}
263
264/// Current value of [`ANGLE_DELTA_HITS`].
265pub(crate) fn angle_delta_hits() -> usize {
266 ANGLE_DELTA_HITS.load(std::sync::atomic::Ordering::Relaxed)
267}
268
269/// Current value of [`TX_CLASS1_HITS`].
270pub(crate) fn tx_class1_hits() -> usize {
271 TX_CLASS1_HITS.load(std::sync::atomic::Ordering::Relaxed)
272}
273const SUB_MI: u32 = 4;
274const MI: usize = 4;
275const SB: usize = 64;
276const BLOCK: usize = 32;
277const SUB: usize = 16;
278const TX32: usize = 32;
279const TX16: usize = 16;
280const TX8: usize = 8;
281const TX4: usize = 4;
282const DC_PRED: usize = 0;
283/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
284/// carries an angle delta — [`crate::tile`]'s own private copy of the same
285/// constant.
286const V_PRED: usize = 1;
287/// The last directional mode, `D67_PRED`.
288const D67_PRED: usize = 8;
289/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
290/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
291/// codes anything else, so this decoder never reads anything else either.
292const ANGLE_DELTA_ZERO: usize = 3;
293const NUM_BASE_LEVELS: i32 = 2;
294const COEFF_BASE_RANGE: i32 = 12;
295const BR_STEP: i32 = 3;
296const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
297
298/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
299/// whose probability mass a superblock or block half outside the frame
300/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
301/// duplicated here (that module is another lane's territory this round) and
302/// kept in step with it by the byte-exact round-trip tests below rather than
303/// by sharing code.
304const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
305const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
306
307fn element_prob(cdf: &[u16], element: usize) -> u16 {
308 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
309}
310
311/// The two-symbol CDF a partial superblock/block's forced-split flag is read
312/// with: the mass of `elements` becomes the probability of the one partition
313/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
314/// (the encoder's non-adapting counterpart to this read).
315fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
316 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
317 [32768 - split, 32768, 0]
318}
319
320fn unsupported(what: impl Into<String>) -> Error {
321 Error::unsupported("AV1 tile", what.into())
322}
323
324/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
325/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
326/// same rule.
327pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
328 match base_q_idx {
329 0..=20 => 0,
330 21..=60 => 1,
331 61..=120 => 2,
332 _ => 3,
333 }
334}
335
336/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
337/// [`crate::tile`]'s writer generates its scan tables with.
338fn default_scan(side: usize) -> Vec<u16> {
339 let mut scan = Vec::with_capacity(side * side);
340 for d in 0..(2 * side - 1) {
341 let lo = d.saturating_sub(side - 1);
342 let hi = d.min(side - 1);
343 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
344 if d % 2 == 0 {
345 scan.extend(diagonal.rev());
346 } else {
347 scan.extend(diagonal);
348 }
349 }
350 scan
351}
352
353/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
354/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
355/// in, instead of the default zigzag. libaom's own tables are keyed by a
356/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
357/// physically column-major level buffer, but they decompose to the exact
358/// same (row, col) walk as a flat row-major traversal of *our* row-major
359/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
360/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
361/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
362/// transposed (column 0 down every row, then column 1, ...).
363fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
364 match class {
365 TxClass::Vert => (0..(side * side) as u16).collect(),
366 TxClass::Horiz => (0..side)
367 .flat_map(|col| (0..side).map(move |row| (row * side + col) as u16))
368 .collect(),
369 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
370 }
371}
372
373fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
374 match scan_idx {
375 0 => 0,
376 i if i <= area / 8 => 1,
377 i if i <= area / 4 => 2,
378 _ => 3,
379 }
380}
381
382fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
383 if row >= side || col >= side {
384 0
385 } else {
386 grid[row * side + col]
387 }
388}
389
390/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
391/// `txb_common.h`): everything but the two lone-axis-identity types this
392/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
393#[derive(Clone, Copy, PartialEq, Eq)]
394enum TxClass {
395 TwoD,
396 Horiz,
397 Vert,
398}
399
400impl TxClass {
401 fn of(tx_type: TxType) -> Self {
402 match tx_type {
403 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
404 // key on axis alone -- FLIPADST is still ADST for this purpose.
405 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
406 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
407 _ => Self::TwoD,
408 }
409 }
410}
411
412/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
413/// table (indexed by the position along the transform's *coded* axis --
414/// `col` for horiz, `row` for vert) that places their contexts past the 2D
415/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
416/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
417fn nz_map_ctx_offset_1d(i: usize) -> usize {
418 match i {
419 0 => 26,
420 1 => 31,
421 _ => 36,
422 }
423}
424
425fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
426 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
427 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
428 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
429 // position through the full 1D neighbour sum and offset table. Skipping
430 // that for every class desynced the last (DC) coefficient of a
431 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
432 // 0, which then read one extra `BR` symbol at the max and forced a
433 // spurious third Golomb call).
434 if class == TxClass::TwoD && row == 0 && col == 0 {
435 return 0;
436 }
437 let offsets: [(usize, usize); 5] = match class {
438 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
439 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
440 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
441 };
442 let mag: i32 = offsets
443 .iter()
444 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
445 .sum();
446 let ctx = ((mag + 1) >> 1).min(4) as usize;
447 match class {
448 TxClass::TwoD => ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize,
449 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
450 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
451 }
452}
453
454fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
455 let extra = match class {
456 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
457 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
458 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
459 };
460 let mag = neighbour(grid, side, row + 1, col).abs()
461 + neighbour(grid, side, row, col + 1).abs()
462 + extra;
463 let mag = (((mag + 1) >> 1).min(6)) as usize;
464 if row == 0 && col == 0 {
465 return mag;
466 }
467 let near_origin = match class {
468 TxClass::TwoD => row < 2 && col < 2,
469 TxClass::Horiz => col == 0,
470 TxClass::Vert => row == 0,
471 };
472 if near_origin { mag + 7 } else { mag + 14 }
473}
474
475fn dc_vote(dc: Option<bool>) -> i32 {
476 match dc {
477 None => 0,
478 Some(true) => -1,
479 Some(false) => 1,
480 }
481}
482
483fn dc_sign_ctx(vote: i32) -> usize {
484 match vote.signum() {
485 0 => 0,
486 -1 => 1,
487 _ => 2,
488 }
489}
490
491/// The remainder of a level the base and base-range syntax could not reach
492/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
493/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
494fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
495 let mut length = 1u32;
496 while dec.literal(1) == 0 {
497 length += 1;
498 if length > 20 {
499 return Err(unsupported("a Golomb tail longer than this decoder reads"));
500 }
501 }
502 let mut x = 1u32;
503 for _ in 1..length {
504 x = (x << 1) | dec.literal(1);
505 }
506 Ok(x - 1)
507}
508
509/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
510/// [`crate::tile`]'s `write_eob`.
511fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
512 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
513 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
514
515 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
516 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
517 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
518 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
519 // `eob_multi_ctx`). Missing that split desynced the very first
520 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
521 // against a real aomdec trace).
522 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
523 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
524 (_, Some(class1)) => class1,
525 };
526 let group = dec.symbol(eob_pt) + 1;
527 if trace {
528 eprintln!("TRACE eob_pt value={group}");
529 }
530 let bits = OFFSET_BITS[group];
531 let mut offset = 0u32;
532 if bits > 0 {
533 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
534 if trace {
535 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
536 }
537 offset = top << (bits - 1);
538 if bits > 1 {
539 offset |= dec.literal(bits - 1);
540 }
541 }
542 GROUP_START[group] + offset as usize
543}
544
545/// One transform block's levels, the inverse of [`crate::tile`]'s
546/// `write_coeffs`, returned as a `side * side` grid in raster order, along
547/// with the transform type that grid was coded under (`DCT_DCT` when the
548/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
549/// 64-point transforms, which never code anything else).
550///
551/// # Errors
552/// Returns an error if the `tx_type` symbol decodes to a value outside its
553/// CDF's own set (a corrupt or unsupported bitstream) — every value the
554/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
555/// produce dispatches to a real inverse transform.
556/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
557/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
558/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
559/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
560/// the plane's own predicted mode instead. Every entry this table can
561/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
562/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
563/// table ever names), so unlike the CDF-coded luma path there is no
564/// ext-tx-set membership check to fall back from here.
565fn default_intra_tx_type(mode: u8) -> TxType {
566 use crate::intra::{
567 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
568 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
569 };
570 match mode {
571 DC_PRED | D45_PRED => TxType::DctDct,
572 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
573 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
574 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
575 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
576 }
577}
578
579fn read_coeffs(
580 dec: &mut SymbolDecoder,
581 coding: &mut TxbTables,
582 scan: &[u16],
583 skip_ctx: usize,
584 sign_ctx: usize,
585 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
586 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
587 // nothing at all; `DctDct` for every luma call and every chroma call at
588 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
589 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
590 default_tx_type: TxType,
591) -> Result<(Vec<i32>, TxType)> {
592 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
593 let side = coding.side;
594 let mut grid = vec![0i32; side * side];
595 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
596 if trace {
597 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
598 }
599 if all_zero {
600 return Ok((grid, TxType::DctDct));
601 }
602 let mut tx_type = default_tx_type;
603 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
604 // The CDF row's own width names its set (lane-cdffwd2: extended
605 // past the original two-way intra split once wider `reduced_tx_set
606 // == 0` inter sets joined the table): 17 slots (16 symbols) is
607 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
608 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
609 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
610 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
611 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
612 let len = tx_type_cdf.len();
613 let t = dec.symbol(tx_type_cdf);
614 if trace {
615 eprintln!("TRACE tx_type value={t} len={len}");
616 }
617 tx_type = match len {
618 17 => TxType::from_symbol_all16(t),
619 13 => TxType::from_symbol_set2_12(t),
620 8 => TxType::from_symbol_set1(t),
621 _ => TxType::from_symbol(t),
622 }
623 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
624 }
625
626 let class = TxClass::of(tx_type);
627 if class != TxClass::TwoD {
628 TX_CLASS1_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
629 }
630 let eob = read_eob(dec, coding, class);
631 if trace {
632 eprintln!("TRACE eob value={eob}");
633 }
634 let class_scan;
635 let scan: &[u16] = if class == TxClass::TwoD {
636 scan
637 } else {
638 class_scan = class_scan_table(side, class);
639 &class_scan
640 };
641 let mut levels = vec![0i32; side * side];
642 for scan_idx in (0..eob).rev() {
643 let pos = scan[scan_idx] as usize;
644 let (row, col) = (pos / side, pos % side);
645 let level = if scan_idx == eob - 1 {
646 let ctx = eob_coeff_ctx(scan_idx, side * side);
647 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
648 if trace {
649 eprintln!(
650 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
651 );
652 }
653 v
654 } else {
655 let ctx = base_ctx(&levels, side, row, col, class);
656 let v = dec.symbol(&mut coding.base[ctx]) as i32;
657 if trace {
658 eprintln!(
659 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
660 );
661 }
662 v
663 };
664 let level = if level > NUM_BASE_LEVELS {
665 let ctx = br_ctx(&levels, side, row, col, class);
666 let mut level = level;
667 let mut sent = 0;
668 loop {
669 let k = dec.symbol(&mut coding.br[ctx]) as i32;
670 if trace {
671 eprintln!(
672 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
673 );
674 }
675 level += k;
676 sent += BR_STEP;
677 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
678 break;
679 }
680 }
681 level
682 } else {
683 level
684 };
685 levels[pos] = level;
686 }
687
688 for &pos in &scan[..eob] {
689 let level = levels[pos as usize];
690 if level == 0 {
691 continue;
692 }
693 let negative = if pos == 0 {
694 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
695 if trace {
696 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
697 }
698 v
699 } else {
700 dec.literal(1) == 1
701 };
702 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
703 let g = read_golomb(dec)?;
704 if trace {
705 eprintln!("TRACE golomb pos={pos} value={g}");
706 }
707 level + g as i32
708 } else {
709 level
710 };
711 grid[pos as usize] = if negative { -level } else { level };
712 }
713 Ok((grid, tx_type))
714}
715
716/// What one coded block leaves behind for the blocks that read it as a
717/// neighbour: whether it coded anything at all, and the sign of its DC —
718/// [`crate::tile`]'s own private `Neighbour`.
719#[derive(Clone, Copy, Default)]
720struct Neighbour {
721 /// The transform unit's cumulative coefficient level (spec `cul_level`,
722 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
723 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
724 /// boolean (`level != 0`) is enough for every context this decoder read
725 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
726 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
727 /// needs the actual magnitude tier of its above/left neighbours, not
728 /// just whether they coded anything.
729 level: u8,
730 dc: Option<bool>,
731}
732
733fn neighbour_state(grid: &[i32]) -> Neighbour {
734 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
735 Neighbour {
736 level: cul.min(7) as u8,
737 dc: (grid[0] != 0).then_some(grid[0] < 0),
738 }
739}
740
741/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
742/// transform unit smaller than the block it sits in): `top`/`left` are the
743/// above/left neighbours' magnitude tiers, each already clamped to 4.
744const SKIP_CONTEXTS: [[usize; 5]; 5] = [
745 [1, 2, 2, 2, 3],
746 [2, 4, 4, 4, 5],
747 [2, 4, 4, 4, 5],
748 [2, 4, 4, 4, 5],
749 [3, 5, 5, 5, 6],
750];
751
752/// The neighbour state a block's contexts are read from — a duplicate of
753/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
754/// territory this round), kept at the same two granularities the real writer
755/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
756/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
757/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
758/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
759/// chroma transform straddling the true, odd-sized frame edge see its
760/// neighbour's state clamped at its own subsampled edge rather than luma's.
761struct Neighbours {
762 above: Vec<[Neighbour; 3]>,
763 left: Vec<[Neighbour; 3]>,
764 above_mode: Vec<usize>,
765 left_mode: Vec<usize>,
766 above_side: Vec<usize>,
767 left_side: Vec<usize>,
768 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
769 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
770 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
771 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
772 /// array cannot tell the second leaf's partition symbol that the first
773 /// one was coded at 8x8.
774 above_side_mi: Vec<usize>,
775 left_side_mi: Vec<usize>,
776 /// Whether the block above/left of this column/row was coded `skip` --
777 /// an inter frame's own `skip` context (spec `SkipContext`), which the
778 /// key-frame writer never tracks (its skip context is always zero); a
779 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
780 /// `left_skip`.
781 above_skip: Vec<bool>,
782 left_skip: Vec<bool>,
783 /// Whether the block above/left of this column/row coded `skip_mode`
784 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
785 /// lane-av1comp round 14.
786 above_skip_mode: Vec<bool>,
787 left_skip_mode: Vec<bool>,
788 /// Whether the block above/left was coded inter -- the `is_inter`
789 /// context (spec `av1_get_intra_inter_context`), a duplicate of
790 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
791 above_inter: Vec<bool>,
792 left_inter: Vec<bool>,
793 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
794 /// alphabet) the block above/left of this column/row coded, or `-1` for
795 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
796 /// functions (`mvstack::ref_ctx` family) need the real reference, not
797 /// just "was it inter" (lane-av1refs: every inter block used to be
798 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
799 /// enough).
800 above_ref: Vec<i8>,
801 left_ref: Vec<i8>,
802 /// The block above/left's *second* reference frame when it was coded
803 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
804 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
805 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
806 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
807 /// (no decode path here ever produces a compound block yet).
808 above_ref1: Vec<Option<i8>>,
809 left_ref1: Vec<Option<i8>>,
810 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
811 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
812 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
813 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
814 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
815 above_comp_group_idx: Vec<u8>,
816 left_comp_group_idx: Vec<u8>,
817 above_compound_idx: Vec<u8>,
818 left_compound_idx: Vec<u8>,
819 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
820 /// `3` = "no info": an intra neighbour or the frame's own border) of the
821 /// block above/left of this column/row -- spec
822 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
823 above_filter: Vec<[u8; 2]>,
824 left_filter: Vec<[u8; 2]>,
825 mi_cols: usize,
826 mi_rows: usize,
827 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
828 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
829 /// 7.15) never filters an 8x8 luma block whose covering coded block read
830 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
831 /// grain [`Self::record_mi`] already writes at), read back at 8x8
832 /// granularity by [`apply_cdef`] since `skip` is constant across every
833 /// mi cell one coded block covers.
834 skip_grid: Vec<bool>,
835 skip_grid_cols_mi: usize,
836 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
837 /// never splits a coded block's transform below its own size (round 2:
838 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
839 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
840 /// edge-length lookup (`apply_deblock`).
841 tx_grid: Vec<u8>,
842 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
843 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
844 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
845 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
846 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
847 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
848 /// reference onto `LAST_FRAME`'s own delta).
849 ref_grid: Vec<i8>,
850}
851
852impl Neighbours {
853 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
854 /// true (unpadded) size in 4x4 mode-info units.
855 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
856 Self {
857 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
858 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
859 above_mode: vec![DC_PRED; cols],
860 left_mode: vec![DC_PRED; rows],
861 above_side: vec![SB; cols],
862 left_side: vec![SB; rows],
863 above_side_mi: vec![SB; cols * (SUB / MI)],
864 left_side_mi: vec![SB; rows * (SUB / MI)],
865 above_skip: vec![false; cols],
866 left_skip: vec![false; rows],
867 above_skip_mode: vec![false; cols],
868 left_skip_mode: vec![false; rows],
869 above_inter: vec![false; cols],
870 left_inter: vec![false; rows],
871 above_ref: vec![-1; cols],
872 left_ref: vec![-1; rows],
873 above_ref1: vec![None; cols],
874 left_ref1: vec![None; rows],
875 above_comp_group_idx: vec![0; cols],
876 left_comp_group_idx: vec![0; rows],
877 above_compound_idx: vec![0; cols],
878 left_compound_idx: vec![0; rows],
879 above_filter: vec![[3u8; 2]; cols],
880 left_filter: vec![[3u8; 2]; rows],
881 mi_cols,
882 mi_rows,
883 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
884 skip_grid_cols_mi: cols * (SUB / MI),
885 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
886 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
887 }
888 }
889
890 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
891 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
892 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
893 /// units as [`Self::fill_skip_grid`].
894 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
895 let (mi_r, mi_c) = at_mi;
896 for rr in 0..side_mi {
897 for cc in 0..side_mi {
898 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
899 if let Some(cell) = self.tx_grid.get_mut(idx) {
900 *cell = tx_px;
901 }
902 if let Some(cell) = self.ref_grid.get_mut(idx) {
903 *cell = ref_frame;
904 }
905 }
906 }
907 }
908
909 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
910 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
911 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
912 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
913 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
914 let (mi_r, mi_c) = at_mi;
915 for rr in 0..side_mi {
916 for cc in 0..side_mi {
917 if let Some(cell) = self
918 .skip_grid
919 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
920 {
921 *cell = skip;
922 }
923 }
924 }
925 }
926
927 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
928 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
929 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
930 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
931 /// straddle the region with a mix of skip/non-skip blocks).
932 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
933 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
934 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
935 /// filtered edge's two sides are each exactly one coded block wide.
936 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
937 self.skip_grid
938 .get(mi_r * self.skip_grid_cols_mi + mi_c)
939 .copied()
940 .unwrap_or(false)
941 }
942
943 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
944 (0..2).all(|rr| {
945 (0..2).all(|cc| {
946 self.skip_grid
947 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
948 .copied()
949 .unwrap_or(false)
950 })
951 })
952 }
953
954 fn start_row(&mut self) {
955 self.left.iter_mut().for_each(|l| *l = Default::default());
956 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
957 self.left_side.iter_mut().for_each(|s| *s = SB);
958 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
959 self.left_skip.iter_mut().for_each(|s| *s = false);
960 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
961 self.left_inter.iter_mut().for_each(|i| *i = false);
962 self.left_ref.iter_mut().for_each(|r| *r = -1);
963 self.left_ref1.iter_mut().for_each(|r| *r = None);
964 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
965 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
966 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
967 }
968
969 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
970 /// block that reads it as a neighbour -- [`crate::tile`]'s
971 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
972 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
973 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
974 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
975 /// the real value, not just `is_inter`).
976 fn record_inter(
977 &mut self,
978 at: (usize, usize),
979 side: usize,
980 skip: bool,
981 is_inter: bool,
982 ref_frame: i8,
983 filter: [u8; 2],
984 skip_mode: bool,
985 ) {
986 let (r, c) = at;
987 for cell in 0..side / SUB {
988 self.above_skip[c + cell] = skip;
989 self.left_skip[r + cell] = skip;
990 self.above_skip_mode[c + cell] = skip_mode;
991 self.left_skip_mode[r + cell] = skip_mode;
992 self.above_inter[c + cell] = is_inter;
993 self.left_inter[r + cell] = is_inter;
994 self.above_ref[c + cell] = ref_frame;
995 self.left_ref[r + cell] = ref_frame;
996 // lane-av1comp: no caller of `record_inter` ever decodes a
997 // compound block yet (see [`Self::above_ref1`]'s doc); the
998 // parameter this becomes lands with `read_ref_frames`.
999 self.above_ref1[c + cell] = None;
1000 self.left_ref1[r + cell] = None;
1001 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
1002 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
1003 // as `3`/`1` even though this block has no second reference.
1004 // `record_compound_ctx` overwrites this with the real bit for an
1005 // actual compound block's cells, called right after this one.
1006 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
1007 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
1008 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
1009 self.above_compound_idx[c + cell] = u8::from(altref);
1010 self.left_compound_idx[r + cell] = u8::from(altref);
1011 self.above_filter[c + cell] = filter;
1012 self.left_filter[r + cell] = filter;
1013 }
1014 }
1015
1016 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
1017 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
1018 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
1019 /// `get_comp_index_context`) -- called right after `record_inter` for
1020 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
1021 /// stamps `above_ref1`/`left_ref1` with the block's real second
1022 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
1023 /// this is the one caller that actually knows it) -- so the next block's
1024 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
1025 /// neighbour instead of `record_inter`'s single-ref default.
1026 fn record_compound_ctx(
1027 &mut self,
1028 at: (usize, usize),
1029 side: usize,
1030 ref1: i8,
1031 comp_group_idx: u8,
1032 compound_idx: u8,
1033 ) {
1034 let (r, c) = at;
1035 for cell in 0..side / SUB {
1036 self.above_ref1[c + cell] = Some(ref1);
1037 self.left_ref1[r + cell] = Some(ref1);
1038 self.above_comp_group_idx[c + cell] = comp_group_idx;
1039 self.left_comp_group_idx[r + cell] = comp_group_idx;
1040 self.above_compound_idx[c + cell] = compound_idx;
1041 self.left_compound_idx[r + cell] = compound_idx;
1042 }
1043 }
1044
1045 /// The context of a block's partition symbol: delegates to the mi-precise
1046 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
1047 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
1048 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
1049 /// only touches the finer mi arrays -- leaves them stale for the *next*
1050 /// sibling's own partition symbol.
1051 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
1052 let (r, c) = at;
1053 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
1054 }
1055
1056 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
1057 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
1058 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
1059 /// than the enclosing 16x16 slot's stale, shared state.
1060 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
1061 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
1062 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
1063 }
1064
1065 /// The gathered coded/DC-sign state of the blocks above and to the left
1066 /// of a block `side` samples across, per plane.
1067 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
1068 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
1069 }
1070
1071 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
1072 /// units, for the same reason [`Self::record_mi`] does.
1073 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
1074 let side_mi = side / MI;
1075 std::array::from_fn(|plane| {
1076 let mut above_coded = false;
1077 let mut left_coded = false;
1078 let mut vote = 0;
1079 for cell in 0..side_mi {
1080 let above = &self.above[mi_c + cell][plane];
1081 let left = &self.left[mi_r + cell][plane];
1082 above_coded |= above.level != 0;
1083 left_coded |= left.level != 0;
1084 vote += dc_vote(above.dc) + dc_vote(left.dc);
1085 }
1086 (above_coded, left_coded, vote)
1087 })
1088 }
1089
1090 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
1091 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
1092 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
1093 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
1094 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
1095 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
1096 /// is always 0, spec's `plane_bsize == tx_size` branch).
1097 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
1098 let mut top = 0u8;
1099 let mut left = 0u8;
1100 for cell in 0..side_mi {
1101 top |= self.above[mi_c + cell][0].level;
1102 left |= self.left[mi_r + cell][0].level;
1103 }
1104 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
1105 if std::env::var_os("EC_AV1_TRACE").is_some() {
1106 eprintln!(
1107 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
1108 );
1109 }
1110 ctx
1111 }
1112
1113 /// Writes one coded block into every cell it covers, on both grids: the
1114 /// mode/side arrays up to `side`'s own width, and the coefficient-context
1115 /// arrays up to the true frame edge — the units past it are left at their
1116 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
1117 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
1118 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
1119 /// not from this block's own side).
1120 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
1121 let (r, c) = at;
1122 for cell in 0..side / SUB {
1123 self.above_mode[c + cell] = mode;
1124 self.left_mode[r + cell] = mode;
1125 self.above_side[c + cell] = side;
1126 self.left_side[r + cell] = side;
1127 }
1128 self.record_mi((r * (SUB / MI), c * (SUB / MI)), side, grids);
1129 }
1130
1131 /// The coefficient-context half of [`Self::record`], taking the block's
1132 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
1133 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
1134 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
1135 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
1136 let (mi_r, mi_c) = at_mi;
1137 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
1138 let side_mi = side / MI;
1139 for cell in 0..side_mi {
1140 self.left_side_mi[mi_r + cell] = side;
1141 self.above_side_mi[mi_c + cell] = side;
1142 }
1143 // A chroma 4x4 unit straddling the true luma edge is still whole in
1144 // chroma's own halved grid, so libaom rounds the luma bound up to the
1145 // plane's own 4x4 unit before clamping a subsampled plane
1146 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
1147 let round_up_even = |n: usize| n.div_ceil(2) * 2;
1148 let bound_h = [
1149 self.mi_rows,
1150 round_up_even(self.mi_rows),
1151 round_up_even(self.mi_rows),
1152 ];
1153 let bound_w = [
1154 self.mi_cols,
1155 round_up_even(self.mi_cols),
1156 round_up_even(self.mi_cols),
1157 ];
1158 for cell in 0..side_mi {
1159 self.left[mi_r + cell] = std::array::from_fn(|plane| {
1160 if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) {
1161 states[plane]
1162 } else {
1163 Default::default()
1164 }
1165 });
1166 self.above[mi_c + cell] = std::array::from_fn(|plane| {
1167 if cell < side_mi.min(bound_w[plane].saturating_sub(mi_c)) {
1168 states[plane]
1169 } else {
1170 Default::default()
1171 }
1172 });
1173 }
1174 }
1175
1176 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
1177 /// inside a coded block whose luma transform is smaller than its own
1178 /// side (`TxMode::Select`): the real per-transform-unit coefficient
1179 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
1180 /// coarse per-block `tx_grid`/`fill_lf_grid` state
1181 /// [`Self::record_split_luma`] still writes once for the whole block.
1182 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
1183 /// the caller's own [`Self::record_split_luma`] call sets those once,
1184 /// at the block's own true side, not this TU's.
1185 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
1186 let state = neighbour_state(grid);
1187 let side_mi = tx_px / MI;
1188 for cell in 0..side_mi {
1189 if mi_r + cell < self.mi_rows {
1190 self.left[mi_r + cell][0] = state;
1191 }
1192 if mi_c + cell < self.mi_cols {
1193 self.above[mi_c + cell][0] = state;
1194 }
1195 }
1196 }
1197
1198 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
1199 /// block whose luma was decoded as several transform units through
1200 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
1201 /// whole-block luma write -- everything [`Self::record`] does except
1202 /// plane 0, which is already correct per-TU by the time this runs.
1203 fn record_split_luma(
1204 &mut self,
1205 at: (usize, usize),
1206 side: usize,
1207 mode: usize,
1208 chroma_grids: [&[i32]; 2],
1209 ) {
1210 let (r, c) = at;
1211 for cell in 0..side / SUB {
1212 self.above_mode[c + cell] = mode;
1213 self.left_mode[r + cell] = mode;
1214 self.above_side[c + cell] = side;
1215 self.left_side[r + cell] = side;
1216 }
1217 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
1218 let side_mi = side / MI;
1219 for cell in 0..side_mi {
1220 self.left_side_mi[mi_r + cell] = side;
1221 self.above_side_mi[mi_c + cell] = side;
1222 }
1223 let round_up_even = |n: usize| n.div_ceil(2) * 2;
1224 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
1225 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
1226 let plane = plane_idx + 1;
1227 let state = neighbour_state(grid);
1228 for cell in 0..side_mi {
1229 if cell < side_mi.min(bound_h.saturating_sub(mi_r)) {
1230 self.left[mi_r + cell][plane] = state;
1231 }
1232 if cell < side_mi.min(bound_w.saturating_sub(mi_c)) {
1233 self.above[mi_c + cell][plane] = state;
1234 }
1235 }
1236 }
1237 }
1238}
1239
1240/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
1241/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
1242/// exactly — including its skip context, which the real key-frame writer
1243/// always writes at a fixed context of zero (it never tracks a neighbour-based
1244/// one for intra blocks; that is the inter-frame writer's rule instead).
1245/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
1246/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
1247/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
1248/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
1249/// plain DC chroma.
1250/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
1251/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
1252/// bound (spec `filter_intra_mode_info` never reads a symbol there).
1253fn filter_intra_size_class(side: usize) -> Option<usize> {
1254 match side {
1255 4 => Some(0),
1256 8 => Some(1),
1257 16 => Some(2),
1258 32 => Some(3),
1259 _ => None,
1260 }
1261}
1262
1263/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
1264/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
1265/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
1266/// it lands away from zero, for gate tests to prove a real stream fired one.
1267fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
1268 let symbol = dec.symbol(cdf);
1269 if symbol != ANGLE_DELTA_ZERO {
1270 ANGLE_DELTA_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1271 }
1272 symbol as i32 - ANGLE_DELTA_ZERO as i32
1273}
1274
1275fn read_intra_mode(
1276 dec: &mut SymbolDecoder,
1277 cdfs: &mut Cdfs,
1278 above_mode: usize,
1279 left_mode: usize,
1280 cfl: bool,
1281 side: usize,
1282 enable_filter_intra: bool,
1283) -> Result<(
1284 bool,
1285 usize,
1286 i32,
1287 usize,
1288 i32,
1289 Option<(i32, i32)>,
1290 Option<usize>,
1291)> {
1292 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
1293 let skip = dec.symbol(&mut cdfs.skip[0]) != 0;
1294 if trace {
1295 eprintln!("TRACE skip value={}", skip as i32);
1296 }
1297 let above_ctx = INTRA_MODE_CTX[above_mode];
1298 let left_ctx = INTRA_MODE_CTX[left_mode];
1299 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
1300 if trace {
1301 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");
1302 }
1303 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
1304 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
1305 if trace {
1306 eprintln!(
1307 "TRACE angle_delta value={}",
1308 delta + ANGLE_DELTA_ZERO as i32
1309 );
1310 }
1311 delta
1312 } else {
1313 0
1314 };
1315 let uv_mode = if cfl {
1316 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
1317 } else {
1318 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
1319 };
1320 if trace {
1321 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");
1322 }
1323 let alpha = if cfl && uv_mode == UV_CFL_PRED {
1324 Some(read_cfl_alphas(dec, cdfs))
1325 } else {
1326 None
1327 };
1328 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
1329 // from this lane's directional chroma: a corner block with neither
1330 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
1331 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
1332 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
1333 // bug in that fallback this lane's own scope does not cover. Keep it
1334 // refused here rather than ship a silently-wrong decode.
1335 if (9..=12).contains(&uv_mode) {
1336 return Err(unsupported("a smooth or paeth chroma mode (round 2)"));
1337 }
1338 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
1339 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
1340 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
1341 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
1342 // the `else` branch below and never reads one either way.
1343 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
1344 DIRECTIONAL_UV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1345 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
1346 } else {
1347 0
1348 };
1349 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
1350 // `use_filter_intra` symbol this decoder never read at all until
1351 // lane-av1real r10 -- silently skipping it left every bit past a
1352 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
1353 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
1354 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
1355 // symbol's bits were never consumed).
1356 let mut filter_intra = None;
1357 if mode == DC_PRED
1358 && enable_filter_intra
1359 && let Some(class) = filter_intra_size_class(side)
1360 {
1361 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
1362 if trace {
1363 eprintln!(
1364 "TRACE use_filter_intra side={side} value={}",
1365 use_filter_intra as i32
1366 );
1367 }
1368 if use_filter_intra {
1369 FILTER_INTRA_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1370 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
1371 if trace {
1372 eprintln!("TRACE filter_intra_mode value={fi_mode}");
1373 }
1374 filter_intra = Some(fi_mode);
1375 }
1376 }
1377 Ok((
1378 skip,
1379 mode,
1380 angle_delta_y,
1381 uv_mode,
1382 angle_delta_uv,
1383 alpha,
1384 filter_intra,
1385 ))
1386}
1387
1388/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
1389/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
1390/// intra modes.
1391const UV_CFL_PRED: usize = 13;
1392
1393/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
1394/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
1395/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
1396/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
1397/// joint sign the same way. Returns each plane's final signed `alpha_q3`
1398/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
1399fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
1400 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
1401 let sign_u = ((joint_sign + 1) * 11) >> 5;
1402 let sign_v = (joint_sign + 1) - 3 * sign_u;
1403 let alpha_u = if sign_u == 0 {
1404 0
1405 } else {
1406 let ctx_u = (joint_sign + 1 - 3) as usize;
1407 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
1408 if sign_u == 2 { mag } else { -mag }
1409 };
1410 let alpha_v = if sign_v == 0 {
1411 0
1412 } else {
1413 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
1414 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
1415 if sign_v == 2 { mag } else { -mag }
1416 };
1417 (alpha_u, alpha_v)
1418}
1419
1420/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
1421/// the reconstructed luma samples under a `side`-square block, subsampled
1422/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
1423/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
1424/// to give the AC values [`cfl_scaled`] scales by alpha.
1425fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
1426 let cside = side / 2;
1427 let mut ac = vec![0i32; cside * cside];
1428 let mut sum = 0i32;
1429 for cy in 0..cside {
1430 for cx in 0..cside {
1431 let (lx, ly) = (px + cx * 2, py + cy * 2);
1432 let q3 = (i32::from(y.data[ly * y.width + lx])
1433 + i32::from(y.data[ly * y.width + lx + 1])
1434 + i32::from(y.data[(ly + 1) * y.width + lx])
1435 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
1436 << 1;
1437 ac[cy * cside + cx] = q3;
1438 sum += q3;
1439 }
1440 }
1441 let num_pel = (cside * cside) as i32;
1442 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
1443 ac.iter_mut().for_each(|v| *v -= avg);
1444 ac
1445}
1446
1447/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
1448/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
1449/// ties away from zero on the shifted-out sign).
1450fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
1451 let v = alpha_q3 * ac_q3;
1452 if v >= 0 {
1453 (v + 32) >> 6
1454 } else {
1455 -((-v + 32) >> 6)
1456 }
1457}
1458
1459/// One plane's reconstruction buffer, `width * height` samples, and the
1460/// prediction/residual reads and writes into it — the decode-side twin of
1461/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
1462/// (own-edge and reach clamps both), passing what it gathers straight to
1463/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
1464struct PlaneBuf {
1465 data: Vec<u8>,
1466 width: usize,
1467 height: usize,
1468 /// The frame's true, decodable extent in this plane's own units — past
1469 /// this, samples are the padded coding surface's invented tail, never a
1470 /// real decoder's edge or reach reads.
1471 true_width: usize,
1472 true_height: usize,
1473}
1474
1475/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
1476/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
1477/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
1478/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
1479/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
1480/// `ALTREF2`/`ALTREF`).
1481type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
1482
1483impl PlaneBuf {
1484 fn edges(
1485 &self,
1486 x: usize,
1487 y: usize,
1488 side: usize,
1489 reach: Reach,
1490 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
1491 let own_across = x + side.min(self.true_width.saturating_sub(x));
1492 let across = if reach.above_right {
1493 own_across + side.min(self.true_width.saturating_sub(own_across))
1494 } else {
1495 own_across
1496 }
1497 .min(self.width);
1498 let own_down = y + side.min(self.true_height.saturating_sub(y));
1499 let down = if reach.below_left {
1500 own_down + side.min(self.true_height.saturating_sub(own_down))
1501 } else {
1502 own_down
1503 }
1504 .min(self.height);
1505 let above = (y > 0 && across > x)
1506 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
1507 let left = (x > 0 && down > y).then(|| {
1508 (y..down)
1509 .map(|row| self.data[row * self.width + x - 1])
1510 .collect::<Vec<_>>()
1511 });
1512 let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]);
1513 (above, left, corner)
1514 }
1515
1516 /// Predicts under `mode` then adds `residual` (side*side, raster),
1517 /// writing the clamped reconstruction back into the plane at `(x, y)`.
1518 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
1519 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
1520 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
1521 /// order (cfl.c).
1522 fn reconstruct(
1523 &mut self,
1524 x: usize,
1525 y: usize,
1526 side: usize,
1527 mode: usize,
1528 angle_delta: i32,
1529 reach: Reach,
1530 residual: &[i32],
1531 cfl: Option<(i32, &[i32])>,
1532 filter_intra: Option<usize>,
1533 ) {
1534 let (above, left, corner) = self.edges(x, y, side, reach);
1535 let mut prediction = vec![0u8; side * side];
1536 if let Some(fi_mode) = filter_intra {
1537 crate::intra::predict_filter_intra(
1538 fi_mode,
1539 above.as_deref(),
1540 left.as_deref(),
1541 corner,
1542 side,
1543 &mut prediction,
1544 );
1545 } else {
1546 // `enable_intra_edge_filter` is the sequence header's own flag
1547 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
1548 // call, never per-block) -- threading it through every
1549 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
1550 // dozen sites for a value that never changes mid-decode, so it
1551 // rides a thread-local instead (this decoder is single-threaded
1552 // per stream). `smooth_neighbor` (spec `get_intra_edge_filter_type`)
1553 // is left `false`: exact for chroma here (a smooth `uv_mode` is
1554 // refused before decode reaches this call) and a corner-cut for
1555 // luma -- ceiling is one wrong filter-strength bucket on a block
1556 // whose real neighbour predicted smooth; upgrade path is
1557 // threading `Neighbours::above_mode`/`left_mode`'s
1558 // `SMOOTH_PRED..=SMOOTH_H_PRED` membership down instead of `false`.
1559 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
1560 predict(
1561 mode as u8,
1562 angle_delta,
1563 above.as_deref(),
1564 left.as_deref(),
1565 corner,
1566 side,
1567 enable_edge_filter,
1568 false,
1569 &mut prediction,
1570 );
1571 }
1572 for row in 0..side {
1573 for col in 0..side {
1574 let idx = row * side + col;
1575 let mut base = i32::from(prediction[idx]);
1576 if let Some((alpha_q3, ac_q3)) = cfl {
1577 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
1578 }
1579 let sample = (base + residual[idx]).clamp(0, 255) as u8;
1580 self.data[(y + row) * self.width + x + col] = sample;
1581 }
1582 }
1583 }
1584}
1585
1586/// Reads one plane's transform block, reconstructs it into `plane` at
1587/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
1588#[allow(clippy::too_many_arguments)]
1589fn read_plane(
1590 dec: &mut SymbolDecoder,
1591 cdfs: &mut Cdfs,
1592 set: TxbSet,
1593 scan: &[u16],
1594 plane_idx: usize,
1595 around: (bool, bool, i32),
1596 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
1597 // it for every plane's `txb` lookup (it is what an intra transform type's
1598 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
1599 tx_mode: usize,
1600 predict_mode: usize,
1601 angle_delta: i32,
1602 reach: Reach,
1603 plane: &mut PlaneBuf,
1604 x: usize,
1605 y: usize,
1606 side: usize,
1607 tx_side: usize,
1608 base_q_idx: u8,
1609 cfl: Option<(i32, &[i32])>,
1610 filter_intra: Option<usize>,
1611 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
1612 // smaller than its own block (spec `get_txb_ctx_general`'s
1613 // `plane_bsize != tx_size` branch), carrying the already-looked-up
1614 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
1615 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
1616 // formula below.
1617 luma_skip_ctx: Option<usize>,
1618) -> Result<Vec<i32>> {
1619 let skip_ctx = if plane_idx == 0 {
1620 luma_skip_ctx.unwrap_or(0)
1621 } else {
1622 usize::from(around.0) + usize::from(around.1)
1623 };
1624 let mut coding = cdfs.txb(set, tx_mode);
1625 // Luma's `default_tx_type` is only a fallback for the sizes whose
1626 // `TxbSet` carries no symbol at all (32-point and up), which the spec
1627 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
1628 // *never* its own coded symbol (`coding.tx_type` is always `None` for
1629 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
1630 // the plane's own predicted mode (`default_intra_tx_type`) -- except
1631 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
1632 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
1633 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
1634 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
1635 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
1636 // narrows there — only `Chroma32` and up do).
1637 let default_tx_type = if plane_idx == 0 || side >= 32 {
1638 TxType::DctDct
1639 } else {
1640 default_intra_tx_type(predict_mode as u8)
1641 };
1642 let (grid, tx_type) = read_coeffs(
1643 dec,
1644 &mut coding,
1645 scan,
1646 skip_ctx,
1647 dc_sign_ctx(around.2),
1648 default_tx_type,
1649 )?;
1650 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
1651 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
1652 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
1653 // guard also assumes.
1654 let levels = if tx_side == side {
1655 grid
1656 } else {
1657 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
1658 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
1659 // keyed by that true size, not the coded corner's -- so the corner
1660 // goes into the top-left of a `side`-sized grid, not the reverse.
1661 let mut full = vec![0i32; side * side];
1662 for row in 0..tx_side {
1663 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
1664 }
1665 full
1666 };
1667 let residual = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), tx_type);
1668 if std::env::var_os("EC_AV1_TRACE").is_some() {
1669 eprintln!(
1670 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
1671 );
1672 }
1673 plane.reconstruct(
1674 x,
1675 y,
1676 side,
1677 predict_mode,
1678 angle_delta,
1679 reach,
1680 &residual,
1681 cfl,
1682 filter_intra,
1683 );
1684 Ok(if tx_side == side {
1685 residual_grid_placeholder(&levels, side)
1686 } else {
1687 levels
1688 })
1689}
1690
1691/// `record`'s neighbour state only reads whether *the coded grid* (not the
1692/// residual) has nonzero entries, so the levels this function already built
1693/// are what it wants back; this helper exists only to name that clearly at
1694/// the one call site where `tx_side == side`.
1695fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
1696 levels.to_vec()
1697}
1698
1699/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
1700/// three planes, reconstructing them into `y`/`u`/`v` and updating
1701/// `neighbours`.
1702#[allow(clippy::too_many_arguments)]
1703fn decode_block(
1704 dec: &mut SymbolDecoder,
1705 cdfs: &mut Cdfs,
1706 neighbours: &mut Neighbours,
1707 at: (usize, usize),
1708 side: usize,
1709 luma_set: TxbSet,
1710 chroma_set: TxbSet,
1711 luma_tx: usize,
1712 chroma_tx: usize,
1713 scans: (&[u16], &[u16]),
1714 cfl: bool,
1715 y: &mut PlaneBuf,
1716 u: &mut PlaneBuf,
1717 v: &mut PlaneBuf,
1718 base_q_idx: u8,
1719 enable_filter_intra: bool,
1720 scan32: &[u16],
1721 scan16: &[u16],
1722 scan8: &[u16],
1723 scan4: &[u16],
1724 tx_select: bool,
1725 reduced_tx_set: bool,
1726) -> Result<()> {
1727 let (r, c) = at;
1728 let (px, py) = (c * SUB, r * SUB);
1729 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
1730 read_intra_mode(
1731 dec,
1732 cdfs,
1733 neighbours.above_mode[c],
1734 neighbours.left_mode[r],
1735 cfl,
1736 side,
1737 enable_filter_intra,
1738 )?;
1739 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
1740 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
1741 // actual chroma-from-luma correlation, same as this decoder always did.
1742 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
1743 DC_PRED
1744 } else {
1745 uv_mode
1746 };
1747 if std::env::var_os("EC_AV1_TRACE").is_some() {
1748 eprintln!(
1749 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
1750 angle_delta_uv={angle_delta_uv}"
1751 );
1752 }
1753 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
1754 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
1755 // block, skipped or not. `logical_tx` is what the loop filter's edge
1756 // lookup and the next block's own `tx_size_context` want (the *nominal*
1757 // transform size -- 64 even for the 64x64 corner-scanned case, spec
1758 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
1759 // which only differs from it at that one corner case.
1760 let (logical_tx, coeff_tx_side) = if tx_select {
1761 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side);
1762 (resolved, if resolved == 64 { 32 } else { resolved })
1763 } else {
1764 (side, luma_tx)
1765 };
1766 let luma_set = if tx_select {
1767 txbset_for(logical_tx, reduced_tx_set)
1768 } else {
1769 luma_set
1770 };
1771 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
1772 let reach = Reach::of(side, px, py, y.width, y.height);
1773 let (cpx, cpy) = (px / 2, py / 2);
1774 let chroma_side = side / 2;
1775 if skip {
1776 // A skipped block codes no residual syntax at all (spec 5.11.34):
1777 // straight prediction, on every plane.
1778 y.reconstruct(
1779 px,
1780 py,
1781 side,
1782 mode,
1783 angle_delta_y,
1784 reach,
1785 &vec![0i32; side * side],
1786 None,
1787 filter_intra,
1788 );
1789 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
1790 u.reconstruct(
1791 cpx,
1792 cpy,
1793 chroma_side,
1794 uv_predict_mode,
1795 angle_delta_uv,
1796 reach,
1797 &vec![0i32; chroma_side * chroma_side],
1798 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
1799 None,
1800 );
1801 v.reconstruct(
1802 cpx,
1803 cpy,
1804 chroma_side,
1805 uv_predict_mode,
1806 angle_delta_uv,
1807 reach,
1808 &vec![0i32; chroma_side * chroma_side],
1809 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
1810 None,
1811 );
1812 let luma_grid = vec![0i32; side * side];
1813 let u_grid = vec![0i32; chroma_side * chroma_side];
1814 let v_grid = vec![0i32; chroma_side * chroma_side];
1815 neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);
1816 } else if !tx_select || logical_tx == side {
1817 // A single luma transform unit -- the old path, unchanged (including
1818 // the 64x64 corner case, `logical_tx == side == 64` with
1819 // `coeff_tx_side == 32`).
1820 let around = neighbours.around(at, side);
1821 let luma_grid = read_plane(
1822 dec,
1823 cdfs,
1824 luma_set,
1825 luma_scan,
1826 0,
1827 around[0],
1828 mode,
1829 mode,
1830 angle_delta_y,
1831 reach,
1832 y,
1833 px,
1834 py,
1835 side,
1836 coeff_tx_side,
1837 base_q_idx,
1838 None,
1839 filter_intra,
1840 None,
1841 )?;
1842 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
1843 let u_grid = read_plane(
1844 dec,
1845 cdfs,
1846 chroma_set,
1847 scans.1,
1848 1,
1849 around[1],
1850 mode,
1851 uv_predict_mode,
1852 angle_delta_uv,
1853 reach,
1854 u,
1855 cpx,
1856 cpy,
1857 chroma_side,
1858 chroma_tx,
1859 base_q_idx,
1860 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
1861 None,
1862 None,
1863 )?;
1864 if std::env::var_os("EC_AV1_TRACE").is_some() {
1865 eprintln!(
1866 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
1867 &u.data[cpy * u.width + cpx..][..chroma_side]
1868 );
1869 }
1870 let v_grid = read_plane(
1871 dec,
1872 cdfs,
1873 chroma_set,
1874 scans.1,
1875 2,
1876 around[2],
1877 mode,
1878 uv_predict_mode,
1879 angle_delta_uv,
1880 reach,
1881 v,
1882 cpx,
1883 cpy,
1884 chroma_side,
1885 chroma_tx,
1886 base_q_idx,
1887 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
1888 None,
1889 None,
1890 )?;
1891 neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);
1892 } else {
1893 // Several luma transform units, raster order (spec
1894 // `transform_block`'s loop): the block's resolved transform is
1895 // genuinely smaller than its own side, so each tile of it predicts
1896 // and codes independently, its own context read fresh off whatever
1897 // the earlier tiles in this same block already wrote -- the same
1898 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
1899 let n_axis = side / logical_tx;
1900 for tu_row in 0..n_axis {
1901 for tu_col in 0..n_axis {
1902 let tu_mi = (
1903 mi_r + tu_row * (logical_tx / MI),
1904 mi_c + tu_col * (logical_tx / MI),
1905 );
1906 let tu_px = px + tu_col * logical_tx;
1907 let tu_py = py + tu_row * logical_tx;
1908 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
1909 let tu_reach = Reach::of(logical_tx, tu_px, tu_py, y.width, y.height);
1910 // This transform unit's own bsize (`logical_tx`) is smaller
1911 // than the block it sits in (`side`), so `txb_skip_ctx` is
1912 // the neighbour-magnitude table, not the lone-TU 0 (spec
1913 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
1914 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
1915 let tu_grid = read_plane(
1916 dec,
1917 cdfs,
1918 luma_set,
1919 luma_scan,
1920 0,
1921 tu_around,
1922 mode,
1923 mode,
1924 angle_delta_y,
1925 tu_reach,
1926 y,
1927 tu_px,
1928 tu_py,
1929 logical_tx,
1930 logical_tx,
1931 base_q_idx,
1932 None,
1933 filter_intra,
1934 Some(tu_skip_ctx),
1935 )?;
1936 if std::env::var_os("EC_AV1_TRACE").is_some() {
1937 eprintln!(
1938 "TRACE tu_bitpos mi=({},{}) tell={}",
1939 tu_mi.0,
1940 tu_mi.1,
1941 dec.debug_bitpos()
1942 );
1943 }
1944 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
1945 }
1946 }
1947 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
1948 let chroma_around = neighbours.around(at, side);
1949 let u_grid = read_plane(
1950 dec,
1951 cdfs,
1952 chroma_set,
1953 scans.1,
1954 1,
1955 chroma_around[1],
1956 mode,
1957 uv_predict_mode,
1958 angle_delta_uv,
1959 reach,
1960 u,
1961 cpx,
1962 cpy,
1963 chroma_side,
1964 chroma_tx,
1965 base_q_idx,
1966 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
1967 None,
1968 None,
1969 )?;
1970 let v_grid = read_plane(
1971 dec,
1972 cdfs,
1973 chroma_set,
1974 scans.1,
1975 2,
1976 chroma_around[2],
1977 mode,
1978 uv_predict_mode,
1979 angle_delta_uv,
1980 reach,
1981 v,
1982 cpx,
1983 cpy,
1984 chroma_side,
1985 chroma_tx,
1986 base_q_idx,
1987 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
1988 None,
1989 None,
1990 )?;
1991 neighbours.record_split_luma(at, side, mode, [&u_grid, &v_grid]);
1992 }
1993 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
1994 neighbours.fill_lf_grid(
1995 (r * (SUB / MI), c * (SUB / MI)),
1996 side / MI,
1997 logical_tx as u8,
1998 0,
1999 );
2000 Ok(())
2001}
2002
2003/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
2004/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
2005/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
2006/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
2007/// just-decoded mode, not the enclosing slot's stale one, is the true
2008/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
2009/// units, which is what its coefficient context (finer than [`SUB`]) is read
2010/// at. Returns the mode this leaf decoded, for the caller's own
2011/// `prev_leaf`/final mode-writeback bookkeeping.
2012#[allow(clippy::too_many_arguments)]
2013fn decode_leaf8(
2014 dec: &mut SymbolDecoder,
2015 cdfs: &mut Cdfs,
2016 neighbours: &mut Neighbours,
2017 outer_at: (usize, usize),
2018 leaf_mi: (usize, usize),
2019 scans: (&[u16], &[u16]),
2020 prev_leaf: Option<((usize, usize), usize)>,
2021 y: &mut PlaneBuf,
2022 u: &mut PlaneBuf,
2023 v: &mut PlaneBuf,
2024 base_q_idx: u8,
2025 enable_filter_intra: bool,
2026 tx_select: bool,
2027 reduced_tx_set: bool,
2028) -> Result<usize> {
2029 let (r, c) = outer_at;
2030 let mut above_mode = neighbours.above_mode[c];
2031 let mut left_mode = neighbours.left_mode[r];
2032 if let Some(((pr, pc), pmode)) = prev_leaf {
2033 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
2034 above_mode = pmode;
2035 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
2036 left_mode = pmode;
2037 }
2038 }
2039 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
2040 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
2041 // `decode_block` caller at 16x16 and up.
2042 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
2043 read_intra_mode(
2044 dec,
2045 cdfs,
2046 above_mode,
2047 left_mode,
2048 true,
2049 8,
2050 enable_filter_intra,
2051 )?;
2052 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
2053 DC_PRED
2054 } else {
2055 uv_mode
2056 };
2057 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
2058 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
2059 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
2060 // transform units, same raster-order per-TU pattern `decode_block`'s
2061 // multi-TU branch runs).
2062 let resolved = if tx_select {
2063 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8)
2064 } else {
2065 8
2066 };
2067 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
2068 let reach = Reach::of(8, px, py, y.width, y.height);
2069 let (cpx, cpy) = (px / 2, py / 2);
2070 let (luma_grid, u_grid, v_grid);
2071 if skip {
2072 y.reconstruct(
2073 px,
2074 py,
2075 8,
2076 mode,
2077 angle_delta_y,
2078 reach,
2079 &vec![0i32; 64],
2080 None,
2081 filter_intra,
2082 );
2083 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
2084 u.reconstruct(
2085 cpx,
2086 cpy,
2087 4,
2088 uv_predict_mode,
2089 angle_delta_uv,
2090 reach,
2091 &vec![0i32; 16],
2092 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2093 None,
2094 );
2095 v.reconstruct(
2096 cpx,
2097 cpy,
2098 4,
2099 uv_predict_mode,
2100 angle_delta_uv,
2101 reach,
2102 &vec![0i32; 16],
2103 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2104 None,
2105 );
2106 luma_grid = vec![0i32; 64];
2107 u_grid = vec![0i32; 16];
2108 v_grid = vec![0i32; 16];
2109 } else if resolved != 4 {
2110 let around = neighbours.around_mi(leaf_mi, 8);
2111 luma_grid = read_plane(
2112 dec,
2113 cdfs,
2114 if reduced_tx_set {
2115 TxbSet::Luma8
2116 } else {
2117 TxbSet::Luma8Set1
2118 },
2119 scans.0,
2120 0,
2121 around[0],
2122 mode,
2123 mode,
2124 angle_delta_y,
2125 reach,
2126 y,
2127 px,
2128 py,
2129 8,
2130 TX8,
2131 base_q_idx,
2132 None,
2133 filter_intra,
2134 None,
2135 )?;
2136 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
2137 u_grid = read_plane(
2138 dec,
2139 cdfs,
2140 TxbSet::Chroma4,
2141 scans.1,
2142 1,
2143 around[1],
2144 mode,
2145 uv_predict_mode,
2146 angle_delta_uv,
2147 reach,
2148 u,
2149 cpx,
2150 cpy,
2151 4,
2152 TX4,
2153 base_q_idx,
2154 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2155 None,
2156 None,
2157 )?;
2158 v_grid = read_plane(
2159 dec,
2160 cdfs,
2161 TxbSet::Chroma4,
2162 scans.1,
2163 2,
2164 around[2],
2165 mode,
2166 uv_predict_mode,
2167 angle_delta_uv,
2168 reach,
2169 v,
2170 cpx,
2171 cpy,
2172 4,
2173 TX4,
2174 base_q_idx,
2175 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2176 None,
2177 None,
2178 )?;
2179 } else {
2180 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
2181 // grid of 4x4 transform units, each predicted from the leaf's own
2182 // 8x8 `mode` and reading its own fresh context off the earlier
2183 // units in this same leaf (the same per-TU pattern `decode_block`'s
2184 // multi-TU branch runs at bigger blocks).
2185 luma_grid = vec![0i32; 64];
2186 for tu_row in 0..2 {
2187 for tu_col in 0..2 {
2188 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
2189 let tu_px = px + tu_col * 4;
2190 let tu_py = py + tu_row * 4;
2191 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
2192 let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height);
2193 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
2194 let tu_grid = read_plane(
2195 dec,
2196 cdfs,
2197 if reduced_tx_set {
2198 TxbSet::Luma4
2199 } else {
2200 TxbSet::Luma4Set1
2201 },
2202 scans.1,
2203 0,
2204 tu_around,
2205 mode,
2206 mode,
2207 angle_delta_y,
2208 tu_reach,
2209 y,
2210 tu_px,
2211 tu_py,
2212 4,
2213 4,
2214 base_q_idx,
2215 None,
2216 filter_intra,
2217 Some(tu_skip_ctx),
2218 )?;
2219 if std::env::var_os("EC_AV1_TRACE").is_some() {
2220 eprintln!(
2221 "TRACE tu_bitpos mi=({},{}) tell={}",
2222 tu_mi.0,
2223 tu_mi.1,
2224 dec.debug_bitpos()
2225 );
2226 }
2227 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
2228 }
2229 }
2230 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
2231 let chroma_around = neighbours.around_mi(leaf_mi, 8);
2232 u_grid = read_plane(
2233 dec,
2234 cdfs,
2235 TxbSet::Chroma4,
2236 scans.1,
2237 1,
2238 chroma_around[1],
2239 mode,
2240 uv_predict_mode,
2241 angle_delta_uv,
2242 reach,
2243 u,
2244 cpx,
2245 cpy,
2246 4,
2247 TX4,
2248 base_q_idx,
2249 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2250 None,
2251 None,
2252 )?;
2253 v_grid = read_plane(
2254 dec,
2255 cdfs,
2256 TxbSet::Chroma4,
2257 scans.1,
2258 2,
2259 chroma_around[2],
2260 mode,
2261 uv_predict_mode,
2262 angle_delta_uv,
2263 reach,
2264 v,
2265 cpx,
2266 cpy,
2267 4,
2268 TX4,
2269 base_q_idx,
2270 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2271 None,
2272 None,
2273 )?;
2274 // `record_split_luma` expects a `record`-style `(r, c)` position in
2275 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
2276 // already in mi units, so calling it here double-scaled the
2277 // position. Plane 0 is already correct per-TU from the
2278 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
2279 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
2280 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
2281 // leaf's own 8x8 side over `MI`).
2282 let side_mi = 2;
2283 for cell in 0..side_mi {
2284 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
2285 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
2286 }
2287 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2288 let bound_h = round_up_even(neighbours.mi_rows);
2289 let bound_w = round_up_even(neighbours.mi_cols);
2290 let u_state = neighbour_state(&u_grid);
2291 let v_state = neighbour_state(&v_grid);
2292 for cell in 0..side_mi {
2293 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
2294 neighbours.left[leaf_mi.0 + cell][1] = u_state;
2295 neighbours.left[leaf_mi.0 + cell][2] = v_state;
2296 }
2297 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
2298 neighbours.above[leaf_mi.1 + cell][1] = u_state;
2299 neighbours.above[leaf_mi.1 + cell][2] = v_state;
2300 }
2301 }
2302 neighbours.fill_skip_grid(leaf_mi, 2, skip);
2303 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
2304 return Ok(mode);
2305 }
2306 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
2307 neighbours.fill_skip_grid(leaf_mi, 2, skip);
2308 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
2309 Ok(mode)
2310}
2311
2312/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
2313/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
2314/// (mod 8) reuse the same table.
2315const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
2316 [(-1, 1), (-2, 2)],
2317 [(0, 1), (-1, 2)],
2318 [(0, 1), (0, 2)],
2319 [(0, 1), (1, 2)],
2320 [(1, 1), (2, 2)],
2321 [(1, 0), (2, 1)],
2322 [(1, 0), (2, 0)],
2323 [(1, 0), (2, -1)],
2324];
2325/// A neighbour tap outside the frame's true extent -- `constrain` reads this
2326/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
2327const CDEF_VERY_LARGE: i32 = 0x4000;
2328const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
2329const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
2330
2331fn cdef_msb(x: i32) -> i32 {
2332 31 - x.leading_zeros() as i32
2333}
2334
2335/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
2336/// centre sample a filter tap is allowed to contribute.
2337fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
2338 if threshold == 0 {
2339 return 0;
2340 }
2341 let shift = (damping - cdef_msb(threshold)).max(0);
2342 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
2343}
2344
2345/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
2346/// direction of an 8x8 luma window and the variance gap between it and its
2347/// orthogonal, `sample(row, col)` reading that window's own pixels.
2348fn cdef_find_dir(sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
2349 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
2350 let mut partial = [[0i64; 15]; 8];
2351 for i in 0..8i64 {
2352 for j in 0..8i64 {
2353 let x = i64::from(sample(i as usize, j as usize)) - 128;
2354 partial[0][(i + j) as usize] += x;
2355 partial[1][(i + j / 2) as usize] += x;
2356 partial[2][i as usize] += x;
2357 partial[3][(3 + i - j / 2) as usize] += x;
2358 partial[4][(7 + i - j) as usize] += x;
2359 partial[5][(3 - i / 2 + j) as usize] += x;
2360 partial[6][j as usize] += x;
2361 partial[7][(i / 2 + j) as usize] += x;
2362 }
2363 }
2364 let mut cost = [0i64; 8];
2365 for i in 0..8usize {
2366 cost[2] += partial[2][i] * partial[2][i];
2367 cost[6] += partial[6][i] * partial[6][i];
2368 }
2369 cost[2] *= DIV_TABLE[8];
2370 cost[6] *= DIV_TABLE[8];
2371 for i in 0..7usize {
2372 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
2373 * DIV_TABLE[i + 1];
2374 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
2375 * DIV_TABLE[i + 1];
2376 }
2377 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
2378 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
2379 for i in (1..8).step_by(2) {
2380 for j in 0..5usize {
2381 cost[i] += partial[i][3 + j] * partial[i][3 + j];
2382 }
2383 cost[i] *= DIV_TABLE[8];
2384 for j in 0..3usize {
2385 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
2386 * DIV_TABLE[2 * j + 2];
2387 }
2388 }
2389 let mut best_cost = 0i64;
2390 let mut best_dir = 0usize;
2391 for (i, &c) in cost.iter().enumerate() {
2392 if c > best_cost {
2393 best_cost = c;
2394 best_dir = i;
2395 }
2396 }
2397 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
2398 (best_dir, var as i32)
2399}
2400
2401/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
2402/// (high variance gap) gets more deringing than a flat or non-directional
2403/// one, only ever applied to the luma primary strength.
2404fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
2405 if var == 0 {
2406 return 0;
2407 }
2408 let i = if var >> 6 != 0 {
2409 cdef_msb(var >> 6).min(12)
2410 } else {
2411 0
2412 };
2413 (strength * (4 + i) + 8) >> 4
2414}
2415
2416/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
2417/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
2418/// previously-filtered neighbour must never feed this block's own sum).
2419#[allow(clippy::too_many_arguments)]
2420fn cdef_filter_block(
2421 sample: impl Fn(i32, i32) -> i32,
2422 dst: &mut PlaneBuf,
2423 ox: usize,
2424 oy: usize,
2425 bw: usize,
2426 bh: usize,
2427 pri_strength: i32,
2428 sec_strength: i32,
2429 dir: usize,
2430 pri_damping: i32,
2431 sec_damping: i32,
2432 enable_primary: bool,
2433 enable_secondary: bool,
2434) {
2435 let clipping_required = enable_primary && enable_secondary;
2436 let pri_taps = CDEF_PRI_TAPS[(pri_strength & 1) as usize];
2437 for i in 0..bh {
2438 for j in 0..bw {
2439 let x = sample(i as i32, j as i32);
2440 let mut sum = 0i32;
2441 let mut max = x;
2442 let mut min = x;
2443 for k in 0..2usize {
2444 if enable_primary {
2445 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
2446 let p0 = sample(i as i32 + tr, j as i32 + tc);
2447 let p1 = sample(i as i32 - tr, j as i32 - tc);
2448 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
2449 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
2450 if clipping_required {
2451 if p0 != CDEF_VERY_LARGE {
2452 max = max.max(p0);
2453 }
2454 if p1 != CDEF_VERY_LARGE {
2455 max = max.max(p1);
2456 }
2457 min = min.min(p0).min(p1);
2458 }
2459 }
2460 if enable_secondary {
2461 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
2462 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
2463 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
2464 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
2465 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
2466 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
2467 if clipping_required {
2468 for s in [s0, s1, s2, s3] {
2469 if s != CDEF_VERY_LARGE {
2470 max = max.max(s);
2471 }
2472 }
2473 min = min.min(s0).min(s1).min(s2).min(s3);
2474 }
2475 sum += CDEF_SEC_TAPS[k]
2476 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
2477 + cdef_constrain(s1 - x, sec_strength, sec_damping)
2478 + cdef_constrain(s2 - x, sec_strength, sec_damping)
2479 + cdef_constrain(s3 - x, sec_strength, sec_damping));
2480 }
2481 }
2482 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
2483 if clipping_required {
2484 y = y.clamp(min, max);
2485 }
2486 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, 255) as u8;
2487 }
2488 }
2489}
2490
2491/// Applies CDEF (spec 7.15) to the whole reconstructed frame, over its true
2492/// (unpadded) `mi_cols`/`mi_rows` extent, before it is cropped to its display
2493/// size. `cdef_bits == 0` is this crate's only supported case so far (see the
2494/// refusal in `stream.rs`), so every 64x64 filter block always uses index 0's
2495/// strengths -- no per-block `cdef_idx` selection is implemented yet.
2496/// bisect scratch (lane-cdffwd2): dump this frame's Y/U/V exactly the way
2497/// the instrumented `aomdec` build's `EC_AV1_PREFILT_DUMP` does (raw
2498/// `true_width`x`true_height` bytes per plane, decode order, one file per
2499/// frame index), gated on env so it is zero-cost/zero-behavior off. Called
2500/// from both the key-frame and inter-frame tile decoders so the frame index
2501/// lines up with aomdec's own (which dumps unconditionally every frame).
2502fn scratch_dump_prefilt(y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
2503 let Some(base) = std::env::var_os("EC_AV1_PREFILT_DUMP_OURS") else {
2504 return;
2505 };
2506 use std::sync::atomic::{AtomicUsize, Ordering};
2507 static IDX: AtomicUsize = AtomicUsize::new(0);
2508 let idx = IDX.fetch_add(1, Ordering::SeqCst);
2509 let path = format!("{}.f{}", base.to_string_lossy(), idx);
2510 let mut out = Vec::new();
2511 for plane in [y, u, v] {
2512 for row in 0..plane.true_height {
2513 let start = row * plane.width;
2514 out.extend_from_slice(&plane.data[start..start + plane.true_width]);
2515 }
2516 }
2517 let _ = std::fs::write(path, out);
2518}
2519
2520/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
2521/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
2522/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
2523/// every block's level comes from [`LoopFilterParams::level`] plus the
2524/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
2525/// `get_filter_level`, precomputed per-block here rather than cached in a
2526/// table the way libaom's `av1_loop_filter_frame_init` does).
2527///
2528/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
2529/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
2530fn apply_deblock(
2531 y: &mut PlaneBuf,
2532 u: &mut PlaneBuf,
2533 v: &mut PlaneBuf,
2534 lf: &LoopFilterParams,
2535 n: &Neighbours,
2536) {
2537 if lf.level[0] != 0 || lf.level[1] != 0 {
2538 deblock_plane(y, 0, lf, n);
2539 }
2540 if lf.level[2] != 0 {
2541 deblock_plane(u, 1, lf, n);
2542 }
2543 if lf.level[3] != 0 {
2544 deblock_plane(v, 2, lf, n);
2545 }
2546}
2547
2548/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
2549/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
2550/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
2551/// mi unit under this decoder's assumed 4:2:0 subsampling).
2552fn plane_to_mi(chroma: bool, coord: usize) -> usize {
2553 if chroma { coord / 2 } else { coord / 4 }
2554}
2555
2556/// This plane's own transform width in pixels at the covering block, spec
2557/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
2558/// width directly; chroma halves it (this decoder's UV transform is always
2559/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
2560/// under 4:2:0 and a block that never splits its own transform).
2561fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
2562 let luma_tx = n
2563 .tx_grid
2564 .get(mi_r * n.skip_grid_cols_mi + mi_c)
2565 .copied()
2566 .unwrap_or(0) as u32;
2567 if chroma { luma_tx / 2 } else { luma_tx }
2568}
2569
2570/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
2571/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
2572/// present only when its neighbour exists inside the true frame -- whether
2573/// the block immediately above (at this block's own leftmost mi column) or
2574/// to the left (at its own topmost mi row) coded a transform at least as wide
2575/// as `own_side`.
2576fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
2577 let above = mi_r > 0 && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
2578 let left = mi_c > 0 && tx_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
2579 usize::from(above) + usize::from(left)
2580}
2581
2582/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
2583/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
2584/// the transform's own side in pixels (`side >> depth`) -- this decoder's
2585/// four square categories (8/16/32/64) each halve at most twice, matching
2586/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
2587fn read_tx_size(
2588 dec: &mut SymbolDecoder,
2589 cdfs: &mut Cdfs,
2590 n: &Neighbours,
2591 at_mi: (usize, usize),
2592 side: usize,
2593) -> usize {
2594 let ctx = tx_size_context(n, at_mi, side);
2595 let depth = match side {
2596 8 => {
2597 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
2598 }
2599 16 => {
2600 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
2601 }
2602 32 => {
2603 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
2604 }
2605 64 => {
2606 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
2607 }
2608 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
2609 };
2610 if depth != 0 {
2611 TX_DEPTH_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2612 }
2613 side >> depth
2614}
2615
2616/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
2617/// the only four sizes a `TxMode::Select` block's coded coefficient grid
2618/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
2619fn scan_for<'a>(
2620 tx_px: usize,
2621 scan32: &'a [u16],
2622 scan16: &'a [u16],
2623 scan8: &'a [u16],
2624 scan4: &'a [u16],
2625) -> &'a [u16] {
2626 match tx_px {
2627 32 => scan32,
2628 16 => scan16,
2629 8 => scan8,
2630 4 => scan4,
2631 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
2632 }
2633}
2634
2635/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
2636/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
2637/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
2638/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
2639/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
2640/// regardless of the flag (`av1_get_ext_tx_set_type`'s
2641/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
2642/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
2643/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
2644fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
2645 match tx_px {
2646 64 => TxbSet::Luma64,
2647 32 => TxbSet::Luma32,
2648 16 => TxbSet::Luma16,
2649 8 if reduced_tx_set => TxbSet::Luma8,
2650 8 => TxbSet::Luma8Set1,
2651 4 if reduced_tx_set => TxbSet::Luma4,
2652 4 => TxbSet::Luma4Set1,
2653 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
2654 }
2655}
2656
2657/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
2658/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
2659fn unit_log2(px: u32) -> i32 {
2660 if px == 0 {
2661 0
2662 } else {
2663 px.trailing_zeros() as i32 - 2
2664 }
2665}
2666
2667/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
2668/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
2669/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
2670/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
2671/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
2672/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
2673/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
2674/// block anywhere aborted the whole stream's decode before comparison).
2675fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8) -> i32 {
2676 let base = i32::from(if plane_idx == 0 {
2677 lf.level[dir]
2678 } else if plane_idx == 1 {
2679 lf.level[2]
2680 } else {
2681 lf.level[3]
2682 });
2683 if !lf.delta_enabled {
2684 return base;
2685 }
2686 let scale = 1i32 << (base >> 5);
2687 let is_inter = ref_frame != 0;
2688 let is_globalmv = ref_frame < 0;
2689 let ref_idx = ref_frame.unsigned_abs() as usize;
2690 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
2691 if is_inter {
2692 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
2693 }
2694 lvl.clamp(0, 63)
2695}
2696
2697/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
2698/// no-segmentation, no-delta-LF path and to this decoder's own invariant
2699/// that a coded block's transform is always its own full size -- so a TU
2700/// edge is always also a PU edge, and the "both sides skipped, not a PU
2701/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
2702/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
2703/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
2704fn edge_params(
2705 lf: &LoopFilterParams,
2706 n: &Neighbours,
2707 plane_idx: usize,
2708 dir: usize,
2709 chroma: bool,
2710 x0: usize,
2711 y0: usize,
2712) -> Option<(u8, i32)> {
2713 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
2714 let cur_tx = tx_px_at(n, chroma, mi_r, mi_c);
2715 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
2716 return None;
2717 }
2718 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
2719 let (pv_mi_r, pv_mi_c) = if dir == 0 {
2720 (mi_r, mi_c - 1)
2721 } else {
2722 (mi_r - 1, mi_c)
2723 };
2724 let pv_tx = tx_px_at(n, chroma, pv_mi_r, pv_mi_c);
2725 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
2726
2727 let cur_level = lf_level(lf, plane_idx, dir, cur_ref);
2728 let pv_level = lf_level(lf, plane_idx, dir, pv_ref);
2729 if cur_level == 0 && pv_level == 0 {
2730 return None;
2731 }
2732 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
2733 let len: u8 = if chroma {
2734 if dim == 0 { 4 } else { 6 }
2735 } else {
2736 [4, 8, 14, 14, 14][dim]
2737 };
2738 let level = if cur_level != 0 { cur_level } else { pv_level };
2739 DEBLOCK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2740 Some((len, level))
2741}
2742
2743/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
2744fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
2745 let sharpness = i32::from(sharpness);
2746 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
2747 let mut lim = level >> shift;
2748 if sharpness > 0 {
2749 lim = lim.min(9 - sharpness);
2750 }
2751 lim = lim.max(1);
2752 (2 * (level + 2) + lim, lim, level >> 4)
2753}
2754
2755fn sclamp(v: i32) -> i32 {
2756 v.clamp(-128, 127)
2757}
2758
2759fn round_pow2(v: i32, n: u32) -> i32 {
2760 (v + (1 << (n - 1))) >> n
2761}
2762
2763/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
2764/// fallback.
2765fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
2766 if !mask {
2767 return [p1, p0, q0, q1];
2768 }
2769 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
2770 let (ps1, ps0, qs0, qs1) = (p1 - 128, p0 - 128, q0 - 128, q1 - 128);
2771 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
2772 let filter = sclamp(outer + 3 * (qs0 - ps0));
2773 let filter1 = sclamp(filter + 4) >> 3;
2774 let filter2 = sclamp(filter + 3) >> 3;
2775 let oq0 = sclamp(qs0 - filter1) + 128;
2776 let op0 = sclamp(ps0 + filter2) + 128;
2777 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
2778 let oq1 = sclamp(qs1 - tap) + 128;
2779 let op1 = sclamp(ps1 + tap) + 128;
2780 [op1, op0, oq0, oq1]
2781}
2782
2783/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
2784/// `filter4`'s narrow taps.
2785#[allow(clippy::too_many_arguments)]
2786fn filter6(
2787 mask: bool,
2788 thresh: i32,
2789 flat: bool,
2790 p2: i32,
2791 p1: i32,
2792 p0: i32,
2793 q0: i32,
2794 q1: i32,
2795 q2: i32,
2796) -> [i32; 4] {
2797 if flat && mask {
2798 [
2799 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
2800 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
2801 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
2802 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
2803 ]
2804 } else {
2805 filter4(mask, thresh, p1, p0, q0, q1)
2806 }
2807}
2808
2809/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
2810#[allow(clippy::too_many_arguments)]
2811fn filter8(
2812 mask: bool,
2813 thresh: i32,
2814 flat: bool,
2815 p3: i32,
2816 p2: i32,
2817 p1: i32,
2818 p0: i32,
2819 q0: i32,
2820 q1: i32,
2821 q2: i32,
2822 q3: i32,
2823) -> [i32; 6] {
2824 if flat && mask {
2825 [
2826 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
2827 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
2828 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
2829 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
2830 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
2831 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
2832 ]
2833 } else {
2834 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
2835 [p2, op1, op0, oq0, oq1, q2]
2836 }
2837}
2838
2839/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
2840/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
2841/// way -- they are only ever taps here, never written).
2842#[allow(clippy::too_many_arguments)]
2843fn filter14(
2844 mask: bool,
2845 thresh: i32,
2846 flat: bool,
2847 flat2: bool,
2848 p6: i32,
2849 p5: i32,
2850 p4: i32,
2851 p3: i32,
2852 p2: i32,
2853 p1: i32,
2854 p0: i32,
2855 q0: i32,
2856 q1: i32,
2857 q2: i32,
2858 q3: i32,
2859 q4: i32,
2860 q5: i32,
2861 q6: i32,
2862) -> [i32; 12] {
2863 if flat2 && flat && mask {
2864 [
2865 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
2866 round_pow2(
2867 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
2868 4,
2869 ),
2870 round_pow2(
2871 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
2872 4,
2873 ),
2874 round_pow2(
2875 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
2876 4,
2877 ),
2878 round_pow2(
2879 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
2880 4,
2881 ),
2882 round_pow2(
2883 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
2884 4,
2885 ),
2886 round_pow2(
2887 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
2888 4,
2889 ),
2890 round_pow2(
2891 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
2892 4,
2893 ),
2894 round_pow2(
2895 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
2896 4,
2897 ),
2898 round_pow2(
2899 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
2900 4,
2901 ),
2902 round_pow2(
2903 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
2904 4,
2905 ),
2906 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
2907 ]
2908 } else {
2909 let [op2, op1, op0, oq0, oq1, oq2] =
2910 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
2911 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
2912 }
2913}
2914
2915/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
2916/// the first (`q0`) sample past the edge, `outer_stride` advances to the
2917/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
2918/// the next along the edge's own filtering direction.
2919#[allow(clippy::too_many_arguments)]
2920fn filter_edge(
2921 data: &mut [u8],
2922 base: usize,
2923 outer_stride: isize,
2924 tap_stride: isize,
2925 len: u8,
2926 level: i32,
2927 sharpness: u8,
2928) {
2929 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
2930 for i in 0..4isize {
2931 let center = (base as isize + i * outer_stride) as usize;
2932 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
2933 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
2934 match len {
2935 4 => {
2936 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
2937 let mask = (p1 - p0).abs() <= limit
2938 && (q1 - q0).abs() <= limit
2939 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
2940 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
2941 data[idx(-2)] = op1.clamp(0, 255) as u8;
2942 data[idx(-1)] = op0.clamp(0, 255) as u8;
2943 data[idx(0)] = oq0.clamp(0, 255) as u8;
2944 data[idx(1)] = oq1.clamp(0, 255) as u8;
2945 }
2946 6 => {
2947 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
2948 let mask = (p2 - p1).abs() <= limit
2949 && (p1 - p0).abs() <= limit
2950 && (q1 - q0).abs() <= limit
2951 && (q2 - q1).abs() <= limit
2952 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
2953 let flat = (p1 - p0).abs() <= 1
2954 && (q1 - q0).abs() <= 1
2955 && (p2 - p0).abs() <= 1
2956 && (q2 - q0).abs() <= 1;
2957 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
2958 data[idx(-2)] = op1.clamp(0, 255) as u8;
2959 data[idx(-1)] = op0.clamp(0, 255) as u8;
2960 data[idx(0)] = oq0.clamp(0, 255) as u8;
2961 data[idx(1)] = oq1.clamp(0, 255) as u8;
2962 }
2963 8 => {
2964 let (p3, p2, p1, p0, q0, q1, q2, q3) =
2965 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
2966 let mask = (p3 - p2).abs() <= limit
2967 && (p2 - p1).abs() <= limit
2968 && (p1 - p0).abs() <= limit
2969 && (q1 - q0).abs() <= limit
2970 && (q2 - q1).abs() <= limit
2971 && (q3 - q2).abs() <= limit
2972 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
2973 let flat = (p1 - p0).abs() <= 1
2974 && (q1 - q0).abs() <= 1
2975 && (p2 - p0).abs() <= 1
2976 && (q2 - q0).abs() <= 1
2977 && (p3 - p0).abs() <= 1
2978 && (q3 - q0).abs() <= 1;
2979 let [op2, op1, op0, oq0, oq1, oq2] =
2980 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
2981 data[idx(-3)] = op2.clamp(0, 255) as u8;
2982 data[idx(-2)] = op1.clamp(0, 255) as u8;
2983 data[idx(-1)] = op0.clamp(0, 255) as u8;
2984 data[idx(0)] = oq0.clamp(0, 255) as u8;
2985 data[idx(1)] = oq1.clamp(0, 255) as u8;
2986 data[idx(2)] = oq2.clamp(0, 255) as u8;
2987 }
2988 _ => {
2989 let (p6, p5, p4, p3, p2, p1, p0) =
2990 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
2991 let (q0, q1, q2, q3, q4, q5, q6) =
2992 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
2993 let mask = (p3 - p2).abs() <= limit
2994 && (p2 - p1).abs() <= limit
2995 && (p1 - p0).abs() <= limit
2996 && (q1 - q0).abs() <= limit
2997 && (q2 - q1).abs() <= limit
2998 && (q3 - q2).abs() <= limit
2999 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
3000 let flat = (p1 - p0).abs() <= 1
3001 && (q1 - q0).abs() <= 1
3002 && (p2 - p0).abs() <= 1
3003 && (q2 - q0).abs() <= 1
3004 && (p3 - p0).abs() <= 1
3005 && (q3 - q0).abs() <= 1;
3006 let flat2 = (p4 - p0).abs() <= 1
3007 && (q4 - q0).abs() <= 1
3008 && (p5 - p0).abs() <= 1
3009 && (q5 - q0).abs() <= 1
3010 && (p6 - p0).abs() <= 1
3011 && (q6 - q0).abs() <= 1;
3012 let out = filter14(
3013 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
3014 q6,
3015 );
3016 for (k, v) in (-6..=5isize).zip(out) {
3017 data[idx(k)] = v.clamp(0, 255) as u8;
3018 }
3019 }
3020 }
3021 }
3022}
3023
3024/// One plane's worth of spec 7.14: every vertical edge across the plane,
3025/// then every horizontal edge (the order the spec and libaom both use).
3026fn deblock_plane(plane: &mut PlaneBuf, plane_idx: usize, lf: &LoopFilterParams, n: &Neighbours) {
3027 let chroma = plane_idx != 0;
3028 let (tw, th, stride) = (plane.true_width, plane.true_height, plane.width);
3029 let mut y0 = 0usize;
3030 while y0 < th {
3031 let mut x0 = 4usize;
3032 while x0 < tw {
3033 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
3034 filter_edge(
3035 &mut plane.data,
3036 y0 * stride + x0,
3037 stride as isize,
3038 1,
3039 len,
3040 level,
3041 lf.sharpness,
3042 );
3043 }
3044 x0 += 4;
3045 }
3046 y0 += 4;
3047 }
3048 let mut x0 = 0usize;
3049 while x0 < tw {
3050 let mut y0 = 4usize;
3051 while y0 < th {
3052 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
3053 filter_edge(
3054 &mut plane.data,
3055 y0 * stride + x0,
3056 1,
3057 stride as isize,
3058 len,
3059 level,
3060 lf.sharpness,
3061 );
3062 }
3063 y0 += 4;
3064 }
3065 x0 += 4;
3066 }
3067}
3068
3069fn apply_cdef(
3070 y: &mut PlaneBuf,
3071 u: &mut PlaneBuf,
3072 v: &mut PlaneBuf,
3073 cdef: &CdefParams,
3074 skip_grid: &Neighbours,
3075) {
3076 if cdef.y_pri_strength[0] == 0
3077 && cdef.y_sec_strength[0] == 0
3078 && cdef.uv_pri_strength[0] == 0
3079 && cdef.uv_sec_strength[0] == 0
3080 {
3081 return;
3082 }
3083 let src_y = y.data.clone();
3084 let src_u = u.data.clone();
3085 let src_v = v.data.clone();
3086 let damping = i32::from(cdef.damping);
3087 let damping_uv = (damping - 1).max(0);
3088 let mut mi_r = 0usize;
3089 while mi_r < skip_grid.mi_rows {
3090 let mut mi_c = 0usize;
3091 while mi_c < skip_grid.mi_cols {
3092 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
3093 let (ox, oy) = (mi_c * 4, mi_r * 4);
3094 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
3095 let sample_y = |r: i32, c: i32| -> i32 {
3096 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
3097 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
3098 CDEF_VERY_LARGE
3099 } else {
3100 i32::from(src_y[ny as usize * y_stride + nx as usize])
3101 }
3102 };
3103 let (dir, var) = cdef_find_dir(|r, c| {
3104 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
3105 i32::from(src_y[ny * y_stride + nx])
3106 });
3107
3108 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
3109 // -- each plane zeroes the shared direction when *its own*
3110 // frame-level primary strength is 0, independent of the
3111 // per-block adjusted `t` and of the other plane's strength.
3112 let y_dir = if cdef.y_pri_strength[0] != 0 { dir } else { 0 };
3113 let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[0]), var);
3114 let enable_primary = t != 0;
3115 let enable_secondary = cdef.y_sec_strength[0] != 0;
3116 if enable_primary || enable_secondary {
3117 cdef_filter_block(
3118 sample_y,
3119 y,
3120 ox,
3121 oy,
3122 8,
3123 8,
3124 t,
3125 i32::from(cdef.y_sec_strength[0]),
3126 y_dir,
3127 damping,
3128 damping,
3129 enable_primary,
3130 enable_secondary,
3131 );
3132 }
3133
3134 let t_uv = i32::from(cdef.uv_pri_strength[0]);
3135 let uv_dir = if t_uv != 0 { dir } else { 0 };
3136 let enable_primary_uv = t_uv != 0;
3137 let enable_secondary_uv = cdef.uv_sec_strength[0] != 0;
3138 if enable_primary_uv || enable_secondary_uv {
3139 let (cox, coy) = (ox / 2, oy / 2);
3140 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
3141 let (tw, th) = (plane.true_width, plane.true_height);
3142 let stride = plane.width;
3143 let sample_uv = |r: i32, c: i32| -> i32 {
3144 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
3145 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
3146 CDEF_VERY_LARGE
3147 } else {
3148 i32::from(src_p[ny as usize * stride + nx as usize])
3149 }
3150 };
3151 cdef_filter_block(
3152 sample_uv,
3153 plane,
3154 cox,
3155 coy,
3156 4,
3157 4,
3158 t_uv,
3159 i32::from(cdef.uv_sec_strength[0]),
3160 uv_dir,
3161 damping_uv,
3162 damping_uv,
3163 enable_primary_uv,
3164 enable_secondary_uv,
3165 );
3166 }
3167 }
3168 }
3169 mi_c += 2;
3170 }
3171 mi_r += 2;
3172 }
3173}
3174
3175/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
3176/// returning the picture it reconstructs to.
3177///
3178/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
3179/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
3180/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
3181/// `compute_image_size` derives one from the other, but not losslessly: a
3182/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
3183/// what the reconstruction is cropped to on the way out, mirroring
3184/// [`crate::encode::crop_encoded`].
3185///
3186/// # Errors
3187/// Returns an error when a block's partition, mode, skip flag or transform
3188/// type is anything this decoder does not reconstruct (round 2: inter, tx
3189/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
3190/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
3191/// or when the tile payload runs out of the symbols this decode expects (a
3192/// genuinely foreign stream).
3193pub fn decode_key_frame_tile(
3194 data: &[u8],
3195 mi_cols: u32,
3196 mi_rows: u32,
3197 base_q_idx: u8,
3198 frame_width: u32,
3199 frame_height: u32,
3200 enable_filter_intra: bool,
3201 cdef: &CdefParams,
3202 loop_filter: &LoopFilterParams,
3203 tx_select: bool,
3204 reduced_tx_set: bool,
3205) -> Result<Picture> {
3206 decode_key_frame_tile_with_cdfs(
3207 data,
3208 mi_cols,
3209 mi_rows,
3210 base_q_idx,
3211 frame_width,
3212 frame_height,
3213 enable_filter_intra,
3214 false,
3215 cdef,
3216 loop_filter,
3217 None,
3218 tx_select,
3219 reduced_tx_set,
3220 )
3221 .map(|(picture, _)| picture)
3222}
3223
3224/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
3225/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
3226/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
3227/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
3228/// since a key frame's own header always forces `primary_ref_frame ==
3229/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
3230/// alongside the picture, for the caller to save into whichever reference
3231/// slots this frame's `refresh_frame_flags` names.
3232pub(crate) fn decode_key_frame_tile_with_cdfs(
3233 data: &[u8],
3234 mi_cols: u32,
3235 mi_rows: u32,
3236 base_q_idx: u8,
3237 frame_width: u32,
3238 frame_height: u32,
3239 enable_filter_intra: bool,
3240 enable_edge_filter: bool,
3241 cdef: &CdefParams,
3242 loop_filter: &LoopFilterParams,
3243 initial_cdfs: Option<Cdfs>,
3244 tx_select: bool,
3245 reduced_tx_set: bool,
3246) -> Result<(Picture, Cdfs)> {
3247 if mi_cols == 0 || mi_rows == 0 {
3248 return Err(unsupported("a frame with no mode-info grid"));
3249 }
3250 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
3251 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
3252 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
3253 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
3254 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
3255
3256 let mut y = PlaneBuf {
3257 data: vec![0u8; width * height],
3258 width,
3259 height,
3260 true_width,
3261 true_height,
3262 };
3263 let mut u = PlaneBuf {
3264 data: vec![0u8; width * height / 4],
3265 width: width / 2,
3266 height: height / 2,
3267 true_width: true_width / 2,
3268 true_height: true_height / 2,
3269 };
3270 let mut v = PlaneBuf {
3271 data: vec![0u8; width * height / 4],
3272 width: width / 2,
3273 height: height / 2,
3274 true_width: true_width / 2,
3275 true_height: true_height / 2,
3276 };
3277
3278 let scan32 = default_scan(TX32);
3279 let scan16 = default_scan(TX16);
3280 let scan8 = default_scan(TX8);
3281 let scan4 = default_scan(TX4);
3282
3283 let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
3284 if std::env::var_os("EC_AV1_TRACE").is_some() {
3285 eprintln!(
3286 "TRACE key_tile_bytes len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
3287 data.len(),
3288 &data[..data.len().min(8)]
3289 );
3290 }
3291 let mut dec = SymbolDecoder::new(data);
3292 let mut neighbours = Neighbours::new(
3293 cols32 as usize * 2,
3294 rows32 as usize * 2,
3295 mi_cols as usize,
3296 mi_rows as usize,
3297 );
3298
3299 for sb_r in 0..sb_rows {
3300 neighbours.start_row();
3301 for sb_c in 0..sb_cols {
3302 let at = (sb_r as usize * 4, sb_c as usize * 4);
3303 let ctx = neighbours.partition_ctx(at, SB);
3304 let (has_cols, has_rows) = (
3305 sb_c * SB_MI + SB_MI / 2 < mi_cols,
3306 sb_r * SB_MI + SB_MI / 2 < mi_rows,
3307 );
3308 // Recomputed at this superblock's own half (spec
3309 // `decode_partition`): a full alphabet symbol when both halves are
3310 // inside the true frame, a single gathered bit when just one is
3311 // (the superblock cannot be left whole, so this is forced split),
3312 // and nothing at all (SPLIT inferred, no bits) when neither is —
3313 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
3314 // three-way write exactly.
3315 let part = if has_cols && has_rows {
3316 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
3317 if std::env::var_os("EC_AV1_TRACE").is_some() {
3318 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
3319 }
3320 p
3321 } else {
3322 match (has_cols, has_rows) {
3323 (true, false) => {
3324 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
3325 }
3326 (false, true) => {
3327 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
3328 }
3329 _ => {}
3330 }
3331 PARTITION_SPLIT
3332 };
3333 match part {
3334 PARTITION_NONE => {
3335 decode_block(
3336 &mut dec,
3337 &mut cdfs,
3338 &mut neighbours,
3339 at,
3340 SB,
3341 TxbSet::Luma64,
3342 TxbSet::Chroma32,
3343 TX32,
3344 TX32,
3345 (&scan32, &scan32),
3346 false,
3347 &mut y,
3348 &mut u,
3349 &mut v,
3350 base_q_idx,
3351 enable_filter_intra,
3352 &scan32,
3353 &scan16,
3354 &scan8,
3355 &scan4,
3356 tx_select,
3357 reduced_tx_set,
3358 )?;
3359 }
3360 PARTITION_SPLIT => {
3361 for q in 0..4 {
3362 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
3363 if r32 >= rows32 || c32 >= cols32 {
3364 continue;
3365 }
3366 let at32 = (r32 as usize * 2, c32 as usize * 2);
3367 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
3368 let (has_cols32, has_rows32) = (
3369 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
3370 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
3371 );
3372 let part32 = if has_cols32 && has_rows32 {
3373 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
3374 if std::env::var_os("EC_AV1_TRACE").is_some() {
3375 eprintln!(
3376 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
3377 r32 * BLOCK_MI,
3378 c32 * BLOCK_MI
3379 );
3380 }
3381 p
3382 } else {
3383 match (has_cols32, has_rows32) {
3384 (true, false) => {
3385 dec.symbol_fixed(&gather(
3386 &cdfs.partition_w32[ctx32],
3387 VERT_ALIKE,
3388 ));
3389 }
3390 (false, true) => {
3391 dec.symbol_fixed(&gather(
3392 &cdfs.partition_w32[ctx32],
3393 HORZ_ALIKE,
3394 ));
3395 }
3396 _ => {}
3397 }
3398 PARTITION_SPLIT
3399 };
3400 match part32 {
3401 PARTITION_NONE => {
3402 decode_block(
3403 &mut dec,
3404 &mut cdfs,
3405 &mut neighbours,
3406 at32,
3407 BLOCK,
3408 TxbSet::Luma32,
3409 TxbSet::Chroma16,
3410 TX32,
3411 TX16,
3412 (&scan32, &scan16),
3413 true,
3414 &mut y,
3415 &mut u,
3416 &mut v,
3417 base_q_idx,
3418 enable_filter_intra,
3419 &scan32,
3420 &scan16,
3421 &scan8,
3422 &scan4,
3423 tx_select,
3424 reduced_tx_set,
3425 )?;
3426 }
3427 PARTITION_SPLIT => {
3428 for sub in 0..4 {
3429 let (sr, sc) =
3430 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
3431 if (sr as u32) * SUB_MI >= mi_rows
3432 || (sc as u32) * SUB_MI >= mi_cols
3433 {
3434 continue;
3435 }
3436 let (has_cols16, has_rows16) = (
3437 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
3438 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
3439 );
3440 let at16 = (sr, sc);
3441 let ctx16 = neighbours.partition_ctx(at16, SUB);
3442 if has_cols16 && has_rows16 {
3443 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
3444 if std::env::var_os("EC_AV1_TRACE").is_some() {
3445 eprintln!(
3446 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
3447 at16.0, at16.1
3448 );
3449 }
3450 if part16 == PARTITION_NONE {
3451 decode_block(
3452 &mut dec,
3453 &mut cdfs,
3454 &mut neighbours,
3455 at16,
3456 SUB,
3457 TxbSet::Luma16,
3458 TxbSet::Chroma8,
3459 TX16,
3460 TX8,
3461 (&scan16, &scan8),
3462 true,
3463 &mut y,
3464 &mut u,
3465 &mut v,
3466 base_q_idx,
3467 enable_filter_intra,
3468 &scan32,
3469 &scan16,
3470 &scan8,
3471 &scan4,
3472 tx_select,
3473 reduced_tx_set,
3474 )?;
3475 continue;
3476 }
3477 if part16 != PARTITION_SPLIT {
3478 return Err(unsupported(
3479 "a partition below 16x16 other than a clean split (this encoder never writes one)",
3480 ));
3481 }
3482 // A real (non-straddle) SPLIT of a
3483 // whole 16x16 into four 8x8 leaves --
3484 // the same recursion the straddle
3485 // path below already runs when the
3486 // true frame edge forces it, just
3487 // over all four positions instead of
3488 // the one or two the edge leaves.
3489 let (mi_row0, mi_col0) =
3490 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
3491 let mut prev_leaf: Option<((usize, usize), usize)> = None;
3492 for i in 0..4 {
3493 let (mr, mc) =
3494 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
3495 let leaf_mi = (mr as usize, mc as usize);
3496 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
3497 let part8 =
3498 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
3499 if std::env::var_os("EC_AV1_TRACE").is_some() {
3500 eprintln!(
3501 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
3502 );
3503 }
3504 if part8 != PARTITION_NONE {
3505 return Err(unsupported(
3506 "a partition below 8x8 (this encoder never writes one)",
3507 ));
3508 }
3509 let leaf_mode = decode_leaf8(
3510 &mut dec,
3511 &mut cdfs,
3512 &mut neighbours,
3513 at16,
3514 leaf_mi,
3515 (&scan8, &scan4),
3516 prev_leaf,
3517 &mut y,
3518 &mut u,
3519 &mut v,
3520 base_q_idx,
3521 enable_filter_intra,
3522 tx_select,
3523 reduced_tx_set,
3524 )?;
3525 prev_leaf = Some((leaf_mi, leaf_mode));
3526 }
3527 if let Some((_, mode)) = prev_leaf {
3528 neighbours.above_mode[sc] = mode;
3529 neighbours.left_mode[sr] = mode;
3530 }
3531 continue;
3532 }
3533 // The true edge falls inside this 16x16
3534 // leaf itself (mod-32==8 target sizes,
3535 // lane-av1-rect): one axis only -- an 8x8
3536 // leaf never itself straddles, so the
3537 // block splits cleanly along whichever
3538 // axis is short.
3539 if !has_cols16 && !has_rows16 {
3540 return Err(unsupported(
3541 "a 16x16 block whose true edge cuts through both \
3542 axes needs a rectangular transform this decoder \
3543 does not code yet",
3544 ));
3545 }
3546 if has_cols16 {
3547 dec.symbol_fixed(&gather(
3548 &cdfs.partition_w16[ctx16],
3549 VERT_ALIKE,
3550 ));
3551 } else {
3552 dec.symbol_fixed(&gather(
3553 &cdfs.partition_w16[ctx16],
3554 HORZ_ALIKE,
3555 ));
3556 }
3557 let (mi_row0, mi_col0) =
3558 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
3559 let leaf_positions: Vec<(u32, u32)> = (0..4)
3560 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
3561 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
3562 .collect();
3563 let mut prev_leaf: Option<((usize, usize), usize)> = None;
3564 for (mr, mc) in leaf_positions {
3565 let leaf_mi = (mr as usize, mc as usize);
3566 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
3567 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
3568 if std::env::var_os("EC_AV1_TRACE").is_some() {
3569 eprintln!(
3570 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
3571 );
3572 }
3573 if part8 != PARTITION_NONE {
3574 return Err(unsupported(
3575 "a partition below 8x8 (this encoder never writes one)",
3576 ));
3577 }
3578 let leaf_mode = decode_leaf8(
3579 &mut dec,
3580 &mut cdfs,
3581 &mut neighbours,
3582 at16,
3583 leaf_mi,
3584 (&scan8, &scan4),
3585 prev_leaf,
3586 &mut y,
3587 &mut u,
3588 &mut v,
3589 base_q_idx,
3590 enable_filter_intra,
3591 tx_select,
3592 reduced_tx_set,
3593 )?;
3594 prev_leaf = Some((leaf_mi, leaf_mode));
3595 }
3596 // `record()`'s `above_mode`/`left_mode`
3597 // write is a no-op at an 8x8 leaf's own
3598 // side, so force the write once the whole
3599 // 16x16 slot's leaves are done, from the
3600 // last leaf (mirrors the writer's r15
3601 // fix).
3602 if let Some((_, mode)) = prev_leaf {
3603 neighbours.above_mode[sc] = mode;
3604 neighbours.left_mode[sr] = mode;
3605 }
3606 }
3607 }
3608 _ => {
3609 return Err(unsupported(
3610 "a partition type this encoder never writes",
3611 ));
3612 }
3613 }
3614 }
3615 }
3616 _ => {
3617 return Err(unsupported("a partition type this encoder never writes"));
3618 }
3619 }
3620 }
3621 }
3622
3623 scratch_dump_prefilt(&y, &u, &v);
3624 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
3625 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
3626
3627 let (fw, fh) = (frame_width as usize, frame_height as usize);
3628 if fw == width && fh == height {
3629 return Ok((
3630 Picture {
3631 width,
3632 height,
3633 y: y.data,
3634 u: u.data,
3635 v: v.data,
3636 },
3637 cdfs,
3638 ));
3639 }
3640 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
3641 let mut out = Vec::with_capacity(w * h);
3642 for row in 0..h {
3643 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
3644 }
3645 out
3646 };
3647 Ok((
3648 Picture {
3649 width: fw,
3650 height: fh,
3651 y: crop(&y, fw, fh),
3652 u: crop(&u, fw / 2, fh / 2),
3653 v: crop(&v, fw / 2, fh / 2),
3654 },
3655 cdfs,
3656 ))
3657}
3658
3659/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
3660/// -- `above`/`left` are the neighbour's own resolved index for this
3661/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
3662/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
3663/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
3664/// block itself has a second reference) -- lane-av1idx: a stale "this
3665/// decoder never codes a compound reference" assumption baked this to
3666/// always-0, which desynced the CDF context bucket (not the decoded value
3667/// outright, hence small pixel deltas rather than a hard desync) the moment
3668/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
3669/// filter frame.
3670fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
3671 let base = dir * 8 + if is_compound { 4 } else { 0 };
3672 let term = if left == above {
3673 left
3674 } else if left == 3 {
3675 above
3676 } else if above == 3 {
3677 left
3678 } else {
3679 3
3680 };
3681 base + term as usize
3682}
3683
3684/// Resolves the interpolation filter kernel(s) an inter block's motion
3685/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
3686/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
3687/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
3688/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
3689/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
3690/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
3691/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
3692/// which forces `EIGHTTAP` without reading anything.
3693#[allow(clippy::too_many_arguments)]
3694fn resolve_interp_filter(
3695 dec: &mut SymbolDecoder,
3696 cdfs: &mut Cdfs,
3697 interp_fixed: Option<mc::InterpFilterKind>,
3698 enable_dual_filter: bool,
3699 force_regular: bool,
3700 above: [u8; 2],
3701 left: [u8; 2],
3702 is_compound: bool,
3703) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
3704 if let Some(kind) = interp_fixed {
3705 return (kind, kind, [3, 3]);
3706 }
3707 if force_regular {
3708 return (
3709 mc::InterpFilterKind::Regular,
3710 mc::InterpFilterKind::Regular,
3711 [0, 0],
3712 );
3713 }
3714 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
3715 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
3716 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
3717 // "horizontal then vertical" despite `predict_with_filters`' own
3718 // `h_kind`/`v_kind` argument order, which is why this function returns
3719 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
3720 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
3721 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
3722 let sym1 = if enable_dual_filter {
3723 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
3724 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
3725 } else {
3726 sym0
3727 };
3728 (
3729 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
3730 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
3731 [sym0, sym1],
3732 )
3733}
3734
3735/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
3736/// duplicating [`crate::tile`]'s private copy of the same rule.
3737pub(crate) fn intra_inter_ctx(
3738 has_above: bool,
3739 has_left: bool,
3740 above_inter: bool,
3741 left_inter: bool,
3742) -> usize {
3743 match (has_above, has_left) {
3744 (true, true) => {
3745 let (above_intra, left_intra) = (!above_inter, !left_inter);
3746 if above_intra && left_intra {
3747 3
3748 } else {
3749 usize::from(above_intra || left_intra)
3750 }
3751 }
3752 (true, false) => 2 * usize::from(!above_inter),
3753 (false, true) => 2 * usize::from(!left_inter),
3754 (false, false) => 0,
3755 }
3756}
3757
3758/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
3759/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
3760/// bits start counting from.
3761fn mv_class_base(class: usize) -> i32 {
3762 if class == 0 { 0 } else { 2i32 << (class + 2) }
3763}
3764
3765/// One motion vector component's non-zero diff (spec 5.11.32
3766/// `read_mv_component`), the inverse of [`crate::tile`]'s private
3767/// `write_mv_component`.
3768fn read_mv_component(
3769 dec: &mut SymbolDecoder,
3770 c: &mut MvComponentCdfs,
3771 allow_high_precision_mv: bool,
3772) -> i32 {
3773 let sign = dec.symbol(&mut c.sign);
3774 let class = dec.symbol(&mut c.class);
3775 let local = if class == 0 {
3776 let bit = dec.symbol(&mut c.class0_bit);
3777 let fr = dec.symbol(&mut c.class0_fr[bit]);
3778 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
3779 // high-precision motion vectors, else implicitly 1 (the low bit
3780 // stays at half-pel precision) -- this crate's own writer always
3781 // leaves the flag off, but a foreign stream can set it per frame.
3782 let hp = if allow_high_precision_mv {
3783 dec.symbol(&mut c.class0_hp)
3784 } else {
3785 1
3786 };
3787 (bit << 3) | (fr << 1) | hp
3788 } else {
3789 let mut d = 0;
3790 for i in 0..class {
3791 d |= dec.symbol(&mut c.bit[i]) << i;
3792 }
3793 let fr = dec.symbol(&mut c.fr);
3794 let hp = if allow_high_precision_mv {
3795 dec.symbol(&mut c.hp)
3796 } else {
3797 1
3798 };
3799 (d << 3) | (fr << 1) | hp
3800 };
3801 let mag = mv_class_base(class) + local as i32 + 1;
3802 if sign == 1 { -mag } else { mag }
3803}
3804
3805/// A motion vector coded as a residual against `pred` (spec 5.11.32
3806/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
3807fn read_mv(
3808 dec: &mut SymbolDecoder,
3809 mv_comp: &mut [MvComponentCdfs; 2],
3810 mv_joint: &mut [u16; 5],
3811 pred: (i32, i32),
3812 allow_high_precision_mv: bool,
3813) -> (i32, i32) {
3814 let joint = dec.symbol(mv_joint);
3815 let mut diff = (0, 0);
3816 if joint == 2 || joint == 3 {
3817 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv);
3818 }
3819 if joint == 1 || joint == 3 {
3820 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv);
3821 }
3822 (pred.0 + diff.0, pred.1 + diff.1)
3823}
3824
3825/// A 1/8-pel motion vector component converted to the 1/16-pel offset
3826/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
3827/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
3828fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
3829 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
3830}
3831
3832impl PlaneBuf {
3833 /// Adds `residual` onto an already-computed `prediction` (motion
3834 /// compensation's output, rather than [`predict`]'s intra one), writing
3835 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
3836 /// counterpart of [`PlaneBuf::reconstruct`].
3837 fn reconstruct_mc(
3838 &mut self,
3839 x: usize,
3840 y: usize,
3841 side: usize,
3842 prediction: &[u8],
3843 residual: &[i32],
3844 ) {
3845 for row in 0..side {
3846 for col in 0..side {
3847 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
3848 .clamp(0, 255) as u8;
3849 self.data[(y + row) * self.width + x + col] = sample;
3850 }
3851 }
3852 }
3853}
3854
3855/// Reads one inter-coded plane's transform block and reconstructs it by
3856/// adding its residual onto a motion-compensated `prediction` -- the inter
3857/// counterpart of [`read_plane`] (every inter transform this decoder reads is
3858/// `side`-square with no oversized-64 case, so there is no padded-grid
3859/// branch to mirror).
3860#[allow(clippy::too_many_arguments)]
3861fn read_inter_plane(
3862 dec: &mut SymbolDecoder,
3863 cdfs: &mut Cdfs,
3864 set: TxbSet,
3865 scan: &[u16],
3866 plane_idx: usize,
3867 around: (bool, bool, i32),
3868 tx_mode: usize,
3869 plane: &mut PlaneBuf,
3870 x: usize,
3871 y: usize,
3872 side: usize,
3873 base_q_idx: u8,
3874 prediction: &[u8],
3875) -> Result<Vec<i32>> {
3876 let skip_ctx = if plane_idx == 0 {
3877 0
3878 } else {
3879 usize::from(around.0) + usize::from(around.1)
3880 };
3881 let mut coding = cdfs.txb(set, tx_mode);
3882 // `av1_get_tx_type` (libaom `blockd.h`): `Intra_Mode_To_Tx_Type` only
3883 // ever applies to an intra block's chroma plane -- an `is_inter` block
3884 // (this function, [`read_inter_plane`], reads only those) has no
3885 // predicted intra mode to index it with, and its `tx_type` (luma or
3886 // chroma alike) is `DCT_DCT` whenever the `TxbSet` itself codes no
3887 // symbol for it.
3888 let default_tx_type = TxType::DctDct;
3889 let (grid, tx_type) = read_coeffs(
3890 dec,
3891 &mut coding,
3892 scan,
3893 skip_ctx,
3894 dc_sign_ctx(around.2),
3895 default_tx_type,
3896 )?;
3897 let residual = dequant_and_inverse_typed(&grid, side, 8, i32::from(base_q_idx), tx_type);
3898 plane.reconstruct_mc(x, y, side, prediction, &residual);
3899 Ok(grid)
3900}
3901
3902/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
3903/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
3904/// `reference_select` set before this is ever called, so that read is never
3905/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
3906/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
3907fn read_single_ref(
3908 dec: &mut SymbolDecoder,
3909 cdfs: &mut Cdfs,
3910 above_ref: i8,
3911 above_ref1: Option<i8>,
3912 left_ref: i8,
3913 left_ref1: Option<i8>,
3914) -> i8 {
3915 let above = (above_ref > 0).then_some(above_ref);
3916 let left = (left_ref > 0).then_some(left_ref);
3917 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
3918 let ref_frame = if p1 == 1 {
3919 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
3920 if p2 == 1 {
3921 ALTREF_FRAME
3922 } else {
3923 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
3924 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
3925 }
3926 } else {
3927 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
3928 if p3 == 1 {
3929 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
3930 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
3931 } else {
3932 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
3933 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
3934 }
3935 };
3936 if ref_frame != LAST_FRAME {
3937 NON_LAST_REF_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3938 let c = match ref_frame {
3939 LAST2_FRAME => &LAST2_HITS,
3940 LAST3_FRAME => &LAST3_HITS,
3941 GOLDEN_FRAME => &GOLDEN_HITS,
3942 BWDREF_FRAME => &BWDREF_HITS,
3943 ALTREF2_FRAME => &ALTREF2_HITS,
3944 ALTREF_FRAME => &ALTREF_HITS,
3945 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
3946 };
3947 c.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3948 }
3949 ref_frame
3950}
3951
3952/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
3953/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
3954/// `reference_select` header bit lets a block choose per-block instead of
3955/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
3956/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
3957/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
3958/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
3959/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
3960/// Resolves a compound reference's own planes -- the same `ref_frame ==
3961/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
3962/// [`decode_inter_block`]'s single-ref path already does, factored out so
3963/// the compound path can call it twice (lane-av1comp).
3964fn ref_planes<'a>(
3965 ref_frame: i8,
3966 ref_y: &'a PlaneBuf,
3967 ref_u: &'a PlaneBuf,
3968 ref_v: &'a PlaneBuf,
3969 other_refs: &'a RefSlots,
3970) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
3971 if ref_frame == LAST_FRAME {
3972 Ok((ref_y, ref_u, ref_v))
3973 } else {
3974 match other_refs[ref_frame as usize] {
3975 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
3976 None => Err(unsupported(
3977 "a reference frame selected with no picture at this frame's own \
3978 ref_frame_idx slot for it",
3979 )),
3980 }
3981 }
3982}
3983
3984/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
3985/// the square block sizes this decoder ever decodes (32/16/8, all
3986/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
3987/// always `is_interinter_compound_used`, so the function is always `true`
3988/// for `side` -- kept as a named call (rather than inlined `true`) so a
3989/// future sub-8 block size does not silently misdecode a real stream.
3990fn is_any_masked_compound_used_here(side: usize) -> bool {
3991 side.min(side) >= 8
3992}
3993
3994/// Whether a compound reference pair is unidirectional (both references on
3995/// the same temporal side of the current frame) -- `has_uni_comp_refs`
3996/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
3997/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
3998/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
3999/// is_backward(ref1)`). Used to build a real
4000/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
4001/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
4002fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
4003 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
4004 backward(ref0) == backward(ref1)
4005}
4006
4007/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
4008/// above/left neighbour contributions [`Neighbours::record_inter`]/
4009/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
4010fn get_comp_group_idx_context(neighbours: &Neighbours, at: (usize, usize), side: usize) -> usize {
4011 let _ = side;
4012 let (r, c) = at;
4013 (neighbours.above_comp_group_idx[c] as usize + neighbours.left_comp_group_idx[r] as usize)
4014 .min(5)
4015}
4016
4017/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
4018/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
4019/// block's own two references' distances from the current frame (spec
4020/// 7.11.3.15's `get_relative_dist`, same convention
4021/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
4022#[allow(clippy::too_many_arguments)]
4023fn get_comp_index_context(
4024 neighbours: &Neighbours,
4025 at: (usize, usize),
4026 side: usize,
4027 order_hint_bits: u32,
4028 cur_order_hint: u32,
4029 ref0_order_hint: u32,
4030 ref1_order_hint: u32,
4031) -> usize {
4032 let _ = side;
4033 let (r, c) = at;
4034 let fwd =
4035 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
4036 .abs();
4037 let bck =
4038 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
4039 .abs();
4040 let offset = usize::from(fwd == bck);
4041 neighbours.above_compound_idx[c] as usize
4042 + neighbours.left_compound_idx[r] as usize
4043 + 3 * offset
4044}
4045
4046fn read_comp_mode(
4047 dec: &mut SymbolDecoder,
4048 cdfs: &mut Cdfs,
4049 above: Option<NeighbourRef>,
4050 left: Option<NeighbourRef>,
4051) -> bool {
4052 let ctx = reference_mode_ctx(above, left);
4053 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
4054 if compound {
4055 COMP_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4056 }
4057 compound
4058}
4059
4060/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
4061/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
4062/// arm), reached once [`read_comp_mode`] has already returned
4063/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
4064/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
4065/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
4066/// convention [`read_single_ref`] already uses, for every downstream binary
4067/// decision. libaom `pred_common.c`'s own compound context functions
4068/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
4069/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
4070/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
4071/// (same vote-the-neighbours-above-left shape, same forward/backward and
4072/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
4073/// against the C source rather than porting six near-duplicate functions.
4074/// Its caller today only needs the symbols consumed, correctly, to keep the
4075/// arithmetic decoder's own state in sync before refusing the block by name
4076/// -- the returned pair is not yet threaded into any motion-compensation
4077/// path.
4078fn read_compound_ref_frames(
4079 dec: &mut SymbolDecoder,
4080 cdfs: &mut Cdfs,
4081 above: Option<NeighbourRef>,
4082 left: Option<NeighbourRef>,
4083 above_ref: i8,
4084 left_ref: i8,
4085) -> (i8, i8) {
4086 let a = (above_ref > 0).then_some(above_ref);
4087 let l = (left_ref > 0).then_some(left_ref);
4088 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
4089 // neighbour's references, not just its first -- `a1`/`l1` carry that
4090 // second reference through to every vote below (lane-av1blend r6: a
4091 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
4092 // row for a block sitting under a skip_mode-forced compound neighbour).
4093 let a1 = above.and_then(|n| n.ref1);
4094 let l1 = left.and_then(|n| n.ref1);
4095 let type_ctx = comp_reference_type_ctx(above, left);
4096 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
4097 if unidir {
4098 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
4099 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
4100 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
4101 if bit == 1 {
4102 (BWDREF_FRAME, ALTREF_FRAME)
4103 } else {
4104 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
4105 if p1 == 1 {
4106 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
4107 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
4108 if p2 == 1 {
4109 (LAST_FRAME, GOLDEN_FRAME)
4110 } else {
4111 (LAST_FRAME, LAST3_FRAME)
4112 }
4113 } else {
4114 (LAST_FRAME, LAST2_FRAME)
4115 }
4116 }
4117 } else {
4118 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
4119 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
4120 let ref0 = if bit0 == 0 {
4121 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
4122 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
4123 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
4124 } else {
4125 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
4126 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
4127 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
4128 };
4129 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
4130 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
4131 let ref1 = if bit1 == 0 {
4132 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
4133 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
4134 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
4135 } else {
4136 ALTREF_FRAME
4137 };
4138 (ref0, ref1)
4139 }
4140}
4141
4142/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
4143/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
4144/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
4145/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
4146/// libaom's `av1_mode_context_analyzer`'s compound branch --
4147/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
4148/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
4149/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
4150/// is not yet turned into an assigned MV pair or motion-compensated --
4151/// lane-av1comp.
4152fn read_inter_compound_mode(
4153 dec: &mut SymbolDecoder,
4154 cdfs: &mut Cdfs,
4155 new_mv_ctx: usize,
4156 ref_mv_ctx: usize,
4157) -> u8 {
4158 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
4159 COMPOUND_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4160 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
4161}
4162
4163/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
4164/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
4165/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
4166/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
4167/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
4168/// non-`IDENTITY` global motion model before a tile is ever decoded.
4169///
4170/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
4171/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
4172/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
4173/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
4174/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
4175fn assign_compound_mv(
4176 dec: &mut SymbolDecoder,
4177 cdfs: &mut Cdfs,
4178 comp_stack: &crate::mvstack::CompoundMvStack,
4179 mode: u8,
4180 allow_high_precision_mv: bool,
4181) -> ((i32, i32), (i32, i32)) {
4182 const NEAREST_NEARESTMV: u8 = 0;
4183 const NEAR_NEARMV: u8 = 1;
4184 const NEAREST_NEWMV: u8 = 2;
4185 const NEW_NEARESTMV: u8 = 3;
4186 const NEAR_NEWMV: u8 = 4;
4187 const NEW_NEARMV: u8 = 5;
4188 const GLOBAL_GLOBALMV: u8 = 6;
4189 const NEW_NEWMV: u8 = 7;
4190
4191 let mut ref_mv_idx = 0usize;
4192 if mode == NEW_NEWMV {
4193 let mut idx = 0usize;
4194 while idx < 2 && comp_stack.entries.len() > idx + 1 {
4195 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
4196 break;
4197 }
4198 idx += 1;
4199 }
4200 ref_mv_idx = idx;
4201 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
4202 let mut idx = 1usize;
4203 while idx < 3 && comp_stack.entries.len() > idx + 1 {
4204 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
4205 break;
4206 }
4207 idx += 1;
4208 }
4209 ref_mv_idx = idx - 1;
4210 }
4211
4212 let near = comp_stack
4213 .entries
4214 .get(ref_mv_idx + 1)
4215 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
4216 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
4217 ref_mv_idx + 1
4218 } else {
4219 ref_mv_idx
4220 };
4221 let new_pred = comp_stack
4222 .entries
4223 .get(new_idx)
4224 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
4225
4226 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
4227 read_mv(
4228 dec,
4229 &mut cdfs.mv_comp,
4230 &mut cdfs.mv_joint,
4231 base,
4232 allow_high_precision_mv,
4233 )
4234 };
4235
4236 match mode {
4237 NEAREST_NEARESTMV => comp_stack.nearest_mv,
4238 NEAR_NEARMV => near,
4239 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
4240 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
4241 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
4242 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
4243 GLOBAL_GLOBALMV => ((0, 0), (0, 0)),
4244 _ => (
4245 read_new(dec, cdfs, new_pred.0),
4246 read_new(dec, cdfs, new_pred.1),
4247 ),
4248 }
4249}
4250
4251/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
4252/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
4253/// and motion-compensated reconstruction, or the inter frame's own intra
4254/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
4255/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
4256/// private `write_inter_frame_leaf` -- both share this one function here,
4257/// parameterised by `side`/the transform sets/scan tables/size group they
4258/// each use.
4259///
4260/// # Errors
4261/// Returns an error when a symbol names anything this decoder does not
4262/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
4263/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
4264/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
4265/// refuse.
4266#[allow(clippy::too_many_arguments)]
4267fn decode_inter_block(
4268 dec: &mut SymbolDecoder,
4269 cdfs: &mut Cdfs,
4270 neighbours: &mut Neighbours,
4271 grid: &mut MiGrid,
4272 at: (usize, usize),
4273 side: usize,
4274 mi_cols: u32,
4275 mi_rows: u32,
4276 y: &mut PlaneBuf,
4277 u: &mut PlaneBuf,
4278 v: &mut PlaneBuf,
4279 ref_y: &PlaneBuf,
4280 ref_u: &PlaneBuf,
4281 ref_v: &PlaneBuf,
4282 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
4283 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
4284 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
4285 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
4286 // slot's still empty (an error-resilient stream, or too early in the
4287 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
4288 other_refs: &RefSlots,
4289 sign_bias_table: &SignBiasTable,
4290 base_q_idx: u8,
4291 luma_set_intra: TxbSet,
4292 luma_set_inter: TxbSet,
4293 chroma_set: TxbSet,
4294 luma_tx: usize,
4295 chroma_tx: usize,
4296 scan_luma: &[u16],
4297 scan_chroma: &[u16],
4298 size_group: usize,
4299 allow_high_precision_mv: bool,
4300 interp_fixed: Option<mc::InterpFilterKind>,
4301 enable_dual_filter: bool,
4302 tpl_frame: Option<&TplFrameArgs>,
4303 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
4304 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
4305 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
4306 // refuses (rather than silently misdecoding) the ones that pick
4307 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
4308 // wired yet.
4309 reference_select: bool,
4310 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
4311 // compound enable bits, gating `comp_group_idx`/`compound_idx`
4312 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
4313 // compound blend weights need this frame's own order hint regardless
4314 // of `use_ref_frame_mvs`.
4315 enable_masked_compound: bool,
4316 enable_jnt_comp: bool,
4317 order_hint_bits: u32,
4318 order_hint: u32,
4319 ref_order_hints: [u32; 7],
4320 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
4321 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
4322 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
4323 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
4324 // when this is `true` (every block this decoder reaches is >= 8x8, so
4325 // `is_comp_ref_allowed` never gates it further); a `true` result forces
4326 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
4327 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
4328 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
4329 skip_mode_present: bool,
4330 skip_mode_frame: [u8; 2],
4331) -> Result<()> {
4332 let (r, c) = at;
4333 let (px, py) = (c * SUB, r * SUB);
4334 let (cpx, cpy) = (px / 2, py / 2);
4335 let chroma_side = side / 2;
4336
4337 let skip_mode_ctx =
4338 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
4339 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
4340 if skip_mode {
4341 SKIP_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4342 }
4343
4344 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
4345 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
4346
4347 let (has_above, has_left) = (r > 0, c > 0);
4348 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);
4349 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
4350 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
4351
4352 let mode_for_tx;
4353 let (luma_grid, u_grid, v_grid);
4354 let block_filter;
4355 let ref_frame_for_lf;
4356 let globalmv_for_lf;
4357 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
4358 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
4359 // common `record_inter` call below (which would otherwise stamp the
4360 // single-ref ALTREF-special-case default over it).
4361 let mut compound_ctx: Option<(i8, u8, u8)> = None;
4362 if is_inter {
4363 let above_nbr = has_above.then(|| NeighbourRef {
4364 is_inter: above_inter,
4365 ref0: if above_inter {
4366 neighbours.above_ref[c]
4367 } else {
4368 0
4369 },
4370 ref1: neighbours.above_ref1[c],
4371 uni: neighbours.above_ref1[c]
4372 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[c], r1)),
4373 });
4374 let left_nbr = has_left.then(|| NeighbourRef {
4375 is_inter: left_inter,
4376 ref0: if left_inter {
4377 neighbours.left_ref[r]
4378 } else {
4379 0
4380 },
4381 ref1: neighbours.left_ref1[r],
4382 uni: neighbours.left_ref1[r]
4383 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[r], r1)),
4384 });
4385 let is_compound =
4386 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
4387 if is_compound {
4388 let (ref0, ref1) = if skip_mode {
4389 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
4390 } else {
4391 read_compound_ref_frames(
4392 dec,
4393 cdfs,
4394 above_nbr,
4395 left_nbr,
4396 neighbours.above_ref[c],
4397 neighbours.left_ref[r],
4398 )
4399 };
4400 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
4401 let bw4 = side / 4;
4402 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
4403 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
4404 // below, just one `get_relative_dist` per reference.
4405 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
4406 field: t.field,
4407 cur_offset_0: crate::motion_field::get_relative_dist(
4408 t.order_hint_bits,
4409 t.order_hint,
4410 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
4411 ),
4412 cur_offset_1: crate::motion_field::get_relative_dist(
4413 t.order_hint_bits,
4414 t.order_hint,
4415 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
4416 ),
4417 allow_high_precision_mv,
4418 });
4419 let comp_stack = crate::mvstack::find_mv_stack_compound(
4420 grid,
4421 mi_row,
4422 mi_col,
4423 bw4,
4424 bw4,
4425 (ref0, ref1),
4426 mi_cols as usize,
4427 mi_rows as usize,
4428 sign_bias_table,
4429 comp_tpl,
4430 );
4431 let compound_mode = if skip_mode {
4432 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
4433 } else {
4434 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
4435 };
4436 let (mv0, mv1) = assign_compound_mv(
4437 dec,
4438 cdfs,
4439 &comp_stack,
4440 compound_mode,
4441 allow_high_precision_mv,
4442 );
4443 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
4444 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
4445 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
4446 // spec `get_ref_filter_type`: matches when EITHER of the
4447 // neighbour's two references equals this block's own ref0 --
4448 // `above_ref1`/`left_ref1` is the neighbour's real second
4449 // reference (`record_compound_ctx`) when it was itself a
4450 // compound block; checking `above_ref`/`left_ref` alone drops a
4451 // real filter match down to the "no neighbour" sentinel
4452 // whenever the shared reference sits in the neighbour's SECOND
4453 // slot (lane-av1idx r2).
4454 let above_filter_ctx = if neighbours.above_ref[c] == ref0
4455 || neighbours.above_ref1[c] == Some(ref0)
4456 {
4457 neighbours.above_filter[c]
4458 } else {
4459 [3, 3]
4460 };
4461 let left_filter_ctx = if neighbours.left_ref[r] == ref0
4462 || neighbours.left_ref1[r] == Some(ref0)
4463 {
4464 neighbours.left_filter[r]
4465 } else {
4466 [3, 3]
4467 };
4468 globalmv_for_lf = is_globalmv;
4469 ref_frame_for_lf = ref0;
4470 mode_for_tx = 0;
4471 for dr in 0..bw4 {
4472 for dc in 0..bw4 {
4473 grid.set(
4474 mi_row + dr,
4475 mi_col + dc,
4476 MiInfo {
4477 is_inter: true,
4478 ref_frame: ref0,
4479 ref_frame1: Some(ref1),
4480 mv1: Some(mv1),
4481 mv: mv0,
4482 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
4483 size: bw4,
4484 },
4485 );
4486 }
4487 }
4488 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
4489 // masked compound / distance-weighted compound are actually
4490 // enabled for this stream -- `is_any_masked_compound_used_here`
4491 // is `true` for every block size this decoder ever reaches
4492 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
4493 // there), so the gate reduces to the sequence header bit; kept
4494 // as an explicit call so a future smaller block size is not
4495 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
4496 let group_ctx = get_comp_group_idx_context(neighbours, at, side);
4497 let comp_group_idx = if !skip_mode
4498 && enable_masked_compound
4499 && is_any_masked_compound_used_here(side)
4500 {
4501 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
4502 } else {
4503 0
4504 };
4505 if comp_group_idx == 1 {
4506 return Err(unsupported(
4507 "a masked COMPOUND_REFERENCE block (comp_group_idx == 1, wedge/\
4508 diffwtd) -- this decoder's compound blend is the plain distance-\
4509 weighted/simple-average combine only, lane-av1comp",
4510 ));
4511 }
4512 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
4513 // called this a `predict_compound_intermediate`/`combine_compound`
4514 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
4515 // unmasking and running the real gates
4516 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
4517 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
4518 // shows the plain-average blend is bit-exact *most of the time*
4519 // -- `combine_compound`'s two-shift-in-one round2 was proven
4520 // algebraically identical to libaom's separate
4521 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
4522 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
4523 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
4524 // the common case a lag-in-frames GOP's hidden altref frames
4525 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
4526 // for several consecutive frames.
4527 //
4528 // The real defect a live gate run isolated (seed 49,
4529 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
4530 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
4531 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
4532 // byte; decode-order frame 2 -- same shape, same zero MV, only
4533 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
4534 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
4535 // Every later frame up through decode-order 9 also mismatches,
4536 // *including* frame 8, whose four blocks are back to
4537 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
4538 // math is wrong" (that block's own math is proven exact) in
4539 // favour of "the picture sitting in some DPB slot is already
4540 // wrong by the time frame 2 reads it, and the corruption
4541 // propagates through refresh_frame_flags into every later
4542 // reference regardless of which named ref a later block picks".
4543 // Frames 10 through 18 (once the GOP's lineage stops tracing
4544 // back through the bad slot) are bit-exact again. This points at
4545 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
4546 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
4547 // indexing feeding `dist_wtd_comp_weight_assign`) around
4548 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
4549 // mc.rs. Not isolated further within lane-av1blend's budget --
4550 // refuse by name rather than ship a blend that is right only
4551 // sometimes. Ceiling: r13/r14's MC plumbing above this line
4552 // stays -- only the plain-average reconstruct is masked off
4553 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
4554 // per decode-order frame (which slot each `Frame` OBU refreshes,
4555 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
4556 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
4557 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
4558 // frame 2.
4559 //
4560 // r2 (fresh fixture, seed 45, same recipe -- the original r1
4561 // fixture is gitignored and could not be regenerated byte-exact):
4562 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
4563 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
4564 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
4565 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
4566 // is forced 0 on every non-key `show_existing_frame`) turned up
4567 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
4568 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
4569 // isolated a *different, smaller* shape than r1's: decode-order
4570 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
4571 // compound block) is the first to diverge from ffmpeg (worst
4572 // delta 1, luma only, clustered at 32-pixel block edges) even
4573 // though BOTH its compound inputs -- the key frame and
4574 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
4575 // itself proven bit-exact: it is later re-shown via
4576 // `show_existing_frame` and matches ffmpeg exactly) -- are
4577 // independently pixel-exact, and the blend arithmetic is the
4578 // same proven-exact formula. That rules out "wrong slot"/"stale
4579 // picture" for this fixture: the inputs are right, so the defect
4580 // is in decode-order frame 3's *own* per-block decode (entropy
4581 // desync from compound-CDF adaptation carried across a slot, or
4582 // the compound mode/MV read itself) -- not in `ref_slots`/
4583 // `refresh_frame_flags`. Not isolated further within budget.
4584 // Upgrade: bisect decode-order frame 3's tile decode against a
4585 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
4586 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
4587 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
4588 // -- the pre-deblock dump frame-index alignment between this
4589 // crate and that aomdec build is NOT 1:1 on this fixture (23
4590 // dumps here vs 24 there), so calibrate that first.
4591 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
4592 // against an instrumented aomdec build (frame-index alignment
4593 // recalibrated via content-hash matching rather than the raw
4594 // dump count -- the keyframe never calls a pre-deblock dump at
4595 // all, since only `decode_inter_frame_tile` does, which is the
4596 // whole "23 vs 24" gap, not a real bug).
4597 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
4598 // seed 45) is still the first divergence: PRE-deblock differs
4599 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
4600 // luma pixels, clustered where its two compound inputs' pixel
4601 // values disagree by more than a couple of levels -- both
4602 // inputs (the keyframe and decode-order frame 2's own picture)
4603 // are independently proven bit-exact (pre- and post-deblock)
4604 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
4605 // matches this decoder's block loop exactly for every block in
4606 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
4607 // every mismatching pixel against `key`/`bwd` (both known-exact)
4608 // picks out `w0=9, w1=7` for the majority (525/846) with zero
4609 // matches for the plain average this decoder actually emits or
4610 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
4611 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
4612 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
4613 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
4614 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
4615 // decoder's own `dist_wtd_comp_weight_assign` was independently
4616 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
4617 // by hand for these distances and gives the same `(9, 7)`).
4618 // `get_comp_index_context` was checked line-for-line against
4619 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
4620 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
4621 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
4622 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
4623 // `default_compound_idx_cdfs` value-for-value; the read is
4624 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
4625 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
4626 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
4627 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
4628 // either -- some blocks in this frame plausibly decode a
4629 // genuinely different (correct, context-dependent) compound_idx
4630 // than block (0,0)'s own -- so this is not simply "always wrong
4631 // the same way": table/context/gate are all individually
4632 // verified correct, yet the decoded VALUE at this specific
4633 // symbol is wrong at least once in this frame. Not isolated
4634 // further within budget. Upgrade: instrument `dec.symbol`'s own
4635 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
4636 // trace fields) immediately before and after the `compound_idx`
4637 // read specifically, not just the surrounding mode/mv/skip
4638 // trace which does match -- the desync (if any) is local to
4639 // this one read, not a wider stream desync.
4640 //
4641 // r5 (this round): the `resolve_interp_filter` call used to sit
4642 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
4643 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
4644 // `read_compound_type`, not before, so that was a genuine
4645 // ordering bug for a Switchable-filter frame (moved below, past
4646 // the `compound_ctx = Some(...)` line). It does NOT explain this
4647 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
4648 // header carries a *fixed* interpolation filter
4649 // (`interp_fixed = Some(Regular)`, confirmed live via a
4650 // one-off dump), so `resolve_interp_filter` never read a symbol
4651 // in either position -- zero bits moved, decoded values
4652 // unchanged before and after the reorder. Kept anyway: it is a
4653 // real spec-order fix for the next Switchable-filter compound
4654 // stream, independently correct regardless of this fixture.
4655 //
4656 // Also ruled out this round: comparing this crate's own
4657 // `SymbolDecoder::debug_bitpos()` against aomdec's
4658 // `aom_reader_tell()` at the block boundary is NOT a valid
4659 // desync probe -- they are different quantities (raw consumed
4660 // input bits vs. an entropy-cost estimate that advances without
4661 // a literal byte fetch), so equal/unequal bitpos proves nothing
4662 // either way. Do not repeat that comparison; instead trace
4663 // `range`/`value` (this crate) against libaom's own internal
4664 // `dif`/`rng` (needs new instrumentation in both) immediately
4665 // after each read *upstream* of this one in the same block:
4666 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
4667 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
4668 // and the DRL loop. All of those independently decoded the SAME
4669 // values this crate and aomdec both show (ref0=1, ref1=5, mode
4670 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
4671 // miscomputation can still decode the identical symbol value off
4672 // a slightly different CDF, narrowing `range` by a different
4673 // amount than aomdec without changing the decoded value itself,
4674 // and only surface as a wrong decode a few reads later exactly
4675 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
4676 // table were independently re-verified again this round and are
4677 // still correct; the four candidates above were not re-audited
4678 // this round. Refusing here (rather than shipping a value-exact-
4679 // most-of-the-time blend) until one of them is found wrong.
4680 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
4681 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
4682 // comp_bwdref* context reads -- kept, real fix). Unmasking on
4683 // that fix alone and running the wide gate sweep (many seeds,
4684 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
4685 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
4686 // cq-level=45) still mismatches roughly half the time, at
4687 // different frames each run for the SAME seed -- aomenc's own
4688 // cpu-used=0 RD search is run-to-run nondeterministic (noted
4689 // above), so this is a second, still-unfound compound_idx defect,
4690 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
4691 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
4692 // either) already flagged more than one bug here. Re-masking:
4693 // do not ship a blend that is right only sometimes.
4694 // lane-av1idx r1: fixed one real bug this round
4695 // (`switchable_interp_ctx` never folded in libaom's
4696 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
4697 // interp_filter context -- kept). Pinned
4698 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
4699 // gate) still mismatches after that fix (decode-order frame 8
4700 // first, small deltas, worst 1-2, propagating through later
4701 // frames via DPB reference) -- a second, still-unfound bug.
4702 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
4703 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
4704 // for the next round's starting point.
4705 let (fwd_offset, bck_offset, compound_idx) = if !skip_mode && enable_jnt_comp {
4706 let idx_ctx = get_comp_index_context(
4707 neighbours,
4708 at,
4709 side,
4710 order_hint_bits,
4711 order_hint,
4712 ref_order_hints[(ref0 - LAST_FRAME) as usize],
4713 ref_order_hints[(ref1 - LAST_FRAME) as usize],
4714 );
4715 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
4716 if idx == 1 {
4717 (8, 8, 1u8)
4718 } else {
4719 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
4720 order_hint_bits,
4721 order_hint,
4722 ref_order_hints[(ref0 - LAST_FRAME) as usize],
4723 ref_order_hints[(ref1 - LAST_FRAME) as usize],
4724 );
4725 (fwd, bck, 0u8)
4726 }
4727 } else {
4728 (8, 8, 1u8)
4729 };
4730 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
4731
4732 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
4733 // comes AFTER `read_compound_type` (the `comp_group_idx`/
4734 // `compound_idx` reads just above), not before -- moved here
4735 // (lane-av1blend r5) from its old position ahead of those reads,
4736 // which stole their bits for a Switchable-filter compound block
4737 // and desynced every symbol read after it in the tile.
4738 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
4739 dec,
4740 cdfs,
4741 interp_fixed,
4742 enable_dual_filter,
4743 is_globalmv,
4744 above_filter_ctx,
4745 left_filter_ctx,
4746 true,
4747 );
4748 block_filter = resolved_filter;
4749
4750 let mut inter0_y = vec![0i32; side * side];
4751 mc::predict_compound_intermediate(
4752 &py0.data,
4753 py0.width,
4754 py0.true_width,
4755 py0.true_height,
4756 mv_to_q4(px, mv0.1, true),
4757 mv_to_q4(py, mv0.0, true),
4758 side,
4759 side,
4760 h_filter,
4761 v_filter,
4762 &mut inter0_y,
4763 );
4764 let mut inter1_y = vec![0i32; side * side];
4765 mc::predict_compound_intermediate(
4766 &py1.data,
4767 py1.width,
4768 py1.true_width,
4769 py1.true_height,
4770 mv_to_q4(px, mv1.1, true),
4771 mv_to_q4(py, mv1.0, true),
4772 side,
4773 side,
4774 h_filter,
4775 v_filter,
4776 &mut inter1_y,
4777 );
4778 let mut pred_y = vec![0u8; side * side];
4779 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
4780
4781 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
4782 mc::predict_compound_intermediate(
4783 &pu0.data,
4784 pu0.width,
4785 pu0.true_width,
4786 pu0.true_height,
4787 mv_to_q4(cpx, mv0.1, false),
4788 mv_to_q4(cpy, mv0.0, false),
4789 chroma_side,
4790 chroma_side,
4791 h_filter,
4792 v_filter,
4793 &mut inter0_u,
4794 );
4795 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
4796 mc::predict_compound_intermediate(
4797 &pu1.data,
4798 pu1.width,
4799 pu1.true_width,
4800 pu1.true_height,
4801 mv_to_q4(cpx, mv1.1, false),
4802 mv_to_q4(cpy, mv1.0, false),
4803 chroma_side,
4804 chroma_side,
4805 h_filter,
4806 v_filter,
4807 &mut inter1_u,
4808 );
4809 let mut pred_u = vec![0u8; chroma_side * chroma_side];
4810 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
4811
4812 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
4813 mc::predict_compound_intermediate(
4814 &pv0.data,
4815 pv0.width,
4816 pv0.true_width,
4817 pv0.true_height,
4818 mv_to_q4(cpx, mv0.1, false),
4819 mv_to_q4(cpy, mv0.0, false),
4820 chroma_side,
4821 chroma_side,
4822 h_filter,
4823 v_filter,
4824 &mut inter0_v,
4825 );
4826 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
4827 mc::predict_compound_intermediate(
4828 &pv1.data,
4829 pv1.width,
4830 pv1.true_width,
4831 pv1.true_height,
4832 mv_to_q4(cpx, mv1.1, false),
4833 mv_to_q4(cpy, mv1.0, false),
4834 chroma_side,
4835 chroma_side,
4836 h_filter,
4837 v_filter,
4838 &mut inter1_v,
4839 );
4840 let mut pred_v = vec![0u8; chroma_side * chroma_side];
4841 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
4842
4843 if skip {
4844 y.reconstruct_mc(px, py, side, &pred_y, &vec![0i32; side * side]);
4845 u.reconstruct_mc(
4846 cpx,
4847 cpy,
4848 chroma_side,
4849 &pred_u,
4850 &vec![0i32; chroma_side * chroma_side],
4851 );
4852 v.reconstruct_mc(
4853 cpx,
4854 cpy,
4855 chroma_side,
4856 &pred_v,
4857 &vec![0i32; chroma_side * chroma_side],
4858 );
4859 luma_grid = vec![0i32; side * side];
4860 u_grid = vec![0i32; chroma_side * chroma_side];
4861 v_grid = vec![0i32; chroma_side * chroma_side];
4862 } else {
4863 let around = neighbours.around(at, side);
4864 luma_grid = read_inter_plane(
4865 dec,
4866 cdfs,
4867 luma_set_inter,
4868 scan_luma,
4869 0,
4870 around[0],
4871 mode_for_tx,
4872 y,
4873 px,
4874 py,
4875 side,
4876 base_q_idx,
4877 &pred_y,
4878 )?;
4879 u_grid = read_inter_plane(
4880 dec,
4881 cdfs,
4882 chroma_set,
4883 scan_chroma,
4884 1,
4885 around[1],
4886 mode_for_tx,
4887 u,
4888 cpx,
4889 cpy,
4890 chroma_side,
4891 base_q_idx,
4892 &pred_u,
4893 )?;
4894 v_grid = read_inter_plane(
4895 dec,
4896 cdfs,
4897 chroma_set,
4898 scan_chroma,
4899 2,
4900 around[2],
4901 mode_for_tx,
4902 v,
4903 cpx,
4904 cpy,
4905 chroma_side,
4906 base_q_idx,
4907 &pred_v,
4908 )?;
4909 }
4910 } else {
4911 let ref_frame =
4912 read_single_ref(
4913 dec,
4914 cdfs,
4915 neighbours.above_ref[c],
4916 neighbours.above_ref1[c],
4917 neighbours.left_ref[r],
4918 neighbours.left_ref1[r],
4919 );
4920 ref_frame_for_lf = ref_frame;
4921 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
4922 // stacked defects (lf_level ref/mode-delta forwarding, the
4923 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
4924 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
4925 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
4926 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
4927 // widens this from GOLDEN alone to every reference `read_single_ref`
4928 // can name.
4929 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
4930 (ref_y, ref_u, ref_v)
4931 } else {
4932 match other_refs[ref_frame as usize] {
4933 Some((ry, ru, rv)) => (ry, ru, rv),
4934 None => {
4935 return Err(unsupported(
4936 "a reference frame selected with no picture at this frame's own \
4937 ref_frame_idx slot for it",
4938 ));
4939 }
4940 }
4941 };
4942
4943 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
4944 let bw4 = side / 4;
4945 // spec 7.10.2.8: only reached when the frame header set
4946 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
4947 // otherwise) -- `cur_offset_0` is this query block's own resolved
4948 // `ref_frame`'s distance from the current frame (spec 7.9.3),
4949 // recomputed per block since different blocks pick different refs.
4950 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
4951 field: t.field,
4952 cur_offset_0: crate::motion_field::get_relative_dist(
4953 t.order_hint_bits,
4954 t.order_hint,
4955 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
4956 ),
4957 allow_high_precision_mv,
4958 });
4959 let stack = find_mv_stack_with_sign_bias(
4960 grid,
4961 mi_row,
4962 mi_col,
4963 bw4,
4964 bw4,
4965 ref_frame,
4966 mi_cols as usize,
4967 mi_rows as usize,
4968 sign_bias_table,
4969 tpl,
4970 );
4971 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
4972 let mut is_globalmv = false;
4973 let (mv, is_new_mv) = if !not_new {
4974 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
4975 // read at most two `drl_mode` bits, one per stack entry past the
4976 // first, stopping at the first `0`. The chosen index selects
4977 // which stack entry `read_mv`'s base predictor comes from
4978 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
4979 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
4980 let mut idx = 0usize;
4981 while idx < 2 && stack.entries.len() > idx + 1 {
4982 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
4983 break;
4984 }
4985 idx += 1;
4986 }
4987 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
4988 (
4989 read_mv(
4990 dec,
4991 &mut cdfs.mv_comp,
4992 &mut cdfs.mv_joint,
4993 base_mv,
4994 allow_high_precision_mv,
4995 ),
4996 true,
4997 )
4998 } else {
4999 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
5000 is_globalmv = !not_zero;
5001 let mv = if !not_zero {
5002 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1) under the
5003 // `GmType::IDENTITY` this crate's `decode_stream` requires of
5004 // every inter frame's `LAST_FRAME` entry (any other warp
5005 // model is refused before the tile decoder is ever called).
5006 (0, 0)
5007 } else {
5008 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
5009 if nearest {
5010 stack.nearest_mv
5011 } else {
5012 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
5013 // at 1): read at most two more `drl_mode` bits, one per stack
5014 // entry past the second, stopping at the first `0`.
5015 // `drl_ctx[idx]` is the context between `entries[idx]` and
5016 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
5017 // exactly the pair this index is choosing between.
5018 let mut idx = 1usize;
5019 while idx < 3 && stack.entries.len() > idx + 1 {
5020 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
5021 break;
5022 }
5023 idx += 1;
5024 }
5025 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
5026 }
5027 };
5028 (mv, false)
5029 };
5030 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
5031 // this block's switchable_interp context when that neighbour coded
5032 // the SAME reference frame this block is about to read -- a
5033 // different-ref neighbour reads as "no neighbour" ([3, 3], the
5034 // sentinel `Neighbours::new` already seeds unset slots with),
5035 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
5036 // block next to a LAST_FRAME one inherits that neighbour's filter
5037 // choice into its own context, corrupting the symbol it reads.
5038 // lane-av1idx r2: also match on the neighbour's SECOND reference
5039 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
5040 // see the 16x16 leaf's own comment above for the spec citation.
5041 let above_filter_ctx = if neighbours.above_ref[c] == ref_frame
5042 || neighbours.above_ref1[c] == Some(ref_frame)
5043 {
5044 neighbours.above_filter[c]
5045 } else {
5046 [3, 3]
5047 };
5048 let left_filter_ctx = if neighbours.left_ref[r] == ref_frame
5049 || neighbours.left_ref1[r] == Some(ref_frame)
5050 {
5051 neighbours.left_filter[r]
5052 } else {
5053 [3, 3]
5054 };
5055 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
5056 dec,
5057 cdfs,
5058 interp_fixed,
5059 enable_dual_filter,
5060 is_globalmv,
5061 above_filter_ctx,
5062 left_filter_ctx,
5063 false,
5064 );
5065 block_filter = resolved_filter;
5066 globalmv_for_lf = is_globalmv;
5067 if std::env::var_os("EC_AV1_TRACE").is_some() {
5068 eprintln!(
5069 "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side} ref={ref_frame} filter={:?}",
5070 skip as u8, mv.0, mv.1, block_filter
5071 );
5072 }
5073 for dr in 0..bw4 {
5074 for dc in 0..bw4 {
5075 grid.set(
5076 mi_row + dr,
5077 mi_col + dc,
5078 MiInfo {
5079 is_inter: true,
5080 ref_frame,
5081 ref_frame1: None,
5082 mv1: None,
5083 mv,
5084 is_new_mv,
5085 size: bw4,
5086 },
5087 );
5088 }
5089 }
5090 mode_for_tx = 0;
5091
5092 let mut pred_y = vec![0u8; side * side];
5093 mc::predict_with_filters(
5094 &py_ref.data,
5095 py_ref.width,
5096 py_ref.true_width,
5097 py_ref.true_height,
5098 mv_to_q4(px, mv.1, true),
5099 mv_to_q4(py, mv.0, true),
5100 side,
5101 side,
5102 h_filter,
5103 v_filter,
5104 &mut pred_y,
5105 );
5106 let mut pred_u = vec![0u8; chroma_side * chroma_side];
5107 mc::predict_with_filters(
5108 &pu_ref.data,
5109 pu_ref.width,
5110 pu_ref.true_width,
5111 pu_ref.true_height,
5112 mv_to_q4(cpx, mv.1, false),
5113 mv_to_q4(cpy, mv.0, false),
5114 chroma_side,
5115 chroma_side,
5116 h_filter,
5117 v_filter,
5118 &mut pred_u,
5119 );
5120 let mut pred_v = vec![0u8; chroma_side * chroma_side];
5121 mc::predict_with_filters(
5122 &pv_ref.data,
5123 pv_ref.width,
5124 pv_ref.true_width,
5125 pv_ref.true_height,
5126 mv_to_q4(cpx, mv.1, false),
5127 mv_to_q4(cpy, mv.0, false),
5128 chroma_side,
5129 chroma_side,
5130 h_filter,
5131 v_filter,
5132 &mut pred_v,
5133 );
5134
5135 if skip {
5136 y.reconstruct_mc(px, py, side, &pred_y, &vec![0i32; side * side]);
5137 u.reconstruct_mc(
5138 cpx,
5139 cpy,
5140 chroma_side,
5141 &pred_u,
5142 &vec![0i32; chroma_side * chroma_side],
5143 );
5144 v.reconstruct_mc(
5145 cpx,
5146 cpy,
5147 chroma_side,
5148 &pred_v,
5149 &vec![0i32; chroma_side * chroma_side],
5150 );
5151 luma_grid = vec![0i32; side * side];
5152 u_grid = vec![0i32; chroma_side * chroma_side];
5153 v_grid = vec![0i32; chroma_side * chroma_side];
5154 } else {
5155 let around = neighbours.around(at, side);
5156 luma_grid = read_inter_plane(
5157 dec,
5158 cdfs,
5159 luma_set_inter,
5160 scan_luma,
5161 0,
5162 around[0],
5163 mode_for_tx,
5164 y,
5165 px,
5166 py,
5167 side,
5168 base_q_idx,
5169 &pred_y,
5170 )?;
5171 u_grid = read_inter_plane(
5172 dec,
5173 cdfs,
5174 chroma_set,
5175 scan_chroma,
5176 1,
5177 around[1],
5178 mode_for_tx,
5179 u,
5180 cpx,
5181 cpy,
5182 chroma_side,
5183 base_q_idx,
5184 &pred_u,
5185 )?;
5186 v_grid = read_inter_plane(
5187 dec,
5188 cdfs,
5189 chroma_set,
5190 scan_chroma,
5191 2,
5192 around[2],
5193 mode_for_tx,
5194 v,
5195 cpx,
5196 cpy,
5197 chroma_side,
5198 base_q_idx,
5199 &pred_v,
5200 )?;
5201 }
5202 }
5203 } else {
5204 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
5205 if mode >= 13 {
5206 return Err(unsupported(
5207 "an intra mode this decoder does not code (round 2)",
5208 ));
5209 }
5210 if (V_PRED..=D67_PRED).contains(&mode) {
5211 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
5212 if angle != ANGLE_DELTA_ZERO {
5213 return Err(unsupported(
5214 "a nonzero angle delta (this encoder never writes one)",
5215 ));
5216 }
5217 }
5218 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
5219 let alpha = if uv_mode == DC_PRED {
5220 None
5221 } else if uv_mode == UV_CFL_PRED {
5222 Some(read_cfl_alphas(dec, cdfs))
5223 } else {
5224 return Err(unsupported("a directional chroma mode (round 2)"));
5225 };
5226 mode_for_tx = mode;
5227 block_filter = [3, 3];
5228 ref_frame_for_lf = 0;
5229 globalmv_for_lf = false;
5230 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
5231 for dr in 0..side / 4 {
5232 for dc in 0..side / 4 {
5233 grid.set(
5234 mi_row + dr,
5235 mi_col + dc,
5236 MiInfo {
5237 is_inter: false,
5238 ref_frame: -1,
5239 ref_frame1: None,
5240 mv1: None,
5241 mv: (0, 0),
5242 is_new_mv: false,
5243 size: side / 4,
5244 },
5245 );
5246 }
5247 }
5248
5249 let reach = Reach::of(side, px, py, y.width, y.height);
5250 if skip {
5251 y.reconstruct(
5252 px,
5253 py,
5254 side,
5255 mode,
5256 0,
5257 reach,
5258 &vec![0i32; side * side],
5259 None,
5260 None,
5261 );
5262 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
5263 u.reconstruct(
5264 cpx,
5265 cpy,
5266 chroma_side,
5267 DC_PRED,
5268 0,
5269 reach,
5270 &vec![0i32; chroma_side * chroma_side],
5271 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5272 None,
5273 );
5274 v.reconstruct(
5275 cpx,
5276 cpy,
5277 chroma_side,
5278 DC_PRED,
5279 0,
5280 reach,
5281 &vec![0i32; chroma_side * chroma_side],
5282 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5283 None,
5284 );
5285 luma_grid = vec![0i32; side * side];
5286 u_grid = vec![0i32; chroma_side * chroma_side];
5287 v_grid = vec![0i32; chroma_side * chroma_side];
5288 } else {
5289 let around = neighbours.around(at, side);
5290 luma_grid = read_plane(
5291 dec,
5292 cdfs,
5293 luma_set_intra,
5294 scan_luma,
5295 0,
5296 around[0],
5297 mode,
5298 mode,
5299 0,
5300 reach,
5301 y,
5302 px,
5303 py,
5304 side,
5305 luma_tx,
5306 base_q_idx,
5307 None,
5308 None,
5309 None,
5310 )?;
5311 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
5312 u_grid = read_plane(
5313 dec,
5314 cdfs,
5315 chroma_set,
5316 scan_chroma,
5317 1,
5318 around[1],
5319 mode,
5320 DC_PRED,
5321 0,
5322 reach,
5323 u,
5324 cpx,
5325 cpy,
5326 chroma_side,
5327 chroma_tx,
5328 base_q_idx,
5329 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5330 None,
5331 None,
5332 )?;
5333 v_grid = read_plane(
5334 dec,
5335 cdfs,
5336 chroma_set,
5337 scan_chroma,
5338 2,
5339 around[2],
5340 mode,
5341 DC_PRED,
5342 0,
5343 reach,
5344 v,
5345 cpx,
5346 cpy,
5347 chroma_side,
5348 chroma_tx,
5349 base_q_idx,
5350 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5351 None,
5352 None,
5353 )?;
5354 }
5355 }
5356 neighbours.record(at, side, mode_for_tx, &[luma_grid, u_grid, v_grid]);
5357 neighbours.record_inter(at, side, skip, is_inter, ref_frame_for_lf, block_filter, skip_mode);
5358 if let Some((ref1, group_idx, idx)) = compound_ctx {
5359 neighbours.record_compound_ctx(at, side, ref1, group_idx, idx);
5360 }
5361 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
5362 neighbours.fill_lf_grid(
5363 (r * (SUB / MI), c * (SUB / MI)),
5364 side / MI,
5365 side as u8,
5366 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
5367 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
5368 if globalmv_for_lf {
5369 -ref_frame_for_lf
5370 } else {
5371 ref_frame_for_lf
5372 },
5373 );
5374 Ok(())
5375}
5376
5377/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
5378/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
5379/// exact symbol order: its own skip flag, intra/inter choice and (when
5380/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
5381/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
5382/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
5383/// same as [`decode_leaf8`]'s coefficient layer but with
5384/// motion-compensated prediction instead of intra prediction when inter.
5385/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
5386/// skip/intra-inter context, overridden by `prev_leaf` exactly as
5387/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
5388/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
5389/// and intra/inter choice, for the next leaf or the caller's final
5390/// write-back.
5391#[allow(clippy::too_many_arguments)]
5392fn decode_inter_block8(
5393 dec: &mut SymbolDecoder,
5394 cdfs: &mut Cdfs,
5395 neighbours: &mut Neighbours,
5396 grid: &mut MiGrid,
5397 mi_cols: u32,
5398 mi_rows: u32,
5399 outer_at: (usize, usize),
5400 leaf_mi: (usize, usize),
5401 y: &mut PlaneBuf,
5402 u: &mut PlaneBuf,
5403 v: &mut PlaneBuf,
5404 ref_y: &PlaneBuf,
5405 ref_u: &PlaneBuf,
5406 ref_v: &PlaneBuf,
5407 other_refs: &RefSlots,
5408 base_q_idx: u8,
5409 scan8: &[u16],
5410 scan4: &[u16],
5411 prev_leaf: Option<((usize, usize), bool, bool)>,
5412 allow_high_precision_mv: bool,
5413 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
5414 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
5415 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
5416 // context uses that same approximation.
5417 reference_select: bool,
5418 enable_masked_compound: bool,
5419 enable_jnt_comp: bool,
5420 order_hint_bits: u32,
5421 order_hint: u32,
5422 ref_order_hints: [u32; 7],
5423 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
5424 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
5425 // so its `skip_mode` context reuses the same [`SUB`]-grid
5426 // `above_skip_mode[c]`/`left_skip_mode[r]` the enclosing 16x16 slot
5427 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
5428 // just above).
5429 skip_mode_present: bool,
5430 skip_mode_frame: [u8; 2],
5431 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
5432 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
5433 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
5434 // `compound_ctx` local, just handed back instead of applied here (this
5435 // fn's `neighbours` recording happens once for the whole straddling
5436 // 16x16 block, after every leaf).
5437) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>)> {
5438 const LAST_FRAME: i8 = 1;
5439 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
5440 const SIZE_GROUP_8: usize = 1;
5441
5442 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
5443 let (cpx, cpy) = (px / 2, py / 2);
5444 const SIDE: usize = 8;
5445 const CHROMA_SIDE: usize = 4;
5446
5447 let (r, c) = outer_at;
5448 let mut above_skip = neighbours.above_skip[c];
5449 let mut left_skip = neighbours.left_skip[r];
5450 let mut above_inter = neighbours.above_inter[c];
5451 let mut left_inter = neighbours.left_inter[r];
5452 if let Some(((pr, pc), pskip, pinter)) = prev_leaf {
5453 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
5454 above_skip = pskip;
5455 above_inter = pinter;
5456 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
5457 left_skip = pskip;
5458 left_inter = pinter;
5459 }
5460 }
5461 let skip_mode_ctx =
5462 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
5463 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
5464 if skip_mode {
5465 SKIP_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5466 }
5467
5468 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
5469 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
5470
5471 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);
5472 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
5473 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
5474
5475 let mode_for_tx;
5476 let (luma_grid, u_grid, v_grid);
5477 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
5478 if is_inter {
5479 if reference_select || skip_mode {
5480 let above_nbr = has_above.then(|| NeighbourRef {
5481 is_inter: above_inter,
5482 ref0: if above_inter { LAST_FRAME } else { 0 },
5483 ref1: None,
5484 uni: false,
5485 });
5486 let left_nbr = has_left.then(|| NeighbourRef {
5487 is_inter: left_inter,
5488 ref0: if left_inter { LAST_FRAME } else { 0 },
5489 ref1: None,
5490 uni: false,
5491 });
5492 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
5493 let (ref0, ref1) = if skip_mode {
5494 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
5495 } else {
5496 read_compound_ref_frames(
5497 dec,
5498 cdfs,
5499 above_nbr,
5500 left_nbr,
5501 if has_above && above_inter {
5502 LAST_FRAME
5503 } else {
5504 -1
5505 },
5506 if has_left && left_inter {
5507 LAST_FRAME
5508 } else {
5509 -1
5510 },
5511 )
5512 };
5513 let (mi_row, mi_col) = leaf_mi;
5514 // lane-av1comp: this leaf path has neither a real sign-bias
5515 // table nor `tpl_frame` (see this function's own doc on the
5516 // coarse `LAST_FRAME`-or-intra neighbour approximation
5517 // already in force above), matching the plain `find_mv_stack`
5518 // (no bias, no tpl) the leaf's single-ref arm below already
5519 // uses.
5520 let comp_stack = crate::mvstack::find_mv_stack_compound(
5521 grid,
5522 mi_row,
5523 mi_col,
5524 2,
5525 2,
5526 (ref0, ref1),
5527 mi_cols as usize,
5528 mi_rows as usize,
5529 &NO_SIGN_BIAS,
5530 None,
5531 );
5532 let compound_mode = if skip_mode {
5533 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
5534 } else {
5535 read_inter_compound_mode(
5536 dec,
5537 cdfs,
5538 comp_stack.new_mv_ctx,
5539 comp_stack.ref_mv_ctx,
5540 )
5541 };
5542 let (mv0, mv1) = assign_compound_mv(
5543 dec,
5544 cdfs,
5545 &comp_stack,
5546 compound_mode,
5547 allow_high_precision_mv,
5548 );
5549
5550 // spec 5.11.25: same gating [`decode_inter_block`]'s own
5551 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
5552 // slot -- the only granularity `Neighbours`' comp_group_idx/
5553 // compound_idx arrays track.
5554 let group_ctx = get_comp_group_idx_context(neighbours, outer_at, SIDE);
5555 let comp_group_idx = if !skip_mode
5556 && enable_masked_compound
5557 && is_any_masked_compound_used_here(SIDE)
5558 {
5559 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
5560 } else {
5561 0
5562 };
5563 if comp_group_idx == 1 {
5564 return Err(unsupported(
5565 "a masked COMPOUND_REFERENCE 8x8 leaf (comp_group_idx == 1, wedge/\
5566 diffwtd) -- this decoder's compound blend is the plain distance-\
5567 weighted/simple-average combine only, lane-av1comp",
5568 ));
5569 }
5570 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
5571 // reference-slot defect as the 16x16 leaf's own mask above
5572 // (r1: falsified as an MC/blend math bug, isolated to a DPB
5573 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
5574 // that comment.
5575 // r3: same defect as the 16x16 leaf's own mask above -- see
5576 // that comment (compound_idx's decoded value, not the blend
5577 // math or reference-slot bookkeeping). r6/r7: same re-mask
5578 // as the 16x16 leaf above -- one real bug found and fixed
5579 // (mvstack.rs ref_ctx family), a second, still-unfound
5580 // compound_idx defect surfaces on the wide gate sweep.
5581 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
5582 // see that comment.
5583 let (fwd_offset, bck_offset, compound_idx) = if !skip_mode && enable_jnt_comp {
5584 let idx_ctx = get_comp_index_context(
5585 neighbours,
5586 outer_at,
5587 SIDE,
5588 order_hint_bits,
5589 order_hint,
5590 ref_order_hints[(ref0 - LAST_FRAME) as usize],
5591 ref_order_hints[(ref1 - LAST_FRAME) as usize],
5592 );
5593 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
5594 if idx == 1 {
5595 (8, 8, 1u8)
5596 } else {
5597 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
5598 order_hint_bits,
5599 order_hint,
5600 ref_order_hints[(ref0 - LAST_FRAME) as usize],
5601 ref_order_hints[(ref1 - LAST_FRAME) as usize],
5602 );
5603 (fwd, bck, 0u8)
5604 }
5605 } else {
5606 (8, 8, 1u8)
5607 };
5608 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
5609
5610 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
5611 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
5612
5613 for dr in 0..2 {
5614 for dc in 0..2 {
5615 grid.set(
5616 mi_row + dr,
5617 mi_col + dc,
5618 MiInfo {
5619 is_inter: true,
5620 ref_frame: ref0,
5621 ref_frame1: Some(ref1),
5622 mv1: Some(mv1),
5623 mv: mv0,
5624 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
5625 size: 2,
5626 },
5627 );
5628 }
5629 }
5630 mode_for_tx = 0;
5631
5632 // lane-av1comp corner-cut, matching this leaf's single-ref
5633 // arm below (`mc::predict`'s own fixed-Regular default):
5634 // `decode_inter_block8` never resolves a switchable filter,
5635 // so both compound taps use `Regular` too.
5636 use mc::InterpFilterKind::Regular;
5637 let mut inter0_y = vec![0i32; SIDE * SIDE];
5638 mc::predict_compound_intermediate(
5639 &py0.data,
5640 py0.width,
5641 py0.true_width,
5642 py0.true_height,
5643 mv_to_q4(px, mv0.1, true),
5644 mv_to_q4(py, mv0.0, true),
5645 SIDE,
5646 SIDE,
5647 Regular,
5648 Regular,
5649 &mut inter0_y,
5650 );
5651 let mut inter1_y = vec![0i32; SIDE * SIDE];
5652 mc::predict_compound_intermediate(
5653 &py1.data,
5654 py1.width,
5655 py1.true_width,
5656 py1.true_height,
5657 mv_to_q4(px, mv1.1, true),
5658 mv_to_q4(py, mv1.0, true),
5659 SIDE,
5660 SIDE,
5661 Regular,
5662 Regular,
5663 &mut inter1_y,
5664 );
5665 let mut pred_y = vec![0u8; SIDE * SIDE];
5666 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
5667
5668 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5669 mc::predict_compound_intermediate(
5670 &pu0.data,
5671 pu0.width,
5672 pu0.true_width,
5673 pu0.true_height,
5674 mv_to_q4(cpx, mv0.1, false),
5675 mv_to_q4(cpy, mv0.0, false),
5676 CHROMA_SIDE,
5677 CHROMA_SIDE,
5678 Regular,
5679 Regular,
5680 &mut inter0_u,
5681 );
5682 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5683 mc::predict_compound_intermediate(
5684 &pu1.data,
5685 pu1.width,
5686 pu1.true_width,
5687 pu1.true_height,
5688 mv_to_q4(cpx, mv1.1, false),
5689 mv_to_q4(cpy, mv1.0, false),
5690 CHROMA_SIDE,
5691 CHROMA_SIDE,
5692 Regular,
5693 Regular,
5694 &mut inter1_u,
5695 );
5696 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
5697 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
5698
5699 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5700 mc::predict_compound_intermediate(
5701 &pv0.data,
5702 pv0.width,
5703 pv0.true_width,
5704 pv0.true_height,
5705 mv_to_q4(cpx, mv0.1, false),
5706 mv_to_q4(cpy, mv0.0, false),
5707 CHROMA_SIDE,
5708 CHROMA_SIDE,
5709 Regular,
5710 Regular,
5711 &mut inter0_v,
5712 );
5713 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5714 mc::predict_compound_intermediate(
5715 &pv1.data,
5716 pv1.width,
5717 pv1.true_width,
5718 pv1.true_height,
5719 mv_to_q4(cpx, mv1.1, false),
5720 mv_to_q4(cpy, mv1.0, false),
5721 CHROMA_SIDE,
5722 CHROMA_SIDE,
5723 Regular,
5724 Regular,
5725 &mut inter1_v,
5726 );
5727 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
5728 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
5729
5730 if skip {
5731 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
5732 u.reconstruct_mc(
5733 cpx,
5734 cpy,
5735 CHROMA_SIDE,
5736 &pred_u,
5737 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
5738 );
5739 v.reconstruct_mc(
5740 cpx,
5741 cpy,
5742 CHROMA_SIDE,
5743 &pred_v,
5744 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
5745 );
5746 luma_grid = vec![0i32; SIDE * SIDE];
5747 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5748 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5749 } else {
5750 let around = neighbours.around_mi(leaf_mi, 8);
5751 luma_grid = read_inter_plane(
5752 dec,
5753 cdfs,
5754 TxbSet::Luma8Inter,
5755 scan8,
5756 0,
5757 around[0],
5758 mode_for_tx,
5759 y,
5760 px,
5761 py,
5762 SIDE,
5763 base_q_idx,
5764 &pred_y,
5765 )?;
5766 u_grid = read_inter_plane(
5767 dec,
5768 cdfs,
5769 TxbSet::Chroma4,
5770 scan4,
5771 1,
5772 around[1],
5773 mode_for_tx,
5774 u,
5775 cpx,
5776 cpy,
5777 CHROMA_SIDE,
5778 base_q_idx,
5779 &pred_u,
5780 )?;
5781 v_grid = read_inter_plane(
5782 dec,
5783 cdfs,
5784 TxbSet::Chroma4,
5785 scan4,
5786 2,
5787 around[2],
5788 mode_for_tx,
5789 v,
5790 cpx,
5791 cpy,
5792 CHROMA_SIDE,
5793 base_q_idx,
5794 &pred_v,
5795 )?;
5796 }
5797 return Ok((skip, is_inter, skip_mode, compound_ctx8));
5798 }
5799 }
5800 let sr_ctx = single_ref_ctx(above_inter || left_inter);
5801 let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]);
5802 let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]);
5803 let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]);
5804 if (p1, p3, p4) != (0, 0, 0) {
5805 return Err(unsupported(
5806 "a reference frame other than LAST_FRAME (round 2)",
5807 ));
5808 }
5809
5810 let (mi_row, mi_col) = leaf_mi;
5811 let stack = find_mv_stack(
5812 grid,
5813 mi_row,
5814 mi_col,
5815 2,
5816 2,
5817 LAST_FRAME,
5818 mi_cols as usize,
5819 mi_rows as usize,
5820 );
5821
5822 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
5823 let (mv, is_new_mv) = if !not_new {
5824 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
5825 // read at most two `drl_mode` bits, one per stack entry past the
5826 // first, stopping at the first `0`. The chosen index selects
5827 // which stack entry `read_mv`'s base predictor comes from
5828 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
5829 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
5830 let mut idx = 0usize;
5831 while idx < 2 && stack.entries.len() > idx + 1 {
5832 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
5833 break;
5834 }
5835 idx += 1;
5836 }
5837 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
5838 (
5839 read_mv(
5840 dec,
5841 &mut cdfs.mv_comp,
5842 &mut cdfs.mv_joint,
5843 base_mv,
5844 allow_high_precision_mv,
5845 ),
5846 true,
5847 )
5848 } else {
5849 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
5850 if !not_zero {
5851 return Err(unsupported("GLOBALMV (round 3)"));
5852 }
5853 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
5854 let mv = if nearest {
5855 stack.nearest_mv
5856 } else {
5857 let mut idx = 1usize;
5858 while idx < 3 && stack.entries.len() > idx + 1 {
5859 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
5860 break;
5861 }
5862 idx += 1;
5863 }
5864 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
5865 };
5866 (mv, false)
5867 };
5868 for dr in 0..2 {
5869 for dc in 0..2 {
5870 grid.set(
5871 mi_row + dr,
5872 mi_col + dc,
5873 MiInfo {
5874 is_inter: true,
5875 ref_frame: LAST_FRAME,
5876 ref_frame1: None,
5877 mv1: None,
5878 mv,
5879 is_new_mv,
5880 size: 2,
5881 },
5882 );
5883 }
5884 }
5885 mode_for_tx = 0;
5886
5887 let mut pred_y = vec![0u8; SIDE * SIDE];
5888 mc::predict(
5889 &ref_y.data,
5890 ref_y.width,
5891 ref_y.true_width,
5892 ref_y.true_height,
5893 mv_to_q4(px, mv.1, true),
5894 mv_to_q4(py, mv.0, true),
5895 SIDE,
5896 SIDE,
5897 &mut pred_y,
5898 );
5899 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
5900 mc::predict(
5901 &ref_u.data,
5902 ref_u.width,
5903 ref_u.true_width,
5904 ref_u.true_height,
5905 mv_to_q4(cpx, mv.1, false),
5906 mv_to_q4(cpy, mv.0, false),
5907 CHROMA_SIDE,
5908 CHROMA_SIDE,
5909 &mut pred_u,
5910 );
5911 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
5912 mc::predict(
5913 &ref_v.data,
5914 ref_v.width,
5915 ref_v.true_width,
5916 ref_v.true_height,
5917 mv_to_q4(cpx, mv.1, false),
5918 mv_to_q4(cpy, mv.0, false),
5919 CHROMA_SIDE,
5920 CHROMA_SIDE,
5921 &mut pred_v,
5922 );
5923
5924 if skip {
5925 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
5926 u.reconstruct_mc(
5927 cpx,
5928 cpy,
5929 CHROMA_SIDE,
5930 &pred_u,
5931 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
5932 );
5933 v.reconstruct_mc(
5934 cpx,
5935 cpy,
5936 CHROMA_SIDE,
5937 &pred_v,
5938 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
5939 );
5940 luma_grid = vec![0i32; SIDE * SIDE];
5941 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5942 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5943 } else {
5944 let around = neighbours.around_mi(leaf_mi, 8);
5945 luma_grid = read_inter_plane(
5946 dec,
5947 cdfs,
5948 TxbSet::Luma8Inter,
5949 scan8,
5950 0,
5951 around[0],
5952 mode_for_tx,
5953 y,
5954 px,
5955 py,
5956 SIDE,
5957 base_q_idx,
5958 &pred_y,
5959 )?;
5960 u_grid = read_inter_plane(
5961 dec,
5962 cdfs,
5963 TxbSet::Chroma4,
5964 scan4,
5965 1,
5966 around[1],
5967 mode_for_tx,
5968 u,
5969 cpx,
5970 cpy,
5971 CHROMA_SIDE,
5972 base_q_idx,
5973 &pred_u,
5974 )?;
5975 v_grid = read_inter_plane(
5976 dec,
5977 cdfs,
5978 TxbSet::Chroma4,
5979 scan4,
5980 2,
5981 around[2],
5982 mode_for_tx,
5983 v,
5984 cpx,
5985 cpy,
5986 CHROMA_SIDE,
5987 base_q_idx,
5988 &pred_v,
5989 )?;
5990 }
5991 } else {
5992 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
5993 if mode >= 13 {
5994 return Err(unsupported(
5995 "an intra mode this decoder does not code (round 2)",
5996 ));
5997 }
5998 if (V_PRED..=D67_PRED).contains(&mode) {
5999 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
6000 if angle != ANGLE_DELTA_ZERO {
6001 return Err(unsupported(
6002 "a nonzero angle delta (this encoder never writes one)",
6003 ));
6004 }
6005 }
6006 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
6007 if uv_mode != DC_PRED {
6008 return Err(unsupported(
6009 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
6010 ));
6011 }
6012 mode_for_tx = mode;
6013 let (mi_row, mi_col) = leaf_mi;
6014 for dr in 0..2 {
6015 for dc in 0..2 {
6016 grid.set(
6017 mi_row + dr,
6018 mi_col + dc,
6019 MiInfo {
6020 is_inter: false,
6021 ref_frame: -1,
6022 ref_frame1: None,
6023 mv1: None,
6024 mv: (0, 0),
6025 is_new_mv: false,
6026 size: 2,
6027 },
6028 );
6029 }
6030 }
6031
6032 let reach = Reach::of(SIDE, px, py, y.width, y.height);
6033 if skip {
6034 y.reconstruct(
6035 px,
6036 py,
6037 SIDE,
6038 mode,
6039 0,
6040 reach,
6041 &vec![0i32; SIDE * SIDE],
6042 None,
6043 None,
6044 );
6045 u.reconstruct(
6046 cpx,
6047 cpy,
6048 CHROMA_SIDE,
6049 DC_PRED,
6050 0,
6051 reach,
6052 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
6053 None,
6054 None,
6055 );
6056 v.reconstruct(
6057 cpx,
6058 cpy,
6059 CHROMA_SIDE,
6060 DC_PRED,
6061 0,
6062 reach,
6063 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
6064 None,
6065 None,
6066 );
6067 luma_grid = vec![0i32; SIDE * SIDE];
6068 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
6069 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
6070 } else {
6071 let around = neighbours.around_mi(leaf_mi, 8);
6072 luma_grid = read_plane(
6073 dec,
6074 cdfs,
6075 TxbSet::Luma8,
6076 scan8,
6077 0,
6078 around[0],
6079 mode,
6080 mode,
6081 0,
6082 reach,
6083 y,
6084 px,
6085 py,
6086 SIDE,
6087 TX8,
6088 base_q_idx,
6089 None,
6090 None,
6091 None,
6092 )?;
6093 u_grid = read_plane(
6094 dec,
6095 cdfs,
6096 TxbSet::Chroma4,
6097 scan4,
6098 1,
6099 around[1],
6100 mode,
6101 DC_PRED,
6102 0,
6103 reach,
6104 u,
6105 cpx,
6106 cpy,
6107 CHROMA_SIDE,
6108 TX4,
6109 base_q_idx,
6110 None,
6111 None,
6112 None,
6113 )?;
6114 v_grid = read_plane(
6115 dec,
6116 cdfs,
6117 TxbSet::Chroma4,
6118 scan4,
6119 2,
6120 around[2],
6121 mode,
6122 DC_PRED,
6123 0,
6124 reach,
6125 v,
6126 cpx,
6127 cpy,
6128 CHROMA_SIDE,
6129 TX4,
6130 base_q_idx,
6131 None,
6132 None,
6133 None,
6134 )?;
6135 }
6136 }
6137 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
6138 neighbours.fill_lf_grid(leaf_mi, 2, 8, if is_inter { LAST_FRAME } else { 0 });
6139 Ok((skip, is_inter, skip_mode, compound_ctx8))
6140}
6141
6142/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
6143/// against `reference` (the previous frame's own decoded picture, at this
6144/// frame's true size -- a decoder's single-slot DPB, matching what this
6145/// crate's encoder always predicts from), returning the picture it
6146/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
6147/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
6148/// `frame_width`/`frame_height` its true render size).
6149///
6150/// # Errors
6151/// Returns an error under the same conditions [`decode_inter_block`] does,
6152/// or when `reference` is not this frame's own true size, or when the tile
6153/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
6154/// refusal [`crate::tile`]'s writer gives its encoder).
6155pub fn decode_inter_frame_tile(
6156 data: &[u8],
6157 mi_cols: u32,
6158 mi_rows: u32,
6159 base_q_idx: u8,
6160 frame_width: u32,
6161 frame_height: u32,
6162 reference: &Picture,
6163 other_refs: [Option<&Picture>; 8],
6164 cdef: &CdefParams,
6165 loop_filter: &LoopFilterParams,
6166 allow_high_precision_mv: bool,
6167 interp_fixed: Option<mc::InterpFilterKind>,
6168 enable_dual_filter: bool,
6169 reference_select: bool,
6170) -> Result<Picture> {
6171 decode_inter_frame_tile_with_cdfs(
6172 data,
6173 mi_cols,
6174 mi_rows,
6175 base_q_idx,
6176 frame_width,
6177 frame_height,
6178 reference,
6179 other_refs,
6180 cdef,
6181 loop_filter,
6182 None,
6183 allow_high_precision_mv,
6184 NO_SIGN_BIAS,
6185 interp_fixed,
6186 enable_dual_filter,
6187 0,
6188 0,
6189 [0; 7],
6190 None,
6191 reference_select,
6192 false,
6193 false,
6194 false,
6195 [0; 2],
6196 )
6197 .map(|(picture, _, _)| picture)
6198}
6199
6200/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
6201/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
6202/// end-of-tile table. An inter frame's own header can name
6203/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
6204/// so `None` is a real case here, not only a convenience default.
6205pub(crate) fn decode_inter_frame_tile_with_cdfs(
6206 data: &[u8],
6207 mi_cols: u32,
6208 mi_rows: u32,
6209 base_q_idx: u8,
6210 frame_width: u32,
6211 frame_height: u32,
6212 reference: &Picture,
6213 other_refs: [Option<&Picture>; 8],
6214 cdef: &CdefParams,
6215 loop_filter: &LoopFilterParams,
6216 initial_cdfs: Option<Cdfs>,
6217 allow_high_precision_mv: bool,
6218 sign_bias_table: SignBiasTable,
6219 interp_fixed: Option<mc::InterpFilterKind>,
6220 enable_dual_filter: bool,
6221 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
6222 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
6223 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
6224 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
6225 // and the caller ([`crate::stream::decode_stream`]) projected one.
6226 order_hint_bits: u32,
6227 order_hint: u32,
6228 ref_order_hints: [u32; 7],
6229 tpl_field: Option<&crate::motion_field::TplField>,
6230 // lane-av1comp: this frame header's own `reference_select` bit, threaded
6231 // to every `decode_inter_block`/`decode_inter_block8` call below.
6232 reference_select: bool,
6233 // lane-av1comp: `seq_params`' own compound-blend enable bits.
6234 enable_masked_compound: bool,
6235 enable_jnt_comp: bool,
6236 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
6237 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
6238 // `decode_inter_block8` call below.
6239 skip_mode_present: bool,
6240 skip_mode_frame: [u8; 2],
6241) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
6242 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
6243 field,
6244 order_hint_bits,
6245 order_hint,
6246 ref_order_hints,
6247 });
6248 if mi_cols == 0 || mi_rows == 0 {
6249 return Err(unsupported("a frame with no mode-info grid"));
6250 }
6251 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
6252 if reference.width != true_width || reference.height != true_height {
6253 return Err(unsupported(
6254 "a reference picture that is not this frame's own true size",
6255 ));
6256 }
6257 let (cols, rows) = block_grid(mi_cols, mi_rows);
6258 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
6259 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
6260
6261 let ref_y = PlaneBuf {
6262 data: reference.y.clone(),
6263 width: reference.width,
6264 height: reference.height,
6265 true_width: reference.width,
6266 true_height: reference.height,
6267 };
6268 let ref_u = PlaneBuf {
6269 data: reference.u.clone(),
6270 width: reference.width / 2,
6271 height: reference.height / 2,
6272 true_width: reference.width / 2,
6273 true_height: reference.height / 2,
6274 };
6275 let ref_v = PlaneBuf {
6276 data: reference.v.clone(),
6277 width: reference.width / 2,
6278 height: reference.height / 2,
6279 true_width: reference.width / 2,
6280 true_height: reference.height / 2,
6281 };
6282 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
6283 // names a live DPB slot for (lane-av1refs: generalised from the old
6284 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
6285 // now per-reference). `decode_inter_block` refuses by name when the
6286 // block it is decoding selects an index that is still `None` here
6287 // (spec 7.9 requires every *active* reference be a compatible size;
6288 // an inactive one this frame never selects is simply left `None`).
6289 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
6290 other_refs[i]
6291 .filter(|g| g.width == reference.width && g.height == reference.height)
6292 .map(|g| {
6293 (
6294 PlaneBuf {
6295 data: g.y.clone(),
6296 width: g.width,
6297 height: g.height,
6298 true_width: g.width,
6299 true_height: g.height,
6300 },
6301 PlaneBuf {
6302 data: g.u.clone(),
6303 width: g.width / 2,
6304 height: g.height / 2,
6305 true_width: g.width / 2,
6306 true_height: g.height / 2,
6307 },
6308 PlaneBuf {
6309 data: g.v.clone(),
6310 width: g.width / 2,
6311 height: g.height / 2,
6312 true_width: g.width / 2,
6313 true_height: g.height / 2,
6314 },
6315 )
6316 })
6317 });
6318 let ref_slots: RefSlots =
6319 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
6320
6321 let mut y = PlaneBuf {
6322 data: vec![0u8; width * height],
6323 width,
6324 height,
6325 true_width,
6326 true_height,
6327 };
6328 let mut u = PlaneBuf {
6329 data: vec![0u8; width * height / 4],
6330 width: width / 2,
6331 height: height / 2,
6332 true_width: true_width / 2,
6333 true_height: true_height / 2,
6334 };
6335 let mut v = PlaneBuf {
6336 data: vec![0u8; width * height / 4],
6337 width: width / 2,
6338 height: height / 2,
6339 true_width: true_width / 2,
6340 true_height: true_height / 2,
6341 };
6342
6343 let scan32 = default_scan(TX32);
6344 let scan16 = default_scan(TX16);
6345 let scan8 = default_scan(TX8);
6346 let scan4 = default_scan(TX4);
6347
6348 let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
6349 let mut dec = SymbolDecoder::new(data);
6350 let mut neighbours = Neighbours::new(
6351 cols as usize * 2,
6352 rows as usize * 2,
6353 mi_cols as usize,
6354 mi_rows as usize,
6355 );
6356 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
6357
6358 for sb_r in 0..sb_rows {
6359 neighbours.start_row();
6360 for sb_c in 0..sb_cols {
6361 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
6362 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
6363 let (has_cols, has_rows) = (
6364 sb_c * SB_MI + SB_MI / 2 < mi_cols,
6365 sb_r * SB_MI + SB_MI / 2 < mi_rows,
6366 );
6367 match (has_cols, has_rows) {
6368 (true, true) => {
6369 dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
6370 }
6371 (true, false) => {
6372 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
6373 }
6374 (false, true) => {
6375 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
6376 }
6377 (false, false) => {}
6378 }
6379
6380 for quadrant in 0..4 {
6381 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
6382 if r32 >= rows || c32 >= cols {
6383 continue;
6384 }
6385 let at = (r32 as usize * 2, c32 as usize * 2);
6386 let ctx32 = neighbours.partition_ctx(at, BLOCK);
6387 let (has_cols32, has_rows32) = (
6388 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
6389 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
6390 );
6391 let part32 = if has_cols32 && has_rows32 {
6392 dec.symbol(&mut cdfs.partition_w32[ctx32])
6393 } else {
6394 match (has_cols32, has_rows32) {
6395 (true, false) => {
6396 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
6397 }
6398 (false, true) => {
6399 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
6400 }
6401 _ => {}
6402 }
6403 PARTITION_SPLIT
6404 };
6405 match part32 {
6406 PARTITION_NONE => {
6407 decode_inter_block(
6408 &mut dec,
6409 &mut cdfs,
6410 &mut neighbours,
6411 &mut grid,
6412 at,
6413 BLOCK,
6414 mi_cols,
6415 mi_rows,
6416 &mut y,
6417 &mut u,
6418 &mut v,
6419 &ref_y,
6420 &ref_u,
6421 &ref_v,
6422 &ref_slots,
6423 &sign_bias_table,
6424 base_q_idx,
6425 TxbSet::Luma32,
6426 TxbSet::Luma32Inter,
6427 TxbSet::Chroma16,
6428 TX32,
6429 TX16,
6430 &scan32,
6431 &scan16,
6432 3,
6433 allow_high_precision_mv,
6434 interp_fixed,
6435 enable_dual_filter,
6436 tpl_frame.as_ref(),
6437 reference_select,
6438 enable_masked_compound,
6439 enable_jnt_comp,
6440 order_hint_bits,
6441 order_hint,
6442 ref_order_hints,
6443 skip_mode_present,
6444 skip_mode_frame,
6445 )?;
6446 }
6447 PARTITION_SPLIT => {
6448 for sub in 0..4 {
6449 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
6450 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
6451 continue;
6452 }
6453 let (has_cols16, has_rows16) = (
6454 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
6455 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
6456 );
6457 if !has_cols16 && !has_rows16 {
6458 return Err(unsupported(
6459 "a 16x16 inter block whose true edge cuts through both \
6460 axes needs a rectangular transform this decoder does \
6461 not code yet",
6462 ));
6463 }
6464 let at16 = (sr, sc);
6465 if has_cols16 && has_rows16 {
6466 let ctx16 = neighbours.partition_ctx(at16, SUB);
6467 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
6468 if part16 != PARTITION_NONE {
6469 return Err(unsupported(
6470 "a partition below 16x16 (this encoder never writes one)",
6471 ));
6472 }
6473 decode_inter_block(
6474 &mut dec,
6475 &mut cdfs,
6476 &mut neighbours,
6477 &mut grid,
6478 at16,
6479 SUB,
6480 mi_cols,
6481 mi_rows,
6482 &mut y,
6483 &mut u,
6484 &mut v,
6485 &ref_y,
6486 &ref_u,
6487 &ref_v,
6488 &ref_slots,
6489 &sign_bias_table,
6490 base_q_idx,
6491 TxbSet::Luma16,
6492 TxbSet::Luma16Inter,
6493 TxbSet::Chroma8,
6494 TX16,
6495 TX8,
6496 &scan16,
6497 &scan8,
6498 2,
6499 allow_high_precision_mv,
6500 interp_fixed,
6501 enable_dual_filter,
6502 tpl_frame.as_ref(),
6503 reference_select,
6504 enable_masked_compound,
6505 enable_jnt_comp,
6506 order_hint_bits,
6507 order_hint,
6508 ref_order_hints,
6509 skip_mode_present,
6510 skip_mode_frame,
6511 )?;
6512 } else {
6513 let ctx16 = neighbours.partition_ctx(at16, SUB);
6514 if has_cols16 {
6515 dec.symbol_fixed(&gather(
6516 &cdfs.partition_w16[ctx16],
6517 VERT_ALIKE,
6518 ));
6519 } else {
6520 dec.symbol_fixed(&gather(
6521 &cdfs.partition_w16[ctx16],
6522 HORZ_ALIKE,
6523 ));
6524 }
6525 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
6526 let leaf_positions: Vec<(u32, u32)> = (0..4)
6527 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
6528 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
6529 .collect();
6530 let mut prev_leaf: Option<((usize, usize), bool, bool)> = None;
6531 let mut last_compound_ctx: Option<(i8, i8, u8, u8)> = None;
6532 let mut last_skip_mode = false;
6533 for (mr, mc) in leaf_positions {
6534 let leaf_mi = (mr as usize, mc as usize);
6535 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
6536 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
6537 if part8 != PARTITION_NONE {
6538 return Err(unsupported(
6539 "a partition below 8x8 (this encoder never writes one)",
6540 ));
6541 }
6542 let (skip, is_inter, skip_mode_leaf, compound_ctx8) =
6543 decode_inter_block8(
6544 &mut dec,
6545 &mut cdfs,
6546 &mut neighbours,
6547 &mut grid,
6548 mi_cols,
6549 mi_rows,
6550 at16,
6551 leaf_mi,
6552 &mut y,
6553 &mut u,
6554 &mut v,
6555 &ref_y,
6556 &ref_u,
6557 &ref_v,
6558 &ref_slots,
6559 base_q_idx,
6560 &scan8,
6561 &scan4,
6562 prev_leaf,
6563 allow_high_precision_mv,
6564 reference_select,
6565 enable_masked_compound,
6566 enable_jnt_comp,
6567 order_hint_bits,
6568 order_hint,
6569 ref_order_hints,
6570 skip_mode_present,
6571 skip_mode_frame,
6572 )?;
6573 prev_leaf = Some((leaf_mi, skip, is_inter));
6574 last_skip_mode = skip_mode_leaf;
6575 if compound_ctx8.is_some() {
6576 last_compound_ctx = compound_ctx8;
6577 }
6578 }
6579 if let Some((_, skip, is_inter)) = prev_leaf {
6580 // corner-cut: `decode_inter_block8`'s
6581 // leaves never read a switchable filter
6582 // (round-3 GLOBALMV refusal already
6583 // bounds them away from the Regular-only
6584 // gap this round closes elsewhere); `[3,
6585 // 3]` is "no info", the same value an
6586 // intra neighbour records. Upgrade:
6587 // thread `interp_fixed`/`enable_dual_filter`
6588 // into `decode_inter_block8` once a
6589 // straddling 8x8 SWITCHABLE stream is on
6590 // hand to pin against.
6591 neighbours.record_inter(
6592 at16,
6593 SUB,
6594 skip,
6595 is_inter,
6596 if is_inter { LAST_FRAME } else { -1 },
6597 [3, 3],
6598 last_skip_mode,
6599 );
6600 if let Some((ref0, ref1, group_idx, idx)) = last_compound_ctx {
6601 neighbours.record_inter(
6602 at16,
6603 SUB,
6604 skip,
6605 is_inter,
6606 ref0,
6607 [3, 3],
6608 last_skip_mode,
6609 );
6610 neighbours
6611 .record_compound_ctx(at16, SUB, ref1, group_idx, idx);
6612 }
6613 }
6614 }
6615 }
6616 }
6617 _ => {
6618 return Err(unsupported("a partition type this encoder never writes"));
6619 }
6620 }
6621 }
6622 }
6623 }
6624
6625 scratch_dump_prefilt(&y, &u, &v);
6626 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
6627 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
6628
6629 let motion_field = build_motion_field(
6630 &grid,
6631 mi_cols as usize,
6632 mi_rows as usize,
6633 order_hint,
6634 ref_order_hints,
6635 );
6636
6637 let (fw, fh) = (frame_width as usize, frame_height as usize);
6638 if fw == width && fh == height {
6639 return Ok((
6640 Picture {
6641 width,
6642 height,
6643 y: y.data,
6644 u: u.data,
6645 v: v.data,
6646 },
6647 cdfs,
6648 motion_field,
6649 ));
6650 }
6651 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
6652 let mut out = Vec::with_capacity(w * h);
6653 for row in 0..h {
6654 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
6655 }
6656 out
6657 };
6658 Ok((
6659 Picture {
6660 width: fw,
6661 height: fh,
6662 y: crop(&y, fw, fh),
6663 u: crop(&u, fw / 2, fh / 2),
6664 v: crop(&v, fw / 2, fh / 2),
6665 },
6666 cdfs,
6667 motion_field,
6668 ))
6669}
6670
6671#[cfg(test)]
6672mod tests {
6673 use super::*;
6674
6675 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
6676 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
6677 // single-purpose writers with their own skip-context rule (keyed to
6678 // superblock position, not the neighbour-tracked one every real block
6679 // uses), never reached by `encode_key_frame_with_modes` — decoding them
6680 // would need a second, throwaway context convention next to the real
6681 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
6682 // this decoder's one target, and the round-trip test below is against
6683 // that path with real quantised residual, not a synthetic all-DC frame.
6684
6685 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
6686 /// when both references sit on the same temporal side -- the three
6687 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
6688 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
6689 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
6690 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
6691 /// not just the three enumerated syntax pairs).
6692 #[test]
6693 fn is_uni_comp_ref_matches_forward_backward_sides() {
6694 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
6695 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
6696 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
6697 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
6698 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
6699 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
6700 }
6701
6702 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
6703 /// with the real second reference (lane-av1comp round 12: previously
6704 /// always cleared to `None` by `record_inter`, so the next block's own
6705 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
6706 /// -- could never see a real compound neighbour).
6707 #[test]
6708 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
6709 let mut n = Neighbours::new(4, 4, 16, 16);
6710 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
6711 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
6712 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
6713 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
6714 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
6715 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
6716 }
6717
6718 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
6719 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
6720 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
6721 /// -- a few corner and interior points, not the whole 6x6 grid.
6722 #[test]
6723 fn compound_mode_ctx_map_matches_libaom_corners() {
6724 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
6725 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
6726 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
6727 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
6728 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
6729 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
6730 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
6731 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
6732 // exactly the ranges `find_mv_stack_compound` produces.
6733 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
6734 }
6735
6736 #[test]
6737 fn a_frame_with_no_mode_info_grid_is_refused() {
6738 assert!(
6739 decode_key_frame_tile(
6740 &[0u8; 4],
6741 0,
6742 32,
6743 32,
6744 0,
6745 128,
6746 false,
6747 &CdefParams::default(),
6748 &LoopFilterParams::default(),
6749 false,
6750 true,
6751 )
6752 .is_err()
6753 );
6754 }
6755
6756 /// Encodes and decodes one picture with `modes`, asserting the decoder's
6757 /// planes are byte-exact against the encoder's own reconstruction.
6758 fn round_trips(w: usize, h: usize, modes: &[u8]) {
6759 use crate::encode::{Encoded, Picture as Pic};
6760 let mut source = vec![0u8; w * h];
6761 for row in 0..h {
6762 for col in 0..w {
6763 source[row * w + col] = ((row * 3 + col * 5) % 251) as u8;
6764 }
6765 }
6766 let picture = Pic {
6767 width: w,
6768 height: h,
6769 y: source,
6770 u: vec![128; w * h / 4],
6771 v: vec![128; w * h / 4],
6772 };
6773 let Encoded {
6774 tile,
6775 reconstruction,
6776 mi_cols,
6777 mi_rows,
6778 base_q_idx,
6779 ..
6780 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
6781 let decoded = decode_key_frame_tile(
6782 &tile,
6783 mi_cols,
6784 mi_rows,
6785 base_q_idx,
6786 w as u32,
6787 h as u32,
6788 false,
6789 &CdefParams::default(),
6790 &LoopFilterParams::default(),
6791 false,
6792 true,
6793 )
6794 .unwrap();
6795 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
6796 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
6797 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
6798 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
6799 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
6800 }
6801
6802 #[test]
6803 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
6804 for (w, h) in [(128usize, 128usize), (192, 128)] {
6805 round_trips(w, h, &[DC_PRED as u8]);
6806 }
6807 }
6808
6809 /// Every one of the thirteen key-frame intra modes, at their base angle,
6810 /// on real (non-flat) content: the mode search picks whichever wins each
6811 /// block, so this exercises the directional edge/reach plumbing this
6812 /// decoder round adds, not just `DC_PRED`.
6813 #[test]
6814 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
6815 for (w, h) in [(128usize, 128usize), (192, 128)] {
6816 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
6817 }
6818 }
6819
6820 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
6821 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
6822 /// this decoder round adds.
6823 #[test]
6824 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
6825 for (w, h) in [(854usize, 480usize), (216, 96)] {
6826 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
6827 }
6828 }
6829
6830 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
6831 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
6832 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
6833 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
6834 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
6835 /// bit, `partition_w8` leaves).
6836 #[test]
6837 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
6838 for (w, h) in [(40usize, 32usize), (640, 360)] {
6839 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
6840 }
6841 }
6842
6843 /// A skipped block codes no residual syntax at all (spec 5.11.34):
6844 /// straight prediction on every plane. The real key-frame writer never
6845 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
6846 /// `0`), so this constructs the exact symbol sequence a writer that did
6847 /// emit it would produce, by hand, and asserts the decoded reconstruction
6848 /// is pure DC prediction (mid-grey, with no neighbours) rather than
6849 /// refusing.
6850 #[test]
6851 fn a_skipped_block_decodes_to_pure_prediction() {
6852 use crate::msac::SymbolEncoder;
6853 let mut cdfs = Cdfs::new(q_ctx_of(40));
6854 let mut enc = SymbolEncoder::new();
6855 // One whole, unsplit 64x64 superblock, coded skip = true.
6856 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
6857 enc.symbol(1, &mut cdfs.skip[0]);
6858 enc.symbol(
6859 DC_PRED,
6860 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
6861 );
6862 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
6863 let data = enc.finish();
6864 let decoded = decode_key_frame_tile(
6865 &data,
6866 16,
6867 16,
6868 40,
6869 64,
6870 64,
6871 false,
6872 &CdefParams::default(),
6873 &LoopFilterParams::default(),
6874 false,
6875 true,
6876 )
6877 .unwrap();
6878 assert!(
6879 decoded.y.iter().all(|&s| s == 128),
6880 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
6881 );
6882 }
6883
6884 // ffmpeg cross-oracle: an independent decoder (not this crate's own
6885 // encoder-side reconstruction) agrees with what this module decodes,
6886 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
6887 // name (that module is another lane's territory this round, and the
6888 // helpers are `#[cfg(test)]`-private to it).
6889 use std::io::Write;
6890 use std::process::{Command, Stdio};
6891
6892 fn have_ffmpeg() -> bool {
6893 Command::new("ffmpeg")
6894 .arg("-version")
6895 .stdout(Stdio::null())
6896 .stderr(Stdio::null())
6897 .status()
6898 .is_ok_and(|s| s.success())
6899 }
6900
6901 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
6902 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
6903 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
6904 let mut child = Command::new("ffmpeg")
6905 .args([
6906 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
6907 ])
6908 .stdin(Stdio::piped())
6909 .stdout(Stdio::piped())
6910 .stderr(Stdio::piped())
6911 .spawn()
6912 .expect("ffmpeg failed to start");
6913 child
6914 .stdin
6915 .take()
6916 .expect("ffmpeg stdin")
6917 .write_all(stream)
6918 .expect("writing the stream to ffmpeg");
6919 let out = child.wait_with_output().expect("ffmpeg failed to run");
6920 assert!(
6921 out.status.success(),
6922 "ffmpeg refused the stream: {}",
6923 String::from_utf8_lossy(&out.stderr)
6924 );
6925 let (luma, chroma) = (width * height, width * height / 4);
6926 assert_eq!(
6927 out.stdout.len(),
6928 luma + 2 * chroma,
6929 "expected one 4:2:0 frame"
6930 );
6931 Picture {
6932 width,
6933 height,
6934 y: out.stdout[..luma].to_vec(),
6935 u: out.stdout[luma..luma + chroma].to_vec(),
6936 v: out.stdout[luma + chroma..].to_vec(),
6937 }
6938 }
6939
6940 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
6941 fn ffmpeg_decode_sequence(
6942 stream: &[u8],
6943 width: usize,
6944 height: usize,
6945 frames: usize,
6946 ) -> Vec<Picture> {
6947 let mut child = Command::new("ffmpeg")
6948 .args([
6949 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
6950 ])
6951 .stdin(Stdio::piped())
6952 .stdout(Stdio::piped())
6953 .stderr(Stdio::piped())
6954 .spawn()
6955 .expect("ffmpeg failed to start");
6956 child
6957 .stdin
6958 .take()
6959 .expect("ffmpeg stdin")
6960 .write_all(stream)
6961 .expect("writing the stream to ffmpeg");
6962 let out = child.wait_with_output().expect("ffmpeg failed to run");
6963 assert!(
6964 out.status.success(),
6965 "ffmpeg refused the stream: {}",
6966 String::from_utf8_lossy(&out.stderr)
6967 );
6968 let (luma, chroma) = (width * height, width * height / 4);
6969 let frame_bytes = luma + 2 * chroma;
6970 assert_eq!(
6971 out.stdout.len(),
6972 frame_bytes * frames,
6973 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
6974 String::from_utf8_lossy(&out.stderr)
6975 );
6976 (0..frames)
6977 .map(|i| {
6978 let base = i * frame_bytes;
6979 Picture {
6980 width,
6981 height,
6982 y: out.stdout[base..base + luma].to_vec(),
6983 u: out.stdout[base + luma..base + luma + chroma].to_vec(),
6984 v: out.stdout[base + luma + chroma..base + frame_bytes].to_vec(),
6985 }
6986 })
6987 .collect()
6988 }
6989
6990 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
6991 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
6992 /// test binary runs callers on parallel threads, and a shared name lets
6993 /// one test's cleanup race another's still-reading ffprobe --
6994 /// pid-keyed-temp-path class).
6995 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
6996 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
6997 let path = std::env::temp_dir().join(format!(
6998 "ec-av1-decode-probe-{}-{}.obu",
6999 std::process::id(),
7000 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7001 ));
7002 let _ = std::fs::remove_file(&path);
7003 std::fs::write(&path, stream).expect("writing the probe stream");
7004 let out = Command::new("ffprobe")
7005 .args([
7006 "-v",
7007 "error",
7008 "-f",
7009 "obu",
7010 "-select_streams",
7011 "v:0",
7012 "-show_entries",
7013 "stream=width,height",
7014 "-of",
7015 "csv=p=0",
7016 ])
7017 .arg(&path)
7018 .output()
7019 .expect("ffprobe failed to run");
7020 let _ = std::fs::remove_file(&path);
7021 assert!(
7022 out.status.success(),
7023 "ffprobe refused the stream: {}",
7024 String::from_utf8_lossy(&out.stderr)
7025 );
7026 let text = String::from_utf8_lossy(&out.stdout);
7027 let mut fields = text.trim().split(',');
7028 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
7029 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
7030 (width, height)
7031 }
7032
7033 /// This module's own decoder against an independent one (ffmpeg), not
7034 /// just against this crate's encoder-side reconstruction: both decoders
7035 /// read the identical tile bytes, so agreement here rules out a bug this
7036 /// crate's own writer and reader could otherwise share.
7037 #[test]
7038 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
7039 if !have_ffmpeg() {
7040 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
7041 return;
7042 }
7043 use crate::encode::encode_key_frame;
7044 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
7045 let picture = round_trip_test_card(width, height);
7046 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
7047 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
7048 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
7049 let ours = decode_key_frame_tile(
7050 &encoded.tile,
7051 encoded.mi_cols,
7052 encoded.mi_rows,
7053 encoded.base_q_idx,
7054 coded_w,
7055 coded_h,
7056 false,
7057 &CdefParams::default(),
7058 &LoopFilterParams::default(),
7059 false,
7060 true,
7061 )
7062 .unwrap();
7063 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
7064 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
7065 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
7066 }
7067 }
7068
7069 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
7070 let mut picture = crate::encode::Picture::grey(width, height);
7071 for row in 0..height {
7072 for col in 0..width {
7073 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u8;
7074 }
7075 }
7076 for row in 0..height / 2 {
7077 for col in 0..width / 2 {
7078 let i = row * width / 2 + col;
7079 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u8;
7080 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u8;
7081 }
7082 }
7083 picture
7084 }
7085
7086 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
7087 let mut picture = crate::encode::Picture::grey(width, height);
7088 for y in 0..height {
7089 for x in 0..width {
7090 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
7091 let gradient = sx * 200.0 / width as f64;
7092 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u8;
7093 }
7094 }
7095 for y in 0..height / 2 {
7096 for x in 0..width / 2 {
7097 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
7098 let i = y * width / 2 + x;
7099 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u8;
7100 picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
7101 }
7102 }
7103 picture
7104 }
7105
7106 /// A GOP (one key frame plus several inter frames, each panned so its
7107 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
7108 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
7109 /// reconstruction, frame by frame, chaining each decoded frame straight
7110 /// into the next as its reference -- exactly the single-slot DPB
7111 /// [`crate::encode::encode_sequence`] itself threads.
7112 fn gop_round_trips(width: usize, height: usize) {
7113 use crate::encode::encode_sequence;
7114 let pictures: Vec<_> = (0..4)
7115 .map(|i| panned_test_card(width, height, i * 3))
7116 .collect();
7117 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
7118 assert_eq!(encoded.frames.len(), 4);
7119
7120 let key = &encoded.frames[0];
7121 let mut reference = decode_key_frame_tile(
7122 &key.tile,
7123 key.mi_cols,
7124 key.mi_rows,
7125 key.base_q_idx,
7126 width as u32,
7127 height as u32,
7128 false,
7129 &CdefParams::default(),
7130 &LoopFilterParams::default(),
7131 false,
7132 true,
7133 )
7134 .unwrap();
7135 assert_eq!(
7136 reference.y, key.reconstruction.y,
7137 "{width}x{height} frame 0 luma"
7138 );
7139 assert_eq!(
7140 reference.u, key.reconstruction.u,
7141 "{width}x{height} frame 0 U"
7142 );
7143 assert_eq!(
7144 reference.v, key.reconstruction.v,
7145 "{width}x{height} frame 0 V"
7146 );
7147
7148 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
7149 let decoded = decode_inter_frame_tile(
7150 &frame.tile,
7151 frame.mi_cols,
7152 frame.mi_rows,
7153 frame.base_q_idx,
7154 width as u32,
7155 height as u32,
7156 &reference,
7157 [None; 8],
7158 &CdefParams::default(),
7159 &LoopFilterParams::default(),
7160 false,
7161 Some(mc::InterpFilterKind::Regular),
7162 false,
7163 false,
7164 )
7165 .unwrap();
7166 assert_eq!(
7167 decoded.y, frame.reconstruction.y,
7168 "{width}x{height} frame {i} luma"
7169 );
7170 assert_eq!(
7171 decoded.u, frame.reconstruction.u,
7172 "{width}x{height} frame {i} U"
7173 );
7174 assert_eq!(
7175 decoded.v, frame.reconstruction.v,
7176 "{width}x{height} frame {i} V"
7177 );
7178 reference = decoded;
7179 }
7180 }
7181
7182 #[test]
7183 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
7184 gop_round_trips(128, 64);
7185 }
7186
7187 /// Same claim, at a size that is not a whole number of 32x32 blocks
7188 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
7189 /// split path is exercised too.
7190 #[test]
7191 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
7192 gop_round_trips(216, 96);
7193 }
7194
7195 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
7196 /// this module does, frame for frame.
7197 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
7198 /// MV stack's *second* candidate (`near_mv`), not its first
7199 /// (`nearest_mv`) -- a hand-built symbol stream drives
7200 /// [`decode_inter_block`] directly, since this crate's own encoder never
7201 /// writes NEARMV (round 3: it never chooses the mode).
7202 #[test]
7203 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
7204 use crate::msac::SymbolEncoder;
7205 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
7206
7207 const LAST_FRAME: i8 = 1;
7208 let (mi_cols, mi_rows) = (12u32, 12u32);
7209 let side = 16usize; // one 16x16 leaf block
7210 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
7211 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7212 let bw4 = side / 4;
7213
7214 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
7215 let (above_mv, left_mv) = ((4, 4), (8, 8));
7216 let neighbour = |mv| MiInfo {
7217 is_inter: true,
7218 ref_frame: LAST_FRAME,
7219 ref_frame1: None,
7220 mv1: None,
7221 mv,
7222 is_new_mv: false,
7223 size: 1,
7224 };
7225 for col in mi_col..mi_col + bw4 {
7226 grid.set(mi_row - 1, col, neighbour(above_mv));
7227 }
7228 for row in mi_row..mi_row + bw4 {
7229 grid.set(row, mi_col - 1, neighbour(left_mv));
7230 }
7231
7232 let stack = find_mv_stack(
7233 &grid,
7234 mi_row,
7235 mi_col,
7236 bw4,
7237 bw4,
7238 LAST_FRAME,
7239 mi_cols as usize,
7240 mi_rows as usize,
7241 );
7242 // Sanity on the test's own setup, not the code under test: two equal-
7243 // weight candidates keep scan order (above, then left -- module doc).
7244 assert_eq!(stack.entries.len(), 2);
7245 assert_eq!(stack.nearest_mv, above_mv);
7246 assert_eq!(stack.near_mv, left_mv);
7247
7248 let (skip_ctx, ii_ctx, sr_ctx) = (
7249 0usize,
7250 intra_inter_ctx(true, true, false, false),
7251 single_ref_ctx(false),
7252 );
7253
7254 let mut cdfs = Cdfs::new(q_ctx_of(100));
7255 let mut enc = SymbolEncoder::new();
7256 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
7257 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
7258 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
7259 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
7260 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
7261 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
7262 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
7263 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
7264 let data = enc.finish();
7265
7266 let (width, height) = (64usize, 64usize);
7267 let ref_pattern: Vec<u8> = (0..width * height).map(|i| (i % 251) as u8).collect();
7268 let ref_plane = |scale: usize| PlaneBuf {
7269 data: ref_pattern
7270 .iter()
7271 .step_by(scale.max(1))
7272 .take((width / scale) * (height / scale))
7273 .copied()
7274 .collect(),
7275 width: width / scale,
7276 height: height / scale,
7277 true_width: width / scale,
7278 true_height: height / scale,
7279 };
7280 let ref_y = PlaneBuf {
7281 data: ref_pattern.clone(),
7282 width,
7283 height,
7284 true_width: width,
7285 true_height: height,
7286 };
7287 let ref_u = ref_plane(2);
7288 let ref_v = ref_plane(2);
7289
7290 let mut y = PlaneBuf {
7291 data: vec![0u8; width * height],
7292 width,
7293 height,
7294 true_width: width,
7295 true_height: height,
7296 };
7297 let mut u = PlaneBuf {
7298 data: vec![0u8; (width / 2) * (height / 2)],
7299 width: width / 2,
7300 height: height / 2,
7301 true_width: width / 2,
7302 true_height: height / 2,
7303 };
7304 let mut v = PlaneBuf {
7305 data: vec![0u8; (width / 2) * (height / 2)],
7306 width: width / 2,
7307 height: height / 2,
7308 true_width: width / 2,
7309 true_height: height / 2,
7310 };
7311
7312 let mut cdfs = Cdfs::new(q_ctx_of(100));
7313 let mut dec = SymbolDecoder::new(&data);
7314 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
7315 decode_inter_block(
7316 &mut dec,
7317 &mut cdfs,
7318 &mut neighbours,
7319 &mut grid,
7320 (r, c),
7321 side,
7322 mi_cols,
7323 mi_rows,
7324 &mut y,
7325 &mut u,
7326 &mut v,
7327 &ref_y,
7328 &ref_u,
7329 &ref_v,
7330 &[None; 8],
7331 &NO_SIGN_BIAS,
7332 100,
7333 TxbSet::Luma16,
7334 TxbSet::Luma16Inter,
7335 TxbSet::Chroma8,
7336 TX16,
7337 TX8,
7338 &[],
7339 &[],
7340 0,
7341 false,
7342 Some(mc::InterpFilterKind::Regular),
7343 false,
7344 None,
7345 false,
7346 false,
7347 false,
7348 0,
7349 0,
7350 [0; 7],
7351 false,
7352 [0; 2],
7353 )
7354 .unwrap();
7355
7356 let (px, py) = (c * SUB, r * SUB);
7357 let mut want_near = vec![0u8; side * side];
7358 crate::mc::predict(
7359 &ref_y.data,
7360 ref_y.width,
7361 ref_y.true_width,
7362 ref_y.true_height,
7363 mv_to_q4(px, left_mv.1, true),
7364 mv_to_q4(py, left_mv.0, true),
7365 side,
7366 side,
7367 &mut want_near,
7368 );
7369 let mut want_nearest = vec![0u8; side * side];
7370 crate::mc::predict(
7371 &ref_y.data,
7372 ref_y.width,
7373 ref_y.true_width,
7374 ref_y.true_height,
7375 mv_to_q4(px, above_mv.1, true),
7376 mv_to_q4(py, above_mv.0, true),
7377 side,
7378 side,
7379 &mut want_nearest,
7380 );
7381 assert_ne!(
7382 want_near, want_nearest,
7383 "test setup: the two candidate MVs must predict differently"
7384 );
7385
7386 let mut got = vec![0u8; side * side];
7387 for row in 0..side {
7388 got[row * side..(row + 1) * side].copy_from_slice(
7389 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
7390 );
7391 }
7392 assert_eq!(
7393 got, want_near,
7394 "NEARMV predicted from the wrong stack entry"
7395 );
7396 }
7397
7398 #[test]
7399 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
7400 if !have_ffmpeg() {
7401 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
7402 return;
7403 }
7404 use crate::encode::encode_sequence;
7405 let (width, height) = (128usize, 64usize);
7406 let pictures: Vec<_> = (0..3)
7407 .map(|i| panned_test_card(width, height, i * 3))
7408 .collect();
7409 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
7410 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
7411 let ffmpeg_frames =
7412 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
7413
7414 let key = &encoded.frames[0];
7415 let mut reference = decode_key_frame_tile(
7416 &key.tile,
7417 key.mi_cols,
7418 key.mi_rows,
7419 key.base_q_idx,
7420 coded_w,
7421 coded_h,
7422 false,
7423 &CdefParams::default(),
7424 &LoopFilterParams::default(),
7425 false,
7426 true,
7427 )
7428 .unwrap();
7429 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
7430
7431 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
7432 let decoded = decode_inter_frame_tile(
7433 &frame.tile,
7434 frame.mi_cols,
7435 frame.mi_rows,
7436 frame.base_q_idx,
7437 coded_w,
7438 coded_h,
7439 &reference,
7440 [None; 8],
7441 &CdefParams::default(),
7442 &LoopFilterParams::default(),
7443 false,
7444 Some(mc::InterpFilterKind::Regular),
7445 false,
7446 false,
7447 )
7448 .unwrap();
7449 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
7450 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
7451 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
7452 reference = decoded;
7453 }
7454 }
7455}