forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB214cdf2Tahinli3 months ago821 commits

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