forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiB66045bcTahinli3 months ago1500 commits

decode.rs21300 lines, 911.9 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::{
25 CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams,
26 SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo,
27};
28use ec_core::{Error, Result};
29
30use crate::cdf;
31use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
32use crate::encode::{Picture, Reach};
33use crate::intra::predict;
34use crate::mc;
35use crate::msac::SymbolDecoder;
36use crate::mvstack::{
37 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
38 MiGrid, MiInfo, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
39 find_mv_stack_with_sign_bias, reference_mode_ctx,
40 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
41 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
42};
43use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
44use crate::transform::{TxType, dequant_and_inverse_typed, dequant_and_inverse_typed_wh};
45
46const PARTITION_NONE: usize = 0;
47const PARTITION_HORZ: usize = 1;
48const PARTITION_VERT: usize = 2;
49const PARTITION_SPLIT: usize = 3;
50const PARTITION_HORZ_A: usize = 4;
51const PARTITION_HORZ_B: usize = 5;
52const PARTITION_VERT_A: usize = 6;
53const PARTITION_VERT_B: usize = 7;
54const PARTITION_HORZ_4: usize = 8;
55const PARTITION_VERT_4: usize = 9;
56const SB_MI: u32 = 16;
57const BLOCK_MI: u32 = 8;
58
59// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
60// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
61// superblock's own top-left mi?", the loop-restoration read's unit span, the
62// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
63// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
64// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
65// inside a 128 superblock).
66thread_local! {
67 static SB128: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
68}
69
70/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
71pub(crate) fn set_sb128(v: bool) {
72 SB128.with(|c| c.set(v));
73 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 });
74}
75
76fn sb128() -> bool {
77 SB128.with(|c| c.get())
78}
79
80/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
81pub(crate) fn sb_mi_cur() -> u32 {
82 if sb128() { SB_MI * 2 } else { SB_MI }
83}
84
85/// How many real 128-level partition symbols this decoder has read, and how
86/// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
87/// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
88thread_local! {
89 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
90 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
91}
92
93/// Current value of [`PART128_SYMBOLS`].
94pub(crate) fn part128_symbols() -> usize {
95 PART128_SYMBOLS.with(|c| c.get())
96}
97
98/// Current value of [`PART128_SPLIT_HITS`].
99pub(crate) fn part128_split_hits() -> usize {
100 PART128_SPLIT_HITS.with(|c| c.get())
101}
102
103/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
104/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
105/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
106/// the 64/32 levels sum 6.
107fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
108 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
109 [32768 - split, 32768, 0]
110}
111
112/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
113const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
114const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
115
116// How many `use_filter_intra` symbols this decoder has read as `1`, across
117// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
118// tests read (before/after, not the absolute value) to prove a stream
119// actually exercised the filter-intra predictor rather than silently
120// skipping it.
121thread_local! {
122 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
123 const { std::cell::Cell::new(0) };
124}
125
126/// Current value of [`FILTER_INTRA_HITS`].
127pub(crate) fn filter_intra_hits() -> usize {
128 FILTER_INTRA_HITS.with(|c| c.get())
129}
130
131// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
132// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
133// `read_filter_intra_mode_info` call), which no gate exercised before this
134// round -- every inter gate recipe passed `--enable-filter-intra=0`.
135thread_local! {
136 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
137 const { std::cell::Cell::new(0) };
138}
139
140/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
141pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
142 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
143}
144
145// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
146// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
147// frame-level flag through the recursive block decode -- `0` (the default)
148// makes every call a true no-op, matching every existing gate stream's
149// `cdef_bits == 0` behaviour exactly.
150thread_local! {
151 static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
152}
153// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
154// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
155// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
156// blocks every non-8-bit stream from reaching a decode call, so this is `8`
157// on every path that runs today -- threading it now (rather than the literal
158// `8`) is stage 1 of widening past that refusal without re-deriving every
159// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
160// depth (this decoder's own internal choice, matches dav1d/libaom).
161thread_local! {
162 static BIT_DEPTH: std::cell::Cell<u8> = const { std::cell::Cell::new(8) };
163}
164/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
165/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
166pub(crate) fn sample_max() -> i32 {
167 (1i32 << BIT_DEPTH.with(std::cell::Cell::get)) - 1
168}
169/// The current stream's bit depth, for callers (e.g. dequant) that need the
170/// raw value rather than the derived clamp bound.
171pub(crate) fn bit_depth() -> u8 {
172 BIT_DEPTH.with(std::cell::Cell::get)
173}
174/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
175/// [`crate::stream`]'s decode loop.
176pub(crate) fn set_bit_depth(bit_depth: u8) {
177 BIT_DEPTH.with(|c| c.set(bit_depth));
178}
179// Whether this superblock's single CDEF unit (this decoder has no 128x128
180// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
181// read -- reset to `false` at the top of each superblock in the two tile
182// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
183thread_local! {
184 static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
185}
186// Number of superblock columns in the current tile's grid, so
187// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
188// [`CDEF_IDX_GRID`].
189thread_local! {
190 static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
191}
192// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
193// which of the header's `1 << cdef.bits` strength pairs applies to that
194// superblock's samples.
195thread_local! {
196 static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
197}
198// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
199// has read, across every call on the current thread -- the gate's proof that a
200// `cdef_bits > 0` stream actually reached the new reader rather than every
201// superblock coincidentally being all-skip.
202thread_local! {
203 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
204}
205
206/// Current value of [`CDEF_IDX_HITS`].
207pub(crate) fn cdef_idx_hits() -> usize {
208 CDEF_IDX_HITS.with(|c| c.get())
209}
210
211// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
212// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
213// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
214// true no-op, matching every existing gate stream's `delta_q_present == 0`
215// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
216thread_local! {
217 static DELTA_Q_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
218 static DELTA_Q_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
219}
220// The running quantizer index (spec `CurrentQIndex`, libaom
221// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
222// top of every tile (spec `decode_tile`), carried across superblocks within
223// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
224// dequantization call sites instead of the frame-constant `base_q_idx`.
225thread_local! {
226 static CURRENT_Q_IDX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
227}
228// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
229// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
230// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
231// back at every dequantization call site keyed on which plane it is doing.
232thread_local! {
233 static QUANT_DELTAS: std::cell::Cell<crate::quant::QuantDeltas> = const {
234 std::cell::Cell::new(crate::quant::QuantDeltas {
235 y_dc: 0,
236 u_dc: 0,
237 u_ac: 0,
238 v_dc: 0,
239 v_ac: 0,
240 })
241 };
242}
243// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
244// read, across every call on the current thread -- the gate's proof that a
245// `delta_q_present` stream actually reached the new reader.
246thread_local! {
247 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
248}
249
250/// Current value of [`DELTA_Q_HITS`].
251pub(crate) fn delta_q_hits() -> usize {
252 DELTA_Q_HITS.with(|c| c.get())
253}
254
255/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
256/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
257/// one), so it is always `0` here.
258fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
259 let d = QUANT_DELTAS.with(|c| c.get());
260 match plane_idx {
261 0 => (d.y_dc, 0),
262 1 => (d.u_dc, d.u_ac),
263 _ => (d.v_dc, d.v_ac),
264 }
265}
266
267/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
268/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
269/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
270/// A no-op when `delta_q_present` is unset, or when this block is not at the
271/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
272/// libaom, collapsed here to a position check since a partition tree's
273/// top-left leaf is the only block that can ever land there), or when that
274/// leaf both *is* the whole superblock and is `skip` (the one case libaom
275/// itself skips the read, state carrying over unchanged).
276fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
277 if !DELTA_Q_PRESENT.with(|c| c.get()) {
278 return;
279 }
280 let sb_mi = sb_mi_cur() as usize;
281 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
282 return;
283 }
284 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, which
285 // it computes against the 64x64 root; under a 128 superblock no leaf this
286 // decoder codes can be the whole superblock (the root is always SPLIT).
287 if is_whole_sb && !sb128() && skip {
288 return;
289 }
290 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
291 const DELTA_Q_SMALL: i32 = 3;
292 if abs >= DELTA_Q_SMALL {
293 let rem_bits = dec.literal(3) + 1;
294 let thr = (1i32 << rem_bits) + 1;
295 abs = dec.literal(rem_bits) as i32 + thr;
296 }
297 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
298 let reduced = if sign_negative { -abs } else { abs };
299 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
300 let res = DELTA_Q_RES.with(|c| c.get());
301 CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
302}
303
304// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
305// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
306thread_local! {
307 static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
308 static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
309 static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
310}
311// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
312// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
313// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
314// updates index 0 and every reader treats that as the value for all 4
315// indices (spec `read_delta_lf_params`'s own single-cdf branch).
316thread_local! {
317 static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
318}
319// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
320// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
321thread_local! {
322 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
323}
324
325/// Current value of [`DELTA_LF_HITS`].
326pub(crate) fn delta_lf_hits() -> usize {
327 DELTA_LF_HITS.with(|c| c.get())
328}
329
330/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
331/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
332/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
333/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
334/// read once into index 0 otherwise.
335fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
336 if !DELTA_LF_PRESENT.with(|c| c.get()) {
337 return;
338 }
339 let sb_mi = sb_mi_cur() as usize;
340 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
341 return;
342 }
343 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, which
344 // it computes against the 64x64 root; under a 128 superblock no leaf this
345 // decoder codes can be the whole superblock (the root is always SPLIT).
346 if is_whole_sb && !sb128() && skip {
347 return;
348 }
349 let multi = DELTA_LF_MULTI.with(|c| c.get());
350 let res = DELTA_LF_RES.with(|c| c.get());
351 let count = if multi { 4 } else { 1 };
352 let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
353 for i in 0..count {
354 let mut abs = if multi {
355 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
356 } else {
357 dec.symbol(&mut cdfs.delta_lf) as i32
358 };
359 const DELTA_LF_SMALL: i32 = 3;
360 if abs >= DELTA_LF_SMALL {
361 let rem_bits = dec.literal(3) + 1;
362 let thr = (1i32 << rem_bits) + 1;
363 abs = dec.literal(rem_bits) as i32 + thr;
364 }
365 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
366 let reduced = if sign_negative { -abs } else { abs };
367 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
368 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
369 }
370 CURRENT_DELTA_LF.with(|c| c.set(cur));
371}
372
373/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
374/// after `skip` is known at every block-decode call site. A no-op at
375/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
376/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
377/// `allow_intrabc`, so neither needs a separate check here. Reads once per
378/// superblock, at the first non-skip block.
379fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
380 let bits = CDEF_BITS.with(|c| c.get());
381 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
382 return;
383 }
384 let idx = dec.literal(u32::from(bits)) as u8;
385 CDEF_TRANSMITTED.with(|c| c.set(true));
386 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
387 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
388 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
389 if sb_cols > 0 {
390 CDEF_IDX_GRID.with(|g| {
391 let mut g = g.borrow_mut();
392 let i = sb_r * sb_cols + sb_c;
393 if i < g.len() {
394 g[i] = idx;
395 }
396 });
397 }
398}
399
400// ---------------------------------------------------------------------------
401// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
402// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
403// the two consumers a real stream exercises: the per-segment quantizer index
404// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
405// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
406// `read_intra_segment_id`/`read_inter_segment_id` and
407// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
408// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
409// is what the oracle every gate here compares against actually does.
410thread_local! {
411 static SEG: std::cell::RefCell<SegmentationParams> =
412 std::cell::RefCell::new(SegmentationParams::default());
413 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
414 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
415 static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
416 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
417 /// this frame has no primary reference (spec `load_previous_segment_ids`).
418 static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
419 /// `(mi_rows, mi_cols)` for both maps above.
420 static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
421 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
422 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
423 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
424 static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
425 static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
426 /// The block currently being decoded -- read back by [`block_q_idx`].
427 static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
428 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
429 static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
430 /// How many real `segment_id` symbols were read, and the set of segment
431 /// ids any block ended up with -- the gate's proof the feature fired.
432 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
433 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
434 /// How many `seg_id_predicted` symbols were read (temporal update).
435 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
436}
437
438/// Installs this frame's segmentation parameters and allocates its map, with
439/// `prev` the primary reference frame's saved map (spec
440/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
441/// slot). Called once per frame, whether or not segmentation is enabled.
442pub(crate) fn set_segmentation(
443 seg: SegmentationParams,
444 mi_rows: usize,
445 mi_cols: usize,
446 prev: Option<&[u8]>,
447) {
448 SEG.with(|s| *s.borrow_mut() = seg);
449 SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));
450 SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
451 PREV_SEG_IDS.with(|m| {
452 let mut m = m.borrow_mut();
453 m.clear();
454 if let Some(p) = prev {
455 if p.len() == mi_rows * mi_cols {
456 m.extend_from_slice(p);
457 }
458 }
459 });
460 ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
461 LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
462 CUR_SEGMENT_ID.with(|c| c.set(0));
463}
464
465/// This frame's decoded segment map, to be stored into whichever reference
466/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
467pub(crate) fn take_segment_ids() -> Vec<u8> {
468 SEG_IDS.with(|m| m.borrow().clone())
469}
470
471/// How many `segment_id` symbols have been read (never reset per frame).
472pub(crate) fn segment_id_hits() -> usize {
473 SEG_ID_HITS.with(|c| c.get())
474}
475
476/// How many distinct segment ids any decoded block has carried.
477pub(crate) fn segment_ids_seen() -> usize {
478 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
479}
480
481/// How many `seg_id_predicted` symbols have been read (temporal update).
482pub(crate) fn segment_pred_hits() -> usize {
483 SEG_PRED_HITS.with(|c| c.get())
484}
485
486/// Resets the segmentation hit counters (gate setup).
487pub(crate) fn reset_segment_hits() {
488 SEG_ID_HITS.with(|c| c.set(0));
489 SEG_IDS_SEEN.with(|c| c.set(0));
490 SEG_PRED_HITS.with(|c| c.set(0));
491}
492
493/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
494/// being decoded, with its `FeatureData` value.
495fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
496 SEG.with(|s| {
497 let s = s.borrow();
498 s.feature_active(segment_id, feature)
499 .then(|| i32::from(s.feature_data[segment_id][feature]))
500 })
501}
502
503/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
504/// `av1_get_qindex`) for the block currently being decoded: the running
505/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
506/// Every dequant call site reads the block's quantizer through here.
507fn block_q_idx() -> i32 {
508 let base = CURRENT_Q_IDX.with(|c| c.get());
509 let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
510 match seg_feature(seg_id, SEG_LVL_ALT_Q) {
511 Some(data) => (base + data).clamp(0, 255),
512 None => base,
513 }
514}
515
516/// The segment id recorded for one mi cell of the current frame's map.
517fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {
518 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
519 if mi_r >= mi_rows || mi_c >= mi_cols {
520 return 0;
521 }
522 SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
523}
524
525/// `set_segment_id`: stamps `id` over every mi cell this block covers.
526fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {
527 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
528 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
529 SEG_IDS.with(|m| {
530 let mut m = m.borrow_mut();
531 for y in 0..y_mis {
532 for x in 0..x_mis {
533 m[(mi_r + y) * mi_cols + mi_c + x] = id;
534 }
535 }
536 });
537 CUR_SEGMENT_ID.with(|c| c.set(id));
538 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
539}
540
541/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
542/// `last_frame_seg_map`): the minimum previous-frame segment id over the
543/// block's own mi footprint. `0` when there is no previous map.
544fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {
545 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
546 PREV_SEG_IDS.with(|m| {
547 let m = m.borrow();
548 if m.is_empty() {
549 return 0;
550 }
551 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
552 let mut id = u8::MAX;
553 for y in 0..y_mis {
554 for x in 0..x_mis {
555 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
556 }
557 }
558 if id == u8::MAX { 0 } else { id }
559 })
560}
561
562/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
563fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
564 if reference == 0 {
565 return diff;
566 }
567 if reference >= max - 1 {
568 return max - diff - 1;
569 }
570 let half = if 2 * reference < max {
571 diff <= 2 * reference
572 } else {
573 diff <= 2 * (max - reference - 1)
574 };
575 if half {
576 return if diff & 1 != 0 {
577 reference + ((diff + 1) >> 1)
578 } else {
579 reference - (diff >> 1)
580 };
581 }
582 if 2 * reference < max { diff } else { max - (diff + 1) }
583}
584
585/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
586/// frame's already-decoded above/left/above-left neighbours.
587fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
588 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
589 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
590 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));
591 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
592 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
593 let ctx = match prev_ul {
594 None => 0,
595 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
596 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
597 Some(_) => 0,
598 };
599 let pred = match (prev_u, prev_l) {
600 (None, l) => l.unwrap_or(0),
601 (Some(u), None) => u,
602 (Some(u), Some(l)) => {
603 if prev_ul == Some(u) {
604 u
605 } else {
606 l
607 }
608 }
609 };
610 (pred, ctx)
611}
612
613/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
614/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
615/// that prediction. Does NOT write the map -- callers do.
616fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {
617 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
618 if skip {
619 return pred as u8;
620 }
621 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
622 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
623 let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));
624 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
625}
626
627/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
628/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
629/// caller decides which by passing `pre_skip`).
630fn intra_segment_id(
631 dec: &mut SymbolDecoder,
632 cdfs: &mut Cdfs,
633 mi_r: usize,
634 mi_c: usize,
635 w_mi: usize,
636 h_mi: usize,
637 skip: bool,
638) {
639 if !SEG.with(|s| s.borrow().enabled) {
640 return;
641 }
642 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
643 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
644}
645
646/// Whether this frame's intra blocks read their `segment_id` before `skip`
647/// (`SegIdPreSkip`); `false` also when segmentation is off.
648fn seg_id_pre_skip() -> bool {
649 SEG.with(|s| {
650 let s = s.borrow();
651 s.enabled && s.seg_id_pre_skip
652 })
653}
654
655/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
656/// Called at both spec positions of an inter frame's block: `pre_skip = true`
657/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
658fn inter_segment_id(
659 dec: &mut SymbolDecoder,
660 cdfs: &mut Cdfs,
661 mi_r: usize,
662 mi_c: usize,
663 w_mi: usize,
664 h_mi: usize,
665 skip: bool,
666 pre_skip: bool,
667) {
668 let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
669 let s = s.borrow();
670 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
671 });
672 if !enabled {
673 return;
674 }
675 if !update_map {
676 // The map is inherited wholesale from the previous frame.
677 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
678 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
679 return;
680 }
681 if pre_skip && !pre_skip_frame {
682 return;
683 }
684 if !pre_skip && skip {
685 // libaom: a skipped block never codes `seg_id_predicted`, and its
686 // segment id is the spatial prediction.
687 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
688 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
689 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
690 return;
691 }
692 let id = if temporal_update {
693 let ctx = seg_pred_ctx(mi_r, mi_c);
694 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
695 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
696 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));
697 if predicted {
698 predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
699 } else {
700 read_segment_id(dec, cdfs, mi_r, mi_c, false)
701 }
702 } else {
703 read_segment_id(dec, cdfs, mi_r, mi_c, false)
704 };
705 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
706}
707
708/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
709fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
710 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
711 // so contribute 0) outside the tile -- the availability check here is
712 // what keeps a previous tile's stamps out of this tile's context.
713 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
714 let above = if mi_r > row0 {
715 ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
716 } else {
717 0
718 };
719 let left = if mi_c > col0 {
720 LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
721 } else {
722 0
723 };
724 usize::from(above + left)
725}
726
727/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
728fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {
729 ABOVE_SEG_PRED.with(|m| {
730 let mut m = m.borrow_mut();
731 for i in 0..w_mi {
732 if let Some(cell) = m.get_mut(mi_c + i) {
733 *cell = value;
734 }
735 }
736 });
737 LEFT_SEG_PRED.with(|m| {
738 let mut m = m.borrow_mut();
739 for i in 0..h_mi {
740 if let Some(cell) = m.get_mut(mi_r + i) {
741 *cell = value;
742 }
743 }
744 });
745}
746
747// How many key-frame luma blocks resolved `smooth_neighbor` (spec
748// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
749// counter, proving a stream actually put a directional block next to a
750// smooth-predicted neighbour rather than every block reading the (previously
751// hardcoded `false`) edge-filter strength bucket unchanged.
752thread_local! {
753 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
754 const { std::cell::Cell::new(0) };
755}
756
757/// Current value of [`SMOOTH_LUMA_HITS`].
758pub(crate) fn smooth_luma_hits() -> usize {
759 SMOOTH_LUMA_HITS.with(|c| c.get())
760}
761
762thread_local! {
763 /// lane-band46 r1: how many split-transform units answered their intra
764 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
765 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
766 /// apply to them (class reach-is-per-transform-unit). Every hit is a
767 /// transform unit whose above-right / below-left reference samples would
768 /// be wrong without that fix.
769 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
770 const { std::cell::Cell::new(0) };
771}
772
773/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
774pub(crate) fn split_tu_reach_fix_hits() -> usize {
775 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
776}
777
778/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
779/// answer differs from the standalone-block answer the call sites used before
780/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
781/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
782/// block's top-left `(px, py)`.
783#[allow(clippy::too_many_arguments)]
784fn tu_reach(
785 bw: usize,
786 bh: usize,
787 col_off: usize,
788 row_off: usize,
789 tx: usize,
790 block: Reach,
791 px: usize,
792 py: usize,
793 width: usize,
794 height: usize,
795) -> Reach {
796 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
797 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height);
798 if fixed != standalone {
799 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));
800 }
801 fixed
802}
803
804// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
805// across every call on the current thread -- lane-chroma r3's own before/after
806// counter, proving a stream actually exercised chroma's smooth/paeth
807// predictor (the previously-refused round-2 gap) rather than every block
808// landing on DC/CFL/directional.
809thread_local! {
810 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
811 const { std::cell::Cell::new(0) };
812}
813
814/// Current value of [`SMOOTH_UV_HITS`].
815pub(crate) fn smooth_uv_hits() -> usize {
816 SMOOTH_UV_HITS.with(|c| c.get())
817}
818
819// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
820// full superblock walk over, across every call on the current thread --
821// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
822// multi-tile stream must prove more than one tile actually fired, not just
823// that the stream carried tile_info.cols > 1.
824thread_local! {
825 static TILE_HITS: std::cell::Cell<usize> =
826 const { std::cell::Cell::new(0) };
827}
828/// Current value of [`TILE_HITS`].
829pub(crate) fn tile_hits() -> usize {
830 TILE_HITS.with(|c| c.get())
831}
832
833// How many 4-pixel deblocking edge groups [`edge_params`] has actually
834// selected for filtering, across every call on the current thread -- the same
835// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
836// exercised `apply_deblock` rather than every edge landing on level 0.
837thread_local! {
838 static DEBLOCK_HITS: std::cell::Cell<usize> =
839 const { std::cell::Cell::new(0) };
840}
841/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
842/// mirroring stream.rs's `pictures_decoded` so the two dumps index
843/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
844static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
845 std::sync::atomic::AtomicUsize::new(0);
846
847/// Current value of [`DEBLOCK_HITS`].
848pub(crate) fn deblock_hits() -> usize {
849 DEBLOCK_HITS.with(|c| c.get())
850}
851
852// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
853// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
854// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
855// stream built with `--enable-onesided-comp=1` really exercised the
856// `uni_comp_ref` alphabet rather than only bidirectional pairs.
857thread_local! {
858 static UNI_COMP_HITS: std::cell::Cell<usize> =
859 const { std::cell::Cell::new(0) };
860}
861
862/// Current value of [`UNI_COMP_HITS`].
863pub(crate) fn uni_comp_hits() -> usize {
864 UNI_COMP_HITS.with(|c| c.get())
865}
866
867// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
868// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
869// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
870// blend and not only the wedge arm.
871thread_local! {
872 static DIFFWTD_HITS: std::cell::Cell<usize> =
873 const { std::cell::Cell::new(0) };
874}
875
876/// Current value of [`DIFFWTD_HITS`].
877pub(crate) fn diffwtd_hits() -> usize {
878 DIFFWTD_HITS.with(|c| c.get())
879}
880
881// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
882// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
883// this decoder's square inter path reaches), so no `compound_type` symbol is
884// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
885// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
886thread_local! {
887 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
888 const { std::cell::Cell::new(0) };
889}
890
891/// Current value of [`DIFFWTD_INFERRED_HITS`].
892pub(crate) fn diffwtd_inferred_hits() -> usize {
893 DIFFWTD_INFERRED_HITS.with(|c| c.get())
894}
895
896// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
897// with `show_frame == 0`, output later by a `show_existing_frame` header
898// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
899// `stream::decode_stream`, which is where the frame header is consumed; the
900// gate's proof that the on-value really reached the bitstream rather than
901// being dropped by the rate control.
902thread_local! {
903 static FWD_KF_HITS: std::cell::Cell<usize> =
904 const { std::cell::Cell::new(0) };
905}
906
907/// Current value of [`FWD_KF_HITS`].
908pub(crate) fn fwd_kf_hits() -> usize {
909 FWD_KF_HITS.with(|c| c.get())
910}
911
912/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
913pub(crate) fn note_fwd_kf() {
914 FWD_KF_HITS.with(|c| c.set(c.get() + 1));
915}
916
917// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
918// the block's own side, across every call on the current thread -- the same
919// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
920// actually exercised a *split* transform under `TxMode::Select` rather than
921// every block coincidentally resolving `depth=0` (indistinguishable from
922// `TxMode::Largest` pixel-wise).
923thread_local! {
924 static TX_DEPTH_HITS: std::cell::Cell<usize> =
925 const { std::cell::Cell::new(0) };
926}
927
928// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
929// transform smaller than their own side (`tx_depth != 0`) while coding a
930// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
931// only exercises with aomenc's tx-size search left ON (its default), which
932// every older recipe in this file pins off. Counted at the block, so a stream
933// where RD happened to give every split-transform block a DC chroma mode
934// reads as zero rather than silently passing for free.
935thread_local! {
936 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
937 const { std::cell::Cell::new(0) };
938}
939
940/// Current value of [`SQ_CHROMA_TX_HITS`].
941pub(crate) fn sq_chroma_tx_hits() -> usize {
942 SQ_CHROMA_TX_HITS.with(|c| c.get())
943}
944
945/// Current value of [`TX_DEPTH_HITS`].
946pub(crate) fn tx_depth_hits() -> usize {
947 TX_DEPTH_HITS.with(|c| c.get())
948}
949
950// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
951// read, and how many of those actually took the split, on the current thread
952// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
953// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
954// coincidentally coding one whole-block transform.
955thread_local! {
956 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
957 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
958 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
959 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
960 // `decode_inter_block` already carries forty parameters and both are
961 // frame-constant.
962 static TX_SELECT_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
963 static REDUCED_TX_SET_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
964 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
965 // frame-constant like the two above and stashed the same way -- an intra
966 // block inside an inter frame reads `use_filter_intra` under it.
967 static ENABLE_FILTER_INTRA_INTER: std::cell::Cell<bool> =
968 const { std::cell::Cell::new(false) };
969}
970
971/// Current value of [`TXFM_SPLIT_READS`].
972pub(crate) fn txfm_split_reads() -> usize {
973 TXFM_SPLIT_READS.with(|c| c.get())
974}
975
976/// Current value of [`TXFM_SPLIT_HITS`].
977pub(crate) fn txfm_split_hits() -> usize {
978 TXFM_SPLIT_HITS.with(|c| c.get())
979}
980
981/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
982/// [`ENABLE_FILTER_INTRA_INTER`].
983pub(crate) fn set_inter_tx_mode(
984 tx_select: bool,
985 reduced_tx_set: bool,
986 enable_filter_intra: bool,
987) {
988 TX_SELECT_INTER.with(|c| c.set(tx_select));
989 REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));
990 ENABLE_FILTER_INTRA_INTER.with(|c| c.set(enable_filter_intra));
991}
992
993// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
994// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
995// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
996// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
997// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
998// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
999// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1000// path above).
1001thread_local! {
1002 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1003 const { std::cell::Cell::new(0) };
1004}
1005
1006/// Current value of [`VERT_B_INTRA_HITS`].
1007pub(crate) fn vert_b_intra_hits() -> usize {
1008 VERT_B_INTRA_HITS.with(|c| c.get())
1009}
1010
1011// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1012// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1013// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1014// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1015// every arm separately so a run where aomenc's RD only picked one cannot
1016// pass as proof of four.
1017thread_local! {
1018 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1019}
1020
1021/// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1022thread_local! {
1023 /// 4x4 transform units decoded inside an 8x8 square of a
1024 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1025 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1026 /// a real `--enable-tx-size-search=1` stream reaches it.
1027 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1028}
1029
1030pub(crate) fn vert_ab_tx4_hits() -> usize {
1031 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1032}
1033
1034pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1035 AB16_HITS.with(std::cell::Cell::get)
1036}
1037
1038fn bump_ab16(arm: usize) {
1039 AB16_HITS.with(|c| {
1040 let mut v = c.get();
1041 v[arm] += 1;
1042 c.set(v);
1043 });
1044}
1045
1046// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1047// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1048// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1049// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1050// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1051// superblock's z-order recursion, not raster mi position).
1052thread_local! {
1053 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1054 const { std::cell::Cell::new(0) };
1055}
1056
1057/// Current value of [`HORZ_VERT_INTRA_HITS`].
1058pub(crate) fn horz_vert_intra_hits() -> usize {
1059 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1060}
1061
1062// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1063// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1064// the case every rect path here refused by name before, and the first
1065// refusal the user's ReelB extract (600s in) stops at.
1066thread_local! {
1067 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1068 const { std::cell::Cell::new(0) };
1069}
1070
1071/// Current value of [`RECT_SPLIT_TX_HITS`].
1072pub(crate) fn rect_split_tx_hits() -> usize {
1073 RECT_SPLIT_TX_HITS.with(|c| c.get())
1074}
1075
1076// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1077// side 64) AND split past the first depth, i.e. tiled more than one unit in
1078// each axis -- the only shape with a transform unit that has neighbours on
1079// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1080// no gate fired before lane-rectsplit r2 (the shared counter above also
1081// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1082thread_local! {
1083 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1084 const { std::cell::Cell::new(0) };
1085}
1086
1087/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1088pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1089 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1090}
1091
1092// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1093// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1094// chroma half takes that had no coefficient tables before (index order:
1095// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1096// proves the pair it happens to hit cannot catch a transposed scan/context
1097// table (class scan-weights-cross-axis).
1098thread_local! {
1099 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1100 const { std::cell::Cell::new([0; 4]) };
1101}
1102
1103/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1104pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1105 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1106}
1107
1108// How many HORZ/VERT intra strips actually predicted with filter intra
1109// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1110// ("this decoder predicts square-only") until `predict_filter_intra` took
1111// `bw`x`bh`.
1112thread_local! {
1113 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1114 const { std::cell::Cell::new(0) };
1115}
1116
1117/// Current value of [`FILTER_INTRA_RECT_HITS`].
1118pub(crate) fn filter_intra_rect_hits() -> usize {
1119 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1120}
1121
1122// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1123// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1124// was never read at all before that round, so a gate needs to prove the flag
1125// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1126// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1127// carry different probabilities (18101 vs 20229), so a transposed pair is
1128// only caught by a gate that sees the flag fire on BOTH shapes (class
1129// scan-weights-cross-axis).
1130thread_local! {
1131 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1132 const { std::cell::Cell::new(0) };
1133 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1134 const { std::cell::Cell::new(0) };
1135}
1136
1137/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1138pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1139 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1140}
1141
1142/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1143pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1144 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1145}
1146
1147// How many rectangular transform units actually coded coefficients through
1148// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1149// exercised the rect coefficient reader at all rather than passing on
1150// all-skip blocks.
1151thread_local! {
1152 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1153 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1154}
1155
1156/// Current value of [`RECT_COEFF_TU_HITS`].
1157pub(crate) fn rect_coeff_tu_hits() -> usize {
1158 RECT_COEFF_TU_HITS.with(|c| c.get())
1159}
1160
1161/// Rectangular transform units whose resolved `tx_type` is a 1D class
1162/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1163/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1164/// for the square reader's own 1D types.
1165pub(crate) fn rect_class1_hits() -> usize {
1166 RECT_CLASS1_HITS.with(|c| c.get())
1167}
1168
1169// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1170// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1171// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1172// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1173// prove nothing about the new shapes.
1174thread_local! {
1175 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1176 const { std::cell::Cell::new(0) };
1177}
1178
1179/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1180pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1181 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1182}
1183
1184// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1185// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1186// counter would be satisfied by a 16x8 strip and prove nothing here.
1187thread_local! {
1188 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1189 const { std::cell::Cell::new(0) };
1190}
1191
1192/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1193pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1194 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1195}
1196
1197// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1198// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1199// call on the current thread -- the same before/after counter pattern as
1200// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1201// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1202// landing on `DCT_DCT`.
1203thread_local! {
1204 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1205 const { std::cell::Cell::new(0) };
1206}
1207
1208// How many `uv_mode` reads resolved to a directional chroma mode (neither
1209// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1210// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1211// actually exercised chroma's own directional predictor.
1212thread_local! {
1213 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1214 const { std::cell::Cell::new(0) };
1215}
1216
1217/// Current value of [`DIRECTIONAL_UV_HITS`].
1218pub(crate) fn directional_uv_hits() -> usize {
1219 DIRECTIONAL_UV_HITS.with(|c| c.get())
1220}
1221
1222// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1223// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1224// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1225// proving a stream actually exercised a nonzero angle delta.
1226thread_local! {
1227 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1228 const { std::cell::Cell::new(0) };
1229}
1230
1231// How many [`read_single_ref`] reads resolved to a reference other than
1232// `LAST_FRAME`, across every call on the current thread -- the same before/after
1233// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1234// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1235// only other supported one so far) rather than every block coincidentally
1236// resolving `LAST_FRAME`.
1237thread_local! {
1238 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1239 const { std::cell::Cell::new(0) };
1240}
1241
1242/// Current value of [`NON_LAST_REF_HITS`].
1243pub(crate) fn non_last_ref_hits() -> usize {
1244 NON_LAST_REF_HITS.with(|c| c.get())
1245}
1246
1247// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1248// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1249// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1250// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1251// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1252// `GOLDEN_FRAME` draw it did not ask for.
1253thread_local! {
1254 static LAST2_HITS: std::cell::Cell<usize> =
1255 const { std::cell::Cell::new(0) };
1256}
1257thread_local! {
1258 static LAST3_HITS: std::cell::Cell<usize> =
1259 const { std::cell::Cell::new(0) };
1260}
1261thread_local! {
1262 static GOLDEN_HITS: std::cell::Cell<usize> =
1263 const { std::cell::Cell::new(0) };
1264}
1265thread_local! {
1266 static BWDREF_HITS: std::cell::Cell<usize> =
1267 const { std::cell::Cell::new(0) };
1268}
1269thread_local! {
1270 static ALTREF2_HITS: std::cell::Cell<usize> =
1271 const { std::cell::Cell::new(0) };
1272}
1273thread_local! {
1274 static ALTREF_HITS: std::cell::Cell<usize> =
1275 const { std::cell::Cell::new(0) };
1276}
1277
1278// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1279// -- proves a `reference_select` stream actually reached a block that picked
1280// compound, not just that the header bit was set. Every such block is
1281// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1282// so this only ever counts attempted reads, never a completed decode.
1283thread_local! {
1284 static COMP_MODE_HITS: std::cell::Cell<usize> =
1285 const { std::cell::Cell::new(0) };
1286}
1287
1288/// Current value of [`COMP_MODE_HITS`].
1289pub(crate) fn comp_mode_hits() -> usize {
1290 COMP_MODE_HITS.with(|c| c.get())
1291}
1292
1293// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1294// use for, across every call on the current thread -- the same before/after
1295// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1296// exercised palette reconstruction rather than only reading and refusing the
1297// `palette_y_mode` symbol.
1298thread_local! {
1299 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1300}
1301
1302/// Current value of [`PALETTE_HITS`].
1303pub(crate) fn palette_hits() -> usize {
1304 PALETTE_HITS.with(|c| c.get())
1305}
1306
1307// lane-tiles r12: of those, how many sat at their own TILE's left column --
1308// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1309// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1310// palette gate that never hits one proves nothing about the tile guard.
1311thread_local! {
1312 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1313}
1314
1315/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1316pub(crate) fn palette_tile_left_hits() -> usize {
1317 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1318}
1319
1320// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1321// palette use -- proves a stream actually reconstructed UV palette pixels,
1322// not just read and refused the `palette_uv_mode` symbol.
1323thread_local! {
1324 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1325}
1326
1327/// Current value of [`PALETTE_UV_HITS`].
1328pub(crate) fn palette_uv_hits() -> usize {
1329 PALETTE_UV_HITS.with(|c| c.get())
1330}
1331
1332// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1333// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1334// (not just the square path's) actually fired.
1335thread_local! {
1336 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1337}
1338
1339/// Current value of [`PALETTE_RECT_HITS`].
1340pub(crate) fn palette_rect_hits() -> usize {
1341 PALETTE_RECT_HITS.with(|c| c.get())
1342}
1343
1344// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1345// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1346// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1347// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1348// RD, almost always refused-on-use because the block doesn't end up USING a
1349// palette -- see r5's report). This is the site the removed refusal
1350// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1351// fired here whether or not the block picked a palette, so this is the
1352// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1353// never observes.
1354thread_local! {
1355 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1356}
1357
1358/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1359pub(crate) fn rect_screen_content_hits() -> usize {
1360 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1361}
1362
1363// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1364// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1365// windowing actually ran, not just that the whole-block path stayed exact.
1366// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1367// first actually incremented in r7, when the refusal it guarded was lifted.
1368thread_local! {
1369 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1370}
1371
1372/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1373pub(crate) fn palette_split_tx_hits() -> usize {
1374 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1375}
1376
1377// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
1378// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
1379// the gate's proof that the lifted path actually ran, per size.
1380thread_local! {
1381 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
1382 const { std::cell::Cell::new([0; 4]) };
1383}
1384
1385/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
1386pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
1387 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
1388}
1389
1390thread_local! {
1391 /// A just-decoded palette-Y block's own predicted pixels
1392 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1393 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1394 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1395 /// per-block override through `read_plane`'s two dozen call sites is the
1396 /// alternative this avoids). Always empty again once that call consumes
1397 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
1398 /// sees stale state.
1399 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1400 const { std::cell::RefCell::new(None) };
1401}
1402
1403
1404/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
1405/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
1406/// site whose reconstruct never runs would be picked up by the NEXT block's
1407/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1408/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1409#[track_caller]
1410fn set_palette_pred(buf: Vec<u16>) {
1411 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1412 let stale = PALETTE_PRED.with(|c| c.borrow().is_some());
1413 eprintln!(
1414 "PALSET len={} stale={stale} at {}",
1415 buf.len(),
1416 std::panic::Location::caller()
1417 );
1418 }
1419 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
1420}
1421
1422#[track_caller]
1423fn take_palette_pred() -> Option<Vec<u16>> {
1424 let got = PALETTE_PRED.with(|c| c.borrow_mut().take());
1425 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1426 eprintln!(
1427 "PALTAKE len={:?} at {}",
1428 got.as_ref().map(Vec::len),
1429 std::panic::Location::caller()
1430 );
1431 }
1432 got
1433}
1434
1435thread_local! {
1436 /// The current frame's `mi` grid, kept only while a frame header set
1437 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
1438 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
1439 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
1440 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
1441 /// does not allow intrabc (so nothing is paid for it).
1442 ///
1443 /// corner-cut: only [`decode_block`] (the square path) records into it,
1444 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
1445 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
1446 /// be wrong there; upgrade = record from the rect/leaf paths too.
1447 static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1448 const { std::cell::RefCell::new(None) };
1449 /// The block vector [`read_intra_mode`] just decoded, handed to
1450 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1451 /// which the alternative -- a tenth tuple member through every caller --
1452 /// already avoids). Always `.take()`n by the block that reads it.
1453 static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1454 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1455 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1456}
1457
1458/// Current value of [`INTRABC_HITS`].
1459pub(crate) fn intrabc_hits() -> usize {
1460 INTRABC_HITS.with(|c| c.get())
1461}
1462
1463/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
1464pub(crate) fn reset_intrabc_hits() {
1465 INTRABC_HITS.with(|c| c.set(0));
1466}
1467
1468/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1469/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1470/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1471/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1472fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1473 INTRABC_MI_GRID.with(|g| {
1474 let mut g = g.borrow_mut();
1475 let Some((grid, _, _)) = g.as_mut() else {
1476 return;
1477 };
1478 let info = crate::mvstack::MiInfo {
1479 is_inter: dv.is_some(),
1480 ref_frame: 0,
1481 ref_frame1: None,
1482 mv: dv.unwrap_or((0, 0)),
1483 mv1: None,
1484 is_new_mv: dv.is_some(),
1485 is_global_mv0: false,
1486 is_global_mv1: false,
1487 size: n4,
1488 size_h: n4,
1489 };
1490 for r in mi_r..mi_r + n4 {
1491 for c in mi_c..mi_c + n4 {
1492 grid.set(r, c, info);
1493 }
1494 }
1495 });
1496}
1497
1498// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
1499// proves a real `skip_mode_present` stream actually reached a block that
1500// picked it, not just that the frame header bit was set.
1501thread_local! {
1502 static SKIP_MODE_HITS: std::cell::Cell<usize> =
1503 const { std::cell::Cell::new(0) };
1504}
1505
1506/// Current value of [`SKIP_MODE_HITS`].
1507pub(crate) fn skip_mode_hits() -> usize {
1508 SKIP_MODE_HITS.with(|c| c.get())
1509}
1510
1511// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
1512// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
1513// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
1514// reached [`obmc_blend`], not just the header bit.
1515thread_local! {
1516 static OBMC_HITS: std::cell::Cell<usize> =
1517 const { std::cell::Cell::new(0) };
1518}
1519
1520// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
1521// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
1522// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
1523// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
1524// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
1525// decoder used to read with the wrong alphabet, so a gate that asserts this
1526// counter advanced proves the fixed path fired (class
1527// `gate-blind-to-feature`).
1528thread_local! {
1529 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1530}
1531
1532/// Current value of [`FIMV_ALPHABET_HITS`].
1533pub fn fimv_alphabet_hits() -> usize {
1534 FIMV_ALPHABET_HITS.with(|c| c.get())
1535}
1536
1537// lane-fimv r1: how many frame headers this decoder has decoded with
1538/// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
1539// prove the encoder really produced the header state under test rather than
1540// assume it.
1541thread_local! {
1542 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1543}
1544
1545/// Current value of [`FIMV_FRAME_HITS`].
1546pub fn fimv_frame_hits() -> usize {
1547 FIMV_FRAME_HITS.with(|c| c.get())
1548}
1549
1550/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
1551/// `force_integer_mv` bit is set.
1552pub fn note_force_integer_mv_frame() {
1553 FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1));
1554}
1555
1556/// Current value of [`OBMC_HITS`].
1557pub(crate) fn obmc_hits() -> usize {
1558 OBMC_HITS.with(|c| c.get())
1559}
1560
1561// lane-scaledref r1: per-case firing counts for the scaled-reference gate
1562// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
1563// reference would pass just as well and prove nothing, so the gate
1564// hard-asserts each combination this round lifts actually occurred:
1565// a compound block with a scaled tap, a warp block whose warp libaom
1566// suppresses because the reference is scaled, an OBMC block, an interintra
1567// block, and an 8x8 leaf.
1568thread_local! {
1569 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1570 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1571 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1572 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1573 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1574 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1575 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1576}
1577
1578/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
1579/// scaled and one unscaled tap.
1580pub(crate) fn mixed_scale_compound_hits() -> usize {
1581 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
1582}
1583
1584/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
1585/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
1586/// instead because their reference is scaled (libaom `motion_mode_allowed`,
1587/// `blockd.h:1484`).
1588pub(crate) fn scaled_warp_suppressed_hits() -> usize {
1589 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
1590}
1591
1592/// Current value of [`SCALED_COMPOUND_HITS`].
1593pub(crate) fn scaled_compound_hits() -> usize {
1594 SCALED_COMPOUND_HITS.with(|c| c.get())
1595}
1596
1597/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
1598pub(crate) fn scaled_warp_fallback_hits() -> usize {
1599 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
1600}
1601
1602/// Current value of [`SCALED_OBMC_HITS`].
1603pub(crate) fn scaled_obmc_hits() -> usize {
1604 SCALED_OBMC_HITS.with(|c| c.get())
1605}
1606
1607/// Current value of [`SCALED_INTERINTRA_HITS`].
1608pub(crate) fn scaled_interintra_hits() -> usize {
1609 SCALED_INTERINTRA_HITS.with(|c| c.get())
1610}
1611
1612/// Current value of [`SCALED_BLOCK8_HITS`].
1613pub(crate) fn scaled_block8_hits() -> usize {
1614 SCALED_BLOCK8_HITS.with(|c| c.get())
1615}
1616
1617// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
1618// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
1619// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
1620// 8x8-leaf OBMC block apart from a 16x16+ one.
1621thread_local! {
1622 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1623}
1624
1625// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
1626// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
1627// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
1628// -- the gate's proof that a fixture really exercises the alphabet this
1629// round changed, even though the block itself still refuses (warp
1630// estimation/filter not ported).
1631thread_local! {
1632 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
1633 const { std::cell::Cell::new(0) };
1634}
1635
1636/// Current value of [`WARP_SELECTED_HITS`].
1637pub(crate) fn warp_selected_hits() -> usize {
1638 WARP_SELECTED_HITS.with(|c| c.get())
1639}
1640
1641// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
1642// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
1643// into the compound intermediate) rather than translationally -- the
1644// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
1645// really reached [`crate::warp::warp_affine_compound`].
1646thread_local! {
1647 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
1648 const { std::cell::Cell::new(0) };
1649}
1650
1651/// Current value of [`COMPOUND_WARP_HITS`].
1652pub(crate) fn compound_warp_hits() -> usize {
1653 COMPOUND_WARP_HITS.with(|c| c.get())
1654}
1655
1656// lane-gmaffine r1: how many blocks built their prediction from a
1657// SIX-parameter (`AFFINE`) global-motion model through
1658// `crate::warp::global_warp_params` -- the gate's proof that a stream really
1659// carried an AFFINE `global_motion_params` AND that a block was predicted
1660// with it, not merely that the header parsed one.
1661thread_local! {
1662 static AFFINE_GM_HITS: std::cell::Cell<usize> =
1663 const { std::cell::Cell::new(0) };
1664}
1665
1666/// Current value of [`AFFINE_GM_HITS`].
1667pub(crate) fn affine_gm_hits() -> usize {
1668 AFFINE_GM_HITS.with(|c| c.get())
1669}
1670
1671// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
1672// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
1673// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
1674// only once `find_projection` returned a usable model, unlike
1675// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
1676// proof that the leaf path itself fired, not the 16x16+ one.
1677thread_local! {
1678 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1679 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1680}
1681
1682/// Current value of [`GLOBALMV_HITS_8`].
1683pub(crate) fn globalmv_hits_8() -> usize {
1684 GLOBALMV_HITS_8.with(|c| c.get())
1685}
1686
1687/// Current value of [`WARP_HITS_8`].
1688pub(crate) fn warp_hits_8() -> usize {
1689 WARP_HITS_8.with(|c| c.get())
1690}
1691
1692// How many blocks decoded `interintra == 1` with the non-wedge blended
1693// prediction applied (lane-interintra r1) -- the gate's proof that a
1694// stream actually exercised interintra.
1695thread_local! {
1696 static INTERINTRA_HITS: std::cell::Cell<usize> =
1697 const { std::cell::Cell::new(0) };
1698}
1699
1700/// Current value of [`INTERINTRA_HITS`].
1701pub(crate) fn interintra_hits() -> usize {
1702 INTERINTRA_HITS.with(|c| c.get())
1703}
1704
1705// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
1706// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
1707// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
1708// gate fixture actually exercises this alphabet, even though the block
1709// still refuses (the mask blend itself is unported).
1710thread_local! {
1711 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
1712 const { std::cell::Cell::new(0) };
1713}
1714
1715/// Current value of [`MASKED_COMPOUND_HITS`].
1716pub(crate) fn masked_compound_hits() -> usize {
1717 MASKED_COMPOUND_HITS.with(|c| c.get())
1718}
1719
1720// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
1721// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
1722// actually exercised the wedge blend, not just the DIFFWTD half of
1723// `MASKED_COMPOUND_HITS`.
1724thread_local! {
1725 static WEDGE_HITS: std::cell::Cell<usize> =
1726 const { std::cell::Cell::new(0) };
1727}
1728
1729/// Current value of [`WEDGE_HITS`].
1730pub(crate) fn wedge_hits() -> usize {
1731 WEDGE_HITS.with(|c| c.get())
1732}
1733
1734// How many blocks decoded a real wedge-INTERINTRA block
1735// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
1736// a gate fixture exercised the wedge blend (fixed sign 0), not just the
1737// smooth arm counted by `INTERINTRA_HITS`.
1738thread_local! {
1739 static WII_HITS: std::cell::Cell<usize> =
1740 const { std::cell::Cell::new(0) };
1741}
1742
1743/// Current value of [`WII_HITS`].
1744pub(crate) fn wii_hits() -> usize {
1745 WII_HITS.with(|c| c.get())
1746}
1747
1748/// Current value of [`OBMC_HITS_8`].
1749pub(crate) fn obmc_hits_8() -> usize {
1750 OBMC_HITS_8.with(|c| c.get())
1751}
1752
1753// lane-rectgate r1: how many 32x32 quadrants actually decoded a
1754// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
1755// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
1756// `VERT_B` all still fall into the generic "a partition type this encoder
1757// never writes" refusal below) -- the gate's proof that a free-partition
1758// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
1759// coincidentally never selecting one.
1760thread_local! {
1761 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
1762 const { std::cell::Cell::new(0) };
1763}
1764
1765/// Current value of [`EXTENDED_PARTITION_HITS`].
1766pub(crate) fn extended_partition_hits() -> usize {
1767 EXTENDED_PARTITION_HITS.with(|c| c.get())
1768}
1769
1770// lane-partitions r1: how many 32x32 quadrants decoded a real
1771// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
1772// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
1773// gate's proof this round's arms actually fired.
1774thread_local! {
1775 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
1776 const { std::cell::Cell::new(0) };
1777}
1778
1779/// Current value of [`RECT_PARTITION_HITS`].
1780pub(crate) fn rect_partition_hits() -> usize {
1781 RECT_PARTITION_HITS.with(|c| c.get())
1782}
1783
1784// lane-inter8 r1: how many superblocks an inter tile coded as a single
1785// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
1786// static content, previously a named refusal).
1787thread_local! {
1788 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
1789 const { std::cell::Cell::new(0) };
1790}
1791
1792/// Current value of [`INTER_SB_NONE_HITS`].
1793pub(crate) fn inter_sb_none_hits() -> usize {
1794 INTER_SB_NONE_HITS.with(|c| c.get())
1795}
1796
1797// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
1798// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
1799// path has always run that loop, so only this counter proves the newly-lifted
1800// alphabet value fired.
1801thread_local! {
1802 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
1803 const { std::cell::Cell::new(0) };
1804}
1805
1806/// Current value of [`INTER_SUB16_SPLIT_HITS`].
1807pub(crate) fn inter_sub16_split_hits() -> usize {
1808 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
1809}
1810
1811// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
1812// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
1813// rect coefficient reader itself fired, not just the strip-level partition
1814// symbol [`RECT_PARTITION_HITS`] already counts.
1815thread_local! {
1816 static RECT_COEFF_HITS: std::cell::Cell<usize> =
1817 const { std::cell::Cell::new(0) };
1818}
1819
1820/// Current value of [`RECT_COEFF_HITS`].
1821pub(crate) fn rect_coeff_hits() -> usize {
1822 RECT_COEFF_HITS.with(|c| c.get())
1823}
1824
1825// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
1826// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
1827// charter's real-aomenc gate hard-asserts.
1828thread_local! {
1829 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
1830 const { std::cell::Cell::new(0) };
1831}
1832
1833/// Current value of [`RECT_LEAF_COEFF_HITS`].
1834pub(crate) fn rect_leaf_coeff_hits() -> usize {
1835 RECT_LEAF_COEFF_HITS.with(|c| c.get())
1836}
1837
1838// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
1839// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
1840// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
1841// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
1842thread_local! {
1843 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
1844 const { std::cell::Cell::new(0) };
1845}
1846
1847/// Current value of [`MODE_MI_OVERRIDE_HITS`].
1848pub(crate) fn mode_mi_override_hits() -> usize {
1849 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
1850}
1851
1852// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
1853// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
1854// mode from the previous tile, where libaom's `up_available`/`left_available`
1855// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
1856// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
1857// per superblock row in `start_row`, so the luma fallback cannot leak the way
1858// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
1859// the invariant that makes the coarse fallback safe.
1860thread_local! {
1861 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
1862 const { std::cell::Cell::new(0) };
1863}
1864
1865/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
1866pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
1867 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
1868}
1869
1870// lane-cfl r1: how many times a chroma intra-edge filter-type read
1871// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
1872// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
1873// r1 defect would have filtered a chroma edge with the wrong strength.
1874thread_local! {
1875 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
1876 const { std::cell::Cell::new(0) };
1877}
1878
1879/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
1880pub(crate) fn uv_mode_mi_override_hits() -> usize {
1881 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
1882}
1883
1884// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
1885// suppressed at a TILE edge that is not a frame edge -- the above/left
1886// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
1887// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
1888// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
1889// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
1890// above would decide this tile's chroma edge filter strength.
1891thread_local! {
1892 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
1893 const { std::cell::Cell::new(0) };
1894}
1895
1896/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
1897pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
1898 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
1899}
1900
1901// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
1902// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
1903// shapes the r1 chroma defect showed up on.
1904thread_local! {
1905 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1906 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1907}
1908
1909/// Current value of [`CFL_BLOCK_HITS`].
1910pub(crate) fn cfl_block_hits() -> usize {
1911 CFL_BLOCK_HITS.with(|c| c.get())
1912}
1913
1914/// Current value of [`UV_ANGLE_DELTA_HITS`].
1915pub(crate) fn uv_angle_delta_hits() -> usize {
1916 UV_ANGLE_DELTA_HITS.with(|c| c.get())
1917}
1918
1919// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
1920// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
1921// gate's proof this round's arms actually reached a real block, not just
1922// that `partition_w64` read one of those two symbol values.
1923thread_local! {
1924 static SB_RECT_HITS: std::cell::Cell<usize> =
1925 const { std::cell::Cell::new(0) };
1926}
1927
1928/// Current value of [`SB_RECT_HITS`].
1929pub(crate) fn sb_rect_hits() -> usize {
1930 SB_RECT_HITS.with(|c| c.get())
1931}
1932
1933// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
1934// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
1935// strip) fired. Real aomenc picks these at 64 even with
1936// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
1937// the counter the gate hard-asserts.
1938thread_local! {
1939 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
1940 const { std::cell::Cell::new([0; 4]) };
1941}
1942
1943/// Current value of [`SB_AB_HITS`], summed over the four arms.
1944pub(crate) fn sb_ab_hits() -> usize {
1945 SB_AB_HITS.with(|c| c.get().iter().sum())
1946}
1947
1948/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
1949/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
1950/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
1951/// proof of all four.
1952pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
1953 SB_AB_HITS.with(std::cell::Cell::get)
1954}
1955
1956// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
1957// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
1958// strips). Two counters, not one, because a gate that only proved "some 1:4
1959// strip fired" would pass on a stream that never coded the other axis, and
1960// every scan/context table this round added comes in a transposed pair.
1961thread_local! {
1962 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1963 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1964}
1965
1966/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
1967pub(crate) fn sb_rect4_horz_hits() -> usize {
1968 SB_RECT4_HORZ_HITS.with(|c| c.get())
1969}
1970
1971/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
1972pub(crate) fn sb_rect4_vert_hits() -> usize {
1973 SB_RECT4_VERT_HITS.with(|c| c.get())
1974}
1975
1976// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
1977// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
1978// strips), the arms the ReelB mid-film extract stops at.
1979thread_local! {
1980 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1981 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1982}
1983
1984/// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
1985/// a gate that only counted strips would pass on an all-skip stream, which
1986/// exercises none of the new scan/context tables.
1987thread_local! {
1988 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1989}
1990
1991// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
1992// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
1993// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
1994// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
1995// counts the same for a 16x8/8x16 strip below 16x16.
1996thread_local! {
1997 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1998 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1999 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2000}
2001
2002/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
2003pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
2004 (
2005 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
2006 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
2007 )
2008}
2009
2010/// Current value of `SUB16_SPLIT_HITS`.
2011pub(crate) fn sub16_split_hits() -> usize {
2012 SUB16_SPLIT_HITS.with(|c| c.get())
2013}
2014
2015/// Current value of `RECT4_COEFF_HITS`.
2016pub(crate) fn rect4_coeff_hits() -> usize {
2017 RECT4_COEFF_HITS.with(|c| c.get())
2018}
2019
2020/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
2021pub(crate) fn rect4_32_horz_hits() -> usize {
2022 RECT4_32_HORZ_HITS.with(|c| c.get())
2023}
2024
2025/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
2026pub(crate) fn rect4_32_vert_hits() -> usize {
2027 RECT4_32_VERT_HITS.with(|c| c.get())
2028}
2029
2030// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
2031// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
2032// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
2033// just inert-compiled. Zero forever on a passing gate means that gate's
2034// stream never carries `delta_q_present=1` through a rect64 block.
2035thread_local! {
2036 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
2037 const { std::cell::Cell::new(0) };
2038}
2039
2040/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
2041pub(crate) fn rect64_qidx_drift_hits() -> usize {
2042 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
2043}
2044
2045// lane-partab r1: how many 32x32 quadrants decoded an AB partition
2046// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
2047// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
2048// free-partition gate's proof this round's arms actually fired.
2049thread_local! {
2050 static PARTAB_HITS: std::cell::Cell<usize> =
2051 const { std::cell::Cell::new(0) };
2052}
2053
2054/// Current value of [`PARTAB_HITS`].
2055pub(crate) fn partab_hits() -> usize {
2056 PARTAB_HITS.with(|c| c.get())
2057}
2058
2059// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
2060// one counter per arm rather than one shared total -- the gate hard-asserts
2061// each of these individually nonzero so a recipe that only ever fires
2062// HORZ_A can't silently stand in for the whole set.
2063thread_local! {
2064 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
2065 const { std::cell::Cell::new(0) };
2066 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
2067 const { std::cell::Cell::new(0) };
2068 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
2069 const { std::cell::Cell::new(0) };
2070 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
2071 const { std::cell::Cell::new(0) };
2072}
2073
2074/// Current value of [`INTRA_HORZ_A_HITS`].
2075pub(crate) fn intra_horz_a_hits() -> usize {
2076 INTRA_HORZ_A_HITS.with(|c| c.get())
2077}
2078/// Current value of [`INTRA_HORZ_B_HITS`].
2079pub(crate) fn intra_horz_b_hits() -> usize {
2080 INTRA_HORZ_B_HITS.with(|c| c.get())
2081}
2082/// Current value of [`INTRA_VERT_A_HITS`].
2083pub(crate) fn intra_vert_a_hits() -> usize {
2084 INTRA_VERT_A_HITS.with(|c| c.get())
2085}
2086/// Current value of [`INTRA_VERT_B_HITS`].
2087pub(crate) fn intra_vert_b_hits() -> usize {
2088 INTRA_VERT_B_HITS.with(|c| c.get())
2089}
2090
2091// How many [`read_inter_compound_mode`] reads actually happened
2092// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
2093// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
2094// mvstack build), not just that `comp_mode` fired. Still refused right
2095// after (no MV assignment or MC wired), so this only counts attempted
2096// reads.
2097thread_local! {
2098 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
2099 const { std::cell::Cell::new(0) };
2100}
2101
2102/// Current value of [`COMPOUND_MODE_HITS`].
2103pub(crate) fn compound_mode_hits() -> usize {
2104 COMPOUND_MODE_HITS.with(|c| c.get())
2105}
2106
2107/// How many query blocks folded in at least one temporal MV candidate
2108/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
2109/// temporal-MV gate's own firing counter (lane-av1tmvp).
2110///
2111/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
2112/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
2113/// this file (`decode_inter_block`) still passes `tpl: None` -- this
2114/// counter compiles and the projection math it counts is unit-tested
2115/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
2116/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
2117/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
2118/// against any real stream today. See the module doc on
2119/// `crate::motion_field` and this crate's ledger for the remaining wiring.
2120pub(crate) fn tmv_hits() -> usize {
2121 crate::mvstack::tmv_hits()
2122}
2123
2124/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
2125/// produced on this thread, the 10-bit inter gate's firing proof.
2126pub(crate) fn inter_pred_hits() -> usize {
2127 crate::mc::inter_pred_hits()
2128}
2129
2130/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
2131/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
2132/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
2133/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
2134/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
2135/// needs to turn a query block's own resolved `ref_frame` into
2136/// `TplArgs::cur_offset_0` (spec 7.9.3).
2137pub(crate) struct TplFrameArgs<'a> {
2138 pub field: &'a crate::motion_field::TplField,
2139 pub order_hint_bits: u32,
2140 pub order_hint: u32,
2141 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
2142 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
2143 /// frame's own `ref_frame_idx` names for each single reference.
2144 pub ref_order_hints: [u32; 7],
2145}
2146
2147/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
2148/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
2149/// decoded `grid`: every 4x4 unit an inter block covers reads the same
2150/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
2151/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
2152/// exact — every block this crate ever codes is at least 8x8, so no 8x8
2153/// cell straddles two different blocks' values.
2154pub(crate) fn build_motion_field(
2155 grid: &MiGrid,
2156 mi_cols: usize,
2157 mi_rows: usize,
2158 order_hint: u32,
2159 ref_order_hints: [u32; 7],
2160) -> crate::motion_field::MotionField {
2161 let mut field =
2162 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
2163 for row in 0..mi_rows {
2164 for col in 0..mi_cols {
2165 if let Some(info) = grid.get(row, col)
2166 && info.is_inter
2167 && info.ref_frame > 0
2168 {
2169 field.set(
2170 row,
2171 col,
2172 crate::motion_field::SavedMv {
2173 mv: info.mv,
2174 ref_frame: info.ref_frame,
2175 },
2176 );
2177 }
2178 }
2179 }
2180 field
2181}
2182
2183/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
2184/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
2185pub(crate) fn ref_hits(ref_frame: i8) -> usize {
2186 let c = match ref_frame {
2187 LAST2_FRAME => &LAST2_HITS,
2188 LAST3_FRAME => &LAST3_HITS,
2189 GOLDEN_FRAME => &GOLDEN_HITS,
2190 BWDREF_FRAME => &BWDREF_HITS,
2191 ALTREF2_FRAME => &ALTREF2_HITS,
2192 ALTREF_FRAME => &ALTREF_HITS,
2193 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
2194 };
2195 c.with(|v| v.get())
2196}
2197
2198thread_local! {
2199 /// The sequence header's `enable_intra_edge_filter`, set once per
2200 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
2201 /// own read of it, kept off the call stack (see that function's own doc
2202 /// comment for why) rather than threaded through every `read_plane`/
2203 /// `decode_block`/`decode_leaf8` call between here and there.
2204 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2205}
2206
2207/// Set [`ENABLE_EDGE_FILTER`] for this thread.
2208///
2209/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
2210/// never did -- so an inter frame's intra blocks read whatever value the last
2211/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
2212/// harmless (its own key frame sets it first), but a caller that decodes an
2213/// inter frame directly, or a test harness running several streams on one
2214/// thread, inherits a foreign sequence's bit: decode stops being a pure
2215/// function of the bitstream. `decode_stream` now calls this once per stream
2216/// from the sequence header, which covers every frame including inter ones.
2217pub(crate) fn set_enable_edge_filter(value: bool) {
2218 ENABLE_EDGE_FILTER.with(|f| f.set(value));
2219}
2220
2221/// Current value of [`ANGLE_DELTA_HITS`].
2222pub(crate) fn angle_delta_hits() -> usize {
2223 ANGLE_DELTA_HITS.with(|c| c.get())
2224}
2225
2226/// Current value of [`TX_CLASS1_HITS`].
2227pub(crate) fn tx_class1_hits() -> usize {
2228 TX_CLASS1_HITS.with(|c| c.get())
2229}
2230
2231// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
2232// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
2233// bottom) this thread's decode actually reconstructed -- the same
2234// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
2235// genuinely exercised the sub-8x8 leaf path rather than every attempt
2236// coincidentally landing on `PARTITION_NONE`.
2237thread_local! {
2238 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2239}
2240
2241/// Current value of [`SUB8_SPLIT_HITS`].
2242pub(crate) fn sub8_split_hits() -> usize {
2243 SUB8_SPLIT_HITS.with(|c| c.get())
2244}
2245
2246// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
2247// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
2248// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
2249// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
2250// asserts on these two rather than a plain leaf count.
2251thread_local! {
2252 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2253 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2254 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
2255 /// two 4x4 transform units, predicted one after the other. A separate
2256 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
2257 /// the gate can prove THIS path fired.
2258 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2259 /// 16x8/8x16 intra strips whose prediction actually read past the block's
2260 /// own width (above-right) or height (below-left) -- the samples
2261 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
2262 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
2263 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2264 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
2265 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
2266 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2267}
2268
2269/// Current value of [`RECT8_SPLIT_TX_HITS`].
2270pub(crate) fn rect8_split_tx_hits() -> usize {
2271 RECT8_SPLIT_TX_HITS.with(|c| c.get())
2272}
2273
2274/// Current value of [`RECT_STRIP_PRED_HITS`].
2275pub(crate) fn rect_strip_pred_hits() -> usize {
2276 RECT_STRIP_PRED_HITS.with(|c| c.get())
2277}
2278
2279/// Current value of [`RECT_STRIP_REACH_HITS`].
2280pub(crate) fn rect_strip_reach_hits() -> usize {
2281 RECT_STRIP_REACH_HITS.with(|c| c.get())
2282}
2283
2284/// Current value of [`TX4X8_CODED_HITS`].
2285pub(crate) fn tx4x8_coded_hits() -> usize {
2286 TX4X8_CODED_HITS.with(|c| c.get())
2287}
2288
2289/// Current value of [`TX8X4_CODED_HITS`].
2290pub(crate) fn tx8x4_coded_hits() -> usize {
2291 TX8X4_CODED_HITS.with(|c| c.get())
2292}
2293
2294// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
2295// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
2296// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
2297// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
2298// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
2299// (`eob_pt_{16,64,128,256}_chroma_class1`).
2300thread_local! {
2301 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
2302 const { std::cell::Cell::new(0) };
2303}
2304
2305/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
2306pub(crate) fn chroma_eob_class1_hits() -> usize {
2307 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
2308}
2309
2310/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
2311/// `tx_type` put this block's `eob_pt` on the class-1 row.
2312fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
2313 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
2314 CHROMA_EOB_CLASS1_HITS.with(|c| c.set(c.get() + 1));
2315 }
2316}
2317
2318const SUB_MI: u32 = 4;
2319const MI: usize = 4;
2320const SB: usize = 64;
2321/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
2322/// (tile start, superblock-row start).
2323///
2324/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
2325/// `av1_get_partition_plane_context` reads its own zero-initialised
2326/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
2327/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
2328/// (64), which reads identically at every level up to 64x64 but sets the bit
2329/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
2330/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
2331/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
2332const NO_NEIGHBOUR_SIDE: usize = 128;
2333const BLOCK: usize = 32;
2334const SUB: usize = 16;
2335const TX32: usize = 32;
2336const TX16: usize = 16;
2337const TX8: usize = 8;
2338const TX4: usize = 4;
2339const DC_PRED: usize = 0;
2340/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
2341/// carries an angle delta — [`crate::tile`]'s own private copy of the same
2342/// constant.
2343const V_PRED: usize = 1;
2344const H_PRED: usize = 2;
2345/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
2346/// `Fimode_To_Intradir`, libaom `blockd.h`).
2347const D157_PRED: usize = 6;
2348/// The last directional mode, `D67_PRED`.
2349const D67_PRED: usize = 8;
2350/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
2351/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
2352/// codes anything else, so this decoder never reads anything else either.
2353const ANGLE_DELTA_ZERO: usize = 3;
2354const NUM_BASE_LEVELS: i32 = 2;
2355const COEFF_BASE_RANGE: i32 = 12;
2356const BR_STEP: i32 = 3;
2357const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
2358
2359/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
2360/// whose probability mass a superblock or block half outside the frame
2361/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
2362/// duplicated here (that module is another lane's territory this round) and
2363/// kept in step with it by the byte-exact round-trip tests below rather than
2364/// by sharing code.
2365const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
2366const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
2367
2368fn element_prob(cdf: &[u16], element: usize) -> u16 {
2369 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
2370}
2371
2372/// The two-symbol CDF a partial superblock/block's forced-split flag is read
2373/// with: the mass of `elements` becomes the probability of the one partition
2374/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
2375/// (the encoder's non-adapting counterpart to this read).
2376fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
2377 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
2378 [32768 - split, 32768, 0]
2379}
2380
2381fn unsupported(what: impl Into<String>) -> Error {
2382 Error::unsupported("AV1 tile", what.into())
2383}
2384
2385/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
2386/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
2387/// same rule.
2388pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
2389 match base_q_idx {
2390 0..=20 => 0,
2391 21..=60 => 1,
2392 61..=120 => 2,
2393 _ => 3,
2394 }
2395}
2396
2397/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
2398/// [`crate::tile`]'s writer generates its scan tables with.
2399fn default_scan(side: usize) -> Vec<u16> {
2400 let mut scan = Vec::with_capacity(side * side);
2401 for d in 0..(2 * side - 1) {
2402 let lo = d.saturating_sub(side - 1);
2403 let hi = d.min(side - 1);
2404 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
2405 if d % 2 == 0 {
2406 scan.extend(diagonal.rev());
2407 } else {
2408 scan.extend(diagonal);
2409 }
2410 }
2411 scan
2412}
2413
2414/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
2415/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
2416/// in, instead of the default zigzag. libaom's own tables are keyed by a
2417/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
2418/// physically column-major level buffer, but they decompose to the exact
2419/// same (row, col) walk as a flat row-major traversal of *our* row-major
2420/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
2421/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
2422/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
2423/// transposed (column 0 down every row, then column 1, ...).
2424fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
2425 class_scan_table_wh(side, side, class)
2426}
2427
2428/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
2429/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
2430/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
2431/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
2432/// transcribed with -- `mrow` is the plain row-major raster in our indexing
2433/// and `mcol` its transpose, at rect sizes exactly as at square ones.
2434fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
2435 match class {
2436 TxClass::Vert => (0..(w * h) as u16).collect(),
2437 TxClass::Horiz => (0..w)
2438 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
2439 .collect(),
2440 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
2441 }
2442}
2443
2444fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
2445 match scan_idx {
2446 0 => 0,
2447 i if i <= area / 8 => 1,
2448 i if i <= area / 4 => 2,
2449 _ => 3,
2450 }
2451}
2452
2453fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
2454 if row >= side || col >= side {
2455 0
2456 } else {
2457 grid[row * side + col]
2458 }
2459}
2460
2461/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
2462/// `txb_common.h`): everything but the two lone-axis-identity types this
2463/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
2464#[derive(Clone, Copy, PartialEq, Eq)]
2465enum TxClass {
2466 TwoD,
2467 Horiz,
2468 Vert,
2469}
2470
2471impl TxClass {
2472 fn of(tx_type: TxType) -> Self {
2473 match tx_type {
2474 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
2475 // key on axis alone -- FLIPADST is still ADST for this purpose.
2476 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
2477 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
2478 _ => Self::TwoD,
2479 }
2480 }
2481}
2482
2483/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
2484/// table (indexed by the position along the transform's *coded* axis --
2485/// `col` for horiz, `row` for vert) that places their contexts past the 2D
2486/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
2487/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
2488fn nz_map_ctx_offset_1d(i: usize) -> usize {
2489 match i {
2490 0 => 26,
2491 1 => 31,
2492 _ => 36,
2493 }
2494}
2495
2496fn base_ctx(
2497 grid: &[i32],
2498 side: usize,
2499 row: usize,
2500 col: usize,
2501 class: TxClass,
2502 rect_shape: Option<(usize, usize)>,
2503) -> usize {
2504 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
2505 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
2506 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
2507 // position through the full 1D neighbour sum and offset table. Skipping
2508 // that for every class desynced the last (DC) coefficient of a
2509 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
2510 // 0, which then read one extra `BR` symbol at the max and forced a
2511 // spurious third Golomb call).
2512 if class == TxClass::TwoD && row == 0 && col == 0 {
2513 return 0;
2514 }
2515 let offsets: [(usize, usize); 5] = match class {
2516 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
2517 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
2518 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
2519 };
2520 let mag: i32 = offsets
2521 .iter()
2522 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
2523 .sum();
2524 let ctx = ((mag + 1) >> 1).min(4) as usize;
2525 match class {
2526 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
2527 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
2528 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
2529 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
2530 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
2531 // strip, which own a genuinely different table from the square one
2532 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
2533 // square table vs the real ctx 13 the rect table gives).
2534 TxClass::TwoD => {
2535 // lane-rectsplit r4: apply libaom's GENERATING RULE
2536 // (`txb_common.h:199-209`) directly instead of indexing the
2537 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
2538 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
2539 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
2540 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
2541 // so 32 consecutive entries are one COLUMN: the [`cdf`]
2542 // transcriptions are `[col][row]` and this read had them as
2543 // `[row][col]` -- the transpose, i.e. the other shape's rule with
2544 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
2545 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
2546 // pins the rule against the tables over their whole 5x5 domain.
2547 if let Some((w, h)) = rect_shape {
2548 if std::env::var_os("EC_NZOFF_DUMP").is_some() {
2549 eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}");
2550 }
2551 if w < h && row < 2 {
2552 return ctx + 11;
2553 }
2554 if w > h && col < 2 {
2555 return ctx + 16;
2556 }
2557 }
2558 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2559 }
2560 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
2561 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
2562 }
2563}
2564
2565fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
2566 let extra = match class {
2567 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
2568 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
2569 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
2570 };
2571 let mag = neighbour(grid, side, row + 1, col).abs()
2572 + neighbour(grid, side, row, col + 1).abs()
2573 + extra;
2574 let mag = (((mag + 1) >> 1).min(6)) as usize;
2575 if row == 0 && col == 0 {
2576 return mag;
2577 }
2578 let near_origin = match class {
2579 TxClass::TwoD => row < 2 && col < 2,
2580 TxClass::Horiz => col == 0,
2581 TxClass::Vert => row == 0,
2582 };
2583 if near_origin { mag + 7 } else { mag + 14 }
2584}
2585
2586/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
2587/// transposed from libaom's column-major buffer into this decoder's row-major
2588/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
2589/// against the real table). Not the square zigzag formula generalized to
2590/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
2591const SCAN_32X16: [u16; 512] = [
2592 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
2593 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
2594 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
2595 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
2596 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
2597 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
2598 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
2599 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
2600 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
2601 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
2602 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
2603 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
2604 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
2605 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
2606 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
2607 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
2608 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
2609 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
2610 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
2611 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
2612 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
2613 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
2614 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
2615 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
2616 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
2617 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
2618 509, 478, 447, 510, 479, 511,
2619];
2620
2621/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
2622/// [`SCAN_32X16`]'s doc comment).
2623const SCAN_16X32: [u16; 512] = [
2624 0, 1, 16, 2, 17, 32, 3, 18, 33, 48, 4, 19, 34, 49, 64, 5, 20, 35, 50, 65, 80, 6, 21, 36, 51,
2625 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
2626 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
2627 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
2628 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
2629 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
2630 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
2631 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
2632 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
2633 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
2634 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
2635 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
2636 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
2637 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
2638 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
2639 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
2640 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
2641 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
2642 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
2643 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
2644 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
2645 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
2646 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
2647 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
2648 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
2649 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
2650];
2651
2652/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
2653/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
2654/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
2655/// the same source).
2656const SCAN_4X8: [u16; 32] = [
2657 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28,
2658 23, 26, 29, 27, 30, 31,
2659];
2660
2661/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
2662const SCAN_8X4: [u16; 32] = [
2663 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21, 14, 7,
2664 29, 22, 15, 30, 23, 31,
2665];
2666
2667/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
2668/// [`SCAN_32X16`]'s doc comment).
2669const SCAN_16X8: [u16; 128] = [
2670 0, 16, 1, 32, 17, 2, 48, 33, 18, 3, 64, 49, 34, 19, 4, 80, 65, 50, 35, 20, 5, 96, 81, 66, 51,
2671 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
2672 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
2673 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
2674 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
2675 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
2676];
2677
2678/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
2679/// [`SCAN_32X16`]'s doc comment).
2680const SCAN_8X16: [u16; 128] = [
2681 0, 1, 8, 2, 9, 16, 3, 10, 17, 24, 4, 11, 18, 25, 32, 5, 12, 19, 26, 33, 40, 6, 13, 20, 27, 34,
2682 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
2683 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
2684 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
2685 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
2686 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
2687];
2688
2689/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
2690/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
2691/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
2692/// scans column-major (`p = col * height + row`), so a naive copy of
2693/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
2694/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
2695/// are byte-identical to this decoder's [`SCAN_8X16`].
2696const SCAN_32X8: [u16; 256] = [
2697 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
2698 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
2699 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
2700 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
2701 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
2702 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
2703 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
2704 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
2705 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
2706 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
2707 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
2708 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
2709 222, 191, 254, 223, 255,
2710];
2711/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
2712/// 16x64 `PARTITION_VERT_4` strip).
2713const SCAN_8X32: [u16; 256] = [
2714 0, 1, 8, 2, 9, 16, 3, 10, 17, 24, 4, 11, 18, 25, 32, 5, 12, 19, 26, 33, 40, 6, 13, 20, 27, 34,
2715 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
2716 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
2717 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
2718 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
2719 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
2720 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
2721 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
2722 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
2723 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
2724 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
2725 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
2726 239, 246, 253, 247, 254, 255,
2727];
2728/// `Default_Scan_16x4`, this decoder's own row-major transcription of
2729/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
2730/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
2731/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
2732/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
2733/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
2734/// were emitted -- a naive copy installs the transpose (class
2735/// reference-layout-not-spec).
2736const SCAN_16X4: [u16; 64] = [
2737 0, 16, 1, 32, 17, 2, 48, 33, 18, 3, 49, 34, 19, 4, 50, 35, 20, 5, 51, 36, 21, 6, 52, 37, 22, 7,
2738 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
2739 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
2740];
2741/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
2742/// 8x32 `PARTITION_VERT_4` strip).
2743const SCAN_4X16: [u16; 64] = [
2744 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28,
2745 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
2746 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
2747];
2748
2749/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
2750/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
2751/// asymmetric-extent pattern).
2752fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
2753 if row >= h || col >= w {
2754 0
2755 } else {
2756 grid[row * w + col]
2757 }
2758}
2759
2760/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
2761/// the rect generalization is libaom's own comment in
2762/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
2763/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
2764/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
2765/// [`decode_block_rect`] codes (see that function's own doc comment).
2766fn base_ctx_rect(
2767 grid: &[i32],
2768 w: usize,
2769 h: usize,
2770 row: usize,
2771 col: usize,
2772 class: TxClass,
2773) -> usize {
2774 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
2775 // the 2D class short-circuits the DC position.
2776 if class == TxClass::TwoD && row == 0 && col == 0 {
2777 return 0;
2778 }
2779 let offsets: [(usize, usize); 5] = match class {
2780 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
2781 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
2782 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
2783 };
2784 let mag: i32 = offsets
2785 .iter()
2786 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
2787 .sum();
2788 let ctx = ((mag + 1) >> 1).min(4) as usize;
2789 match class {
2790 TxClass::TwoD => {
2791 if w < h && row < 2 {
2792 return ctx + 11;
2793 }
2794 if w > h && col < 2 {
2795 return ctx + 16;
2796 }
2797 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2798 }
2799 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
2800 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
2801 // position along one axis only).
2802 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
2803 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
2804 }
2805}
2806
2807/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
2808/// neighbour-offset math itself is shape-independent, only the boundary
2809/// clamp needs the real bound in each axis.
2810fn br_ctx_rect(
2811 grid: &[i32],
2812 w: usize,
2813 h: usize,
2814 row: usize,
2815 col: usize,
2816 class: TxClass,
2817) -> usize {
2818 let extra = match class {
2819 TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(),
2820 TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(),
2821 TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(),
2822 };
2823 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
2824 + neighbour_rect(grid, w, h, row, col + 1).abs()
2825 + extra;
2826 let mag = (((mag + 1) >> 1).min(6)) as usize;
2827 if row == 0 && col == 0 {
2828 return mag;
2829 }
2830 let near_origin = match class {
2831 TxClass::TwoD => row < 2 && col < 2,
2832 TxClass::Horiz => col == 0,
2833 TxClass::Vert => row == 0,
2834 };
2835 if near_origin { mag + 7 } else { mag + 14 }
2836}
2837
2838fn dc_vote(dc: Option<bool>) -> i32 {
2839 match dc {
2840 None => 0,
2841 Some(true) => -1,
2842 Some(false) => 1,
2843 }
2844}
2845
2846fn dc_sign_ctx(vote: i32) -> usize {
2847 match vote.signum() {
2848 0 => 0,
2849 -1 => 1,
2850 _ => 2,
2851 }
2852}
2853
2854/// The remainder of a level the base and base-range syntax could not reach
2855/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
2856/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
2857fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
2858 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
2859 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
2860 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
2861 // for every tail any encoder writes -- our own writer tops out at 19 zeros
2862 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
2863 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
2864 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
2865 // RED: seed 67 stops here today, and with the cap raised it decodes to a
2866 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
2867 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
2868 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
2869 // together with that defect's fix, not before.
2870 let mut length = 1u32;
2871 while dec.literal(1) == 0 {
2872 length += 1;
2873 if length > 20 {
2874 return Err(unsupported("a Golomb tail longer than this decoder reads"));
2875 }
2876 }
2877 let mut x = 1u32;
2878 for _ in 1..length {
2879 x = (x << 1) | dec.literal(1);
2880 }
2881 Ok(x - 1)
2882}
2883
2884/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
2885/// [`crate::tile`]'s `write_eob`.
2886fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
2887 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
2888 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
2889
2890 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2891 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
2892 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
2893 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
2894 // `eob_multi_ctx`). Missing that split desynced the very first
2895 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
2896 // against a real aomdec trace).
2897 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
2898 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
2899 (_, Some(class1)) => class1,
2900 };
2901 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2902 let (range, value) = dec.debug_state();
2903 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
2904 }
2905 let group = dec.symbol(eob_pt) + 1;
2906 if trace {
2907 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
2908 }
2909 let bits = OFFSET_BITS[group];
2910 let mut offset = 0u32;
2911 if bits > 0 {
2912 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
2913 if trace {
2914 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
2915 }
2916 offset = top << (bits - 1);
2917 if bits > 1 {
2918 offset |= dec.literal(bits - 1);
2919 }
2920 }
2921 GROUP_START[group] + offset as usize
2922}
2923
2924/// One transform block's levels, the inverse of [`crate::tile`]'s
2925/// `write_coeffs`, returned as a `side * side` grid in raster order, along
2926/// with the transform type that grid was coded under (`DCT_DCT` when the
2927/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
2928/// 64-point transforms, which never code anything else).
2929///
2930/// # Errors
2931/// Returns an error if the `tx_type` symbol decodes to a value outside its
2932/// CDF's own set (a corrupt or unsupported bitstream) — every value the
2933/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
2934/// produce dispatches to a real inverse transform.
2935/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
2936/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
2937/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
2938/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
2939/// the plane's own predicted mode instead. Every entry this table can
2940/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
2941/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
2942/// table ever names), so unlike the CDF-coded luma path there is no
2943/// ext-tx-set membership check to fall back from here.
2944fn default_intra_tx_type(mode: u8) -> TxType {
2945 use crate::intra::{
2946 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
2947 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
2948 };
2949 match mode {
2950 DC_PRED | D45_PRED => TxType::DctDct,
2951 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
2952 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
2953 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
2954 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
2955 }
2956}
2957
2958/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
2959/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
2960/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
2961fn is_smooth_mode(mode: usize) -> bool {
2962 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
2963}
2964
2965fn read_coeffs(
2966 dec: &mut SymbolDecoder,
2967 coding: &mut TxbTables,
2968 scan: &[u16],
2969 skip_ctx: usize,
2970 sign_ctx: usize,
2971 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
2972 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
2973 // nothing at all; `DctDct` for every luma call and every chroma call at
2974 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
2975 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
2976 default_tx_type: TxType,
2977 // `Some((w, h))` with `w != h` when this read is a superblock-level
2978 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
2979 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
2980 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
2981 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
2982 // caller's block genuinely is `side` x `side`.
2983 rect_shape: Option<(usize, usize)>,
2984) -> Result<(Vec<i32>, TxType)> {
2985 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2986 let side = coding.side;
2987 let mut grid = vec![0i32; side * side];
2988 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2989 let (range, value) = dec.debug_state();
2990 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
2991 }
2992 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
2993 if std::env::var_os("EC_TRACE_COEFF").is_some() {
2994 let (rng, _) = dec.debug_state();
2995 eprintln!(
2996 "EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero={} rng={rng}",
2997 all_zero as i32
2998 );
2999 }
3000 if std::env::var_os("EC_AV1_TELL").is_some() {
3001 eprintln!(
3002 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
3003 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
3004 );
3005 }
3006 if trace {
3007 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
3008 }
3009 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
3010 let (range, value) = dec.debug_state();
3011 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
3012 }
3013 if all_zero {
3014 return Ok((grid, TxType::DctDct));
3015 }
3016 let mut tx_type = default_tx_type;
3017 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
3018 // The CDF row's own width names its set (lane-cdffwd2: extended
3019 // past the original two-way intra split once wider `reduced_tx_set
3020 // == 0` inter sets joined the table): 17 slots (16 symbols) is
3021 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
3022 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
3023 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
3024 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
3025 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
3026 let len = tx_type_cdf.len();
3027 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
3028 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
3029 }
3030 let t = dec.symbol(tx_type_cdf);
3031 if std::env::var_os("EC_TRACE_COEFF").is_some() {
3032 let (rng, _) = dec.debug_state();
3033 eprintln!("EC_COEFF_STEP tag=tx_type rng={rng}");
3034 }
3035 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
3036 let (range, value) = dec.debug_state();
3037 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
3038 }
3039 if trace {
3040 eprintln!("TRACE tx_type value={t} len={len}");
3041 }
3042 tx_type = match len {
3043 17 => TxType::from_symbol_all16(t),
3044 13 => TxType::from_symbol_set2_12(t),
3045 8 => TxType::from_symbol_set1(t),
3046 _ => TxType::from_symbol(t),
3047 }
3048 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
3049 }
3050
3051 let class = TxClass::of(tx_type);
3052 if class != TxClass::TwoD {
3053 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3054 RECT_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3055 }
3056 let eob = read_eob(dec, coding, class);
3057 if trace {
3058 eprintln!("TRACE eob value={eob}");
3059 }
3060 let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some();
3061 if ec_trace_coeff {
3062 let (rng, _) = dec.debug_state();
3063 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
3064 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
3065 }
3066 let class_scan;
3067 let scan: &[u16] = if class == TxClass::TwoD {
3068 scan
3069 } else {
3070 class_scan = class_scan_table(side, class);
3071 &class_scan
3072 };
3073 let mut levels = vec![0i32; side * side];
3074 for scan_idx in (0..eob).rev() {
3075 let pos = scan[scan_idx] as usize;
3076 let (row, col) = (pos / side, pos % side);
3077 let level = if scan_idx == eob - 1 {
3078 let ctx = eob_coeff_ctx(scan_idx, side * side);
3079 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
3080 if trace {
3081 eprintln!(
3082 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
3083 );
3084 }
3085 v
3086 } else {
3087 let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
3088 let v = dec.symbol(&mut coding.base[ctx]) as i32;
3089 if ec_trace_coeff {
3090 let (rng, _) = dec.debug_state();
3091 // `pos` in libaom's column-major `coeff_idx` convention, so
3092 // the ladder lines up with instrumented `aomdec`.
3093 let apos = col * side + row;
3094 eprintln!(
3095 "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"
3096 );
3097 }
3098 if trace {
3099 eprintln!(
3100 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
3101 );
3102 }
3103 v
3104 };
3105 let level = if level > NUM_BASE_LEVELS {
3106 let ctx = br_ctx(&levels, side, row, col, class);
3107 let mut level = level;
3108 let mut sent = 0;
3109 loop {
3110 let k = dec.symbol(&mut coding.br[ctx]) as i32;
3111 if trace {
3112 eprintln!(
3113 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
3114 );
3115 }
3116 level += k;
3117 sent += BR_STEP;
3118 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
3119 break;
3120 }
3121 }
3122 level
3123 } else {
3124 level
3125 };
3126 if ec_trace_coeff && scan_idx == eob - 1 {
3127 let (rng, _) = dec.debug_state();
3128 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
3129 }
3130 levels[pos] = level;
3131 }
3132 if ec_trace_coeff {
3133 let (rng, _) = dec.debug_state();
3134 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
3135 }
3136
3137 for (c, &pos) in scan[..eob].iter().enumerate() {
3138 let level = levels[pos as usize];
3139 if level == 0 {
3140 continue;
3141 }
3142 let negative = if pos == 0 {
3143 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
3144 if trace {
3145 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
3146 }
3147 v
3148 } else {
3149 dec.literal(1) == 1
3150 };
3151 if ec_trace_coeff {
3152 let (rng, _) = dec.debug_state();
3153 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
3154 }
3155 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
3156 let g = read_golomb(dec)?;
3157 if trace {
3158 eprintln!("TRACE golomb pos={pos} value={g}");
3159 }
3160 level + g as i32
3161 } else {
3162 level
3163 };
3164 if ec_trace_coeff {
3165 let (rng, _) = dec.debug_state();
3166 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
3167 }
3168 grid[pos as usize] = if negative { -level } else { level };
3169 }
3170 Ok((grid, tx_type))
3171}
3172
3173/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
3174/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
3175/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
3176/// can ever produce, since every `tx_type` this decoder's rect sets can read
3177/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
3178/// rather than guess-decode if a non-2D class ever shows up here, since
3179/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
3180/// form for those.
3181fn read_coeffs_rect(
3182 dec: &mut SymbolDecoder,
3183 coding: &mut TxbTables,
3184 scan: &[u16],
3185 w: usize,
3186 h: usize,
3187 skip_ctx: usize,
3188 sign_ctx: usize,
3189 default_tx_type: TxType,
3190) -> Result<(Vec<i32>, TxType)> {
3191 let rect_trace = std::env::var_os("EC_TRACE_COEFF").is_some();
3192 let mut grid = vec![0i32; w * h];
3193 let entry_rng = dec.debug_state().0;
3194 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
3195 if rect_trace {
3196 eprintln!(
3197 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} all_zero={} rng={}",
3198 all_zero as i32,
3199 dec.debug_state().0
3200 );
3201 }
3202 if all_zero {
3203 return Ok((grid, TxType::DctDct));
3204 }
3205 RECT_COEFF_TU_HITS.with(|c| c.set(c.get() + 1));
3206 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
3207 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
3208 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
3209 // context offsets -- both of which now have rect forms
3210 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
3211 // The rect sets that carry no symbol at all still pass `None` here.
3212 let mut tx_type = default_tx_type;
3213 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
3214 let len = tx_type_cdf.len();
3215 let t = dec.symbol(tx_type_cdf);
3216 tx_type = match len {
3217 17 => TxType::from_symbol_all16(t),
3218 13 => TxType::from_symbol_set2_12(t),
3219 8 => TxType::from_symbol_set1(t),
3220 _ => TxType::from_symbol(t),
3221 }
3222 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
3223 if rect_trace {
3224 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
3225 }
3226 }
3227 let class = TxClass::of(tx_type);
3228 if class != TxClass::TwoD {
3229 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3230 }
3231 let eob = read_eob(dec, coding, class);
3232 if rect_trace {
3233 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
3234 }
3235 let class_scan;
3236 let scan: &[u16] = if class == TxClass::TwoD {
3237 scan
3238 } else {
3239 class_scan = class_scan_table_wh(w, h, class);
3240 &class_scan
3241 };
3242 let mut levels = vec![0i32; w * h];
3243 for scan_idx in (0..eob).rev() {
3244 let pos = scan[scan_idx] as usize;
3245 let (row, col) = (pos / w, pos % w);
3246 // libaom's column-major `coeff_idx`, for ladder comparison.
3247 let apos = col * h + row;
3248 let level = if scan_idx == eob - 1 {
3249 let ctx = eob_coeff_ctx(scan_idx, w * h);
3250 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
3251 if rect_trace {
3252 eprintln!(
3253 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
3254 dec.debug_state().0
3255 );
3256 }
3257 v
3258 } else {
3259 let ctx = base_ctx_rect(&levels, w, h, row, col, class);
3260 let v = dec.symbol(&mut coding.base[ctx]) as i32;
3261 if rect_trace {
3262 eprintln!(
3263 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
3264 dec.debug_state().0
3265 );
3266 }
3267 v
3268 };
3269 let level = if level > NUM_BASE_LEVELS {
3270 let ctx = br_ctx_rect(&levels, w, h, row, col, class);
3271 let mut level = level;
3272 let mut sent = 0;
3273 loop {
3274 let k = dec.symbol(&mut coding.br[ctx]) as i32;
3275 if rect_trace {
3276 eprintln!(
3277 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
3278 dec.debug_state().0
3279 );
3280 }
3281 level += k;
3282 sent += BR_STEP;
3283 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
3284 break;
3285 }
3286 }
3287 level
3288 } else {
3289 level
3290 };
3291 levels[pos] = level;
3292 if rect_trace {
3293 let (rng, _) = dec.debug_state();
3294 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
3295 }
3296 }
3297 if rect_trace {
3298 let (rng, _) = dec.debug_state();
3299 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
3300 }
3301 for &pos in &scan[..eob] {
3302 let level = levels[pos as usize];
3303 if level == 0 {
3304 continue;
3305 }
3306 let negative = if pos == 0 {
3307 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
3308 } else {
3309 dec.literal(1) == 1
3310 };
3311 if rect_trace {
3312 let (rng, _) = dec.debug_state();
3313 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} rng={rng}", u8::from(negative));
3314 }
3315 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
3316 let g = read_golomb(dec)?;
3317 level + g as i32
3318 } else {
3319 level
3320 };
3321 grid[pos as usize] = if negative { -level } else { level };
3322 }
3323 Ok((grid, tx_type))
3324}
3325
3326/// What one coded block leaves behind for the blocks that read it as a
3327/// neighbour: whether it coded anything at all, and the sign of its DC —
3328/// [`crate::tile`]'s own private `Neighbour`.
3329#[derive(Clone, Copy, Default)]
3330struct Neighbour {
3331 /// The transform unit's cumulative coefficient level (spec `cul_level`,
3332 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
3333 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
3334 /// boolean (`level != 0`) is enough for every context this decoder read
3335 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
3336 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
3337 /// needs the actual magnitude tier of its above/left neighbours, not
3338 /// just whether they coded anything.
3339 level: u8,
3340 dc: Option<bool>,
3341}
3342
3343fn neighbour_state(grid: &[i32]) -> Neighbour {
3344 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
3345 Neighbour {
3346 level: cul.min(7) as u8,
3347 dc: (grid[0] != 0).then_some(grid[0] < 0),
3348 }
3349}
3350
3351/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
3352/// transform unit smaller than the block it sits in): `top`/`left` are the
3353/// above/left neighbours' magnitude tiers, each already clamped to 4.
3354const SKIP_CONTEXTS: [[usize; 5]; 5] = [
3355 [1, 2, 2, 2, 3],
3356 [2, 4, 4, 4, 5],
3357 [2, 4, 4, 4, 5],
3358 [2, 4, 4, 4, 5],
3359 [3, 5, 5, 5, 6],
3360];
3361
3362/// The neighbour state a block's contexts are read from — a duplicate of
3363/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
3364/// territory this round), kept at the same two granularities the real writer
3365/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
3366/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
3367/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
3368/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
3369/// chroma transform straddling the true, odd-sized frame edge see its
3370/// neighbour's state clamped at its own subsampled edge rather than luma's.
3371struct Neighbours {
3372 above: Vec<[Neighbour; 3]>,
3373 left: Vec<[Neighbour; 3]>,
3374 above_mode: Vec<usize>,
3375 left_mode: Vec<usize>,
3376 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
3377 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
3378 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
3379 /// luma one -- the same block can (and often does) code a different
3380 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
3381 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
3382 /// within-block neighbour finer than this grid) is luma-only -- a known,
3383 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
3384 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
3385 above_uv_mode: Vec<usize>,
3386 left_uv_mode: Vec<usize>,
3387 above_side: Vec<usize>,
3388 left_side: Vec<usize>,
3389 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
3390 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
3391 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
3392 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
3393 /// array cannot tell the second leaf's partition symbol that the first
3394 /// one was coded at 8x8.
3395 above_side_mi: Vec<usize>,
3396 left_side_mi: Vec<usize>,
3397 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
3398 /// / row, with the mi position it was written at
3399 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
3400 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
3401 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
3402 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
3403 /// leaf whose neighbour is another split group needs that group's leaf 3
3404 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
3405 /// and read only by [`decode_leaf_split4`]; the position guard makes it
3406 /// fall back to the coarse slot whenever the real neighbour was a block
3407 /// of 8x8 or larger (whose one mode is correct for every row it spans).
3408 sub8_mode_col: Vec<(usize, usize)>,
3409 sub8_mode_row: Vec<(usize, usize)>,
3410 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
3411 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
3412 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
3413 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
3414 /// the leaf above writes the same row slot the block to the left owns.
3415 uv_mode_col: Vec<(usize, usize)>,
3416 uv_mode_row: Vec<(usize, usize)>,
3417 /// Whether the block above/left of this column/row was coded `skip` --
3418 /// an inter frame's own `skip` context (spec `SkipContext`), which the
3419 /// key-frame writer never tracks (its skip context is always zero); a
3420 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
3421 /// `left_skip`.
3422 above_skip: Vec<bool>,
3423 left_skip: Vec<bool>,
3424 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
3425 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
3426 /// pixels last written over each unit by `set_txfm_ctxs`/
3427 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
3428 /// symbol reads its context from (lane-txselect, spec 5.11.17).
3429 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
3430 /// array is exactly libaom's per-superblock-row reset, since each mi row
3431 /// is only ever visited inside one superblock row.
3432 above_txfm: Vec<u8>,
3433 left_txfm: Vec<u8>,
3434 /// Whether the block above/left of this column/row coded `skip_mode`
3435 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
3436 /// lane-av1comp round 14.
3437 above_skip_mode: Vec<bool>,
3438 left_skip_mode: Vec<bool>,
3439 /// Whether the block above/left was coded inter -- the `is_inter`
3440 /// context (spec `av1_get_intra_inter_context`), a duplicate of
3441 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
3442 above_inter: Vec<bool>,
3443 left_inter: Vec<bool>,
3444 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
3445 /// alphabet) the block above/left of this column/row coded, or `-1` for
3446 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
3447 /// functions (`mvstack::ref_ctx` family) need the real reference, not
3448 /// just "was it inter" (lane-av1refs: every inter block used to be
3449 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
3450 /// enough).
3451 above_ref: Vec<i8>,
3452 left_ref: Vec<i8>,
3453 /// The block above/left's *second* reference frame when it was coded
3454 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
3455 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
3456 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
3457 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
3458 /// (no decode path here ever produces a compound block yet).
3459 above_ref1: Vec<Option<i8>>,
3460 left_ref1: Vec<Option<i8>>,
3461 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
3462 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
3463 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
3464 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
3465 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
3466 above_comp_group_idx: Vec<u8>,
3467 left_comp_group_idx: Vec<u8>,
3468 above_compound_idx: Vec<u8>,
3469 left_compound_idx: Vec<u8>,
3470 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
3471 /// `3` = "no info": an intra neighbour or the frame's own border) of the
3472 /// block above/left of this column/row -- spec
3473 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
3474 above_filter: Vec<[u8; 2]>,
3475 left_filter: Vec<[u8; 2]>,
3476 mi_cols: usize,
3477 mi_rows: usize,
3478 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
3479 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
3480 /// 7.15) never filters an 8x8 luma block whose covering coded block read
3481 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
3482 /// grain [`Self::record_mi`] already writes at), read back at 8x8
3483 /// granularity by [`apply_cdef`] since `skip` is constant across every
3484 /// mi cell one coded block covers.
3485 skip_grid: Vec<bool>,
3486 skip_grid_cols_mi: usize,
3487 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
3488 /// never splits a coded block's transform below its own size (round 2:
3489 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
3490 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
3491 /// edge-length lookup (`apply_deblock`).
3492 tx_grid: Vec<u8>,
3493 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
3494 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
3495 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
3496 tx_h_grid: Vec<u8>,
3497 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
3498 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
3499 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
3500 /// does NOT follow luma's `tx_depth` split, so deriving it as
3501 /// `tx_grid / 2` invented chroma transform edges the deblocker then
3502 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
3503 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
3504 /// every caller routes through.
3505 uv_tx_grid: Vec<u8>,
3506 uv_tx_h_grid: Vec<u8>,
3507 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
3508 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
3509 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
3510 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
3511 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
3512 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
3513 /// reference onto `LAST_FRAME`'s own delta).
3514 ref_grid: Vec<i8>,
3515 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
3516 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
3517 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
3518 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
3519 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
3520 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
3521 /// to know which mode produced the value.
3522 delta_lf_grid: Vec<[i8; 4]>,
3523 /// The block above/left's own palette-Y size (0 = not a palette block)
3524 /// and its base colours -- `av1_get_palette_mode_ctx`/
3525 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
3526 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
3527 above_palette_size: Vec<usize>,
3528 left_palette_size: Vec<usize>,
3529 above_palette_colors: Vec<[u16; 8]>,
3530 left_palette_colors: Vec<[u16; 8]>,
3531 /// As the four fields above, for the neighbour's own chroma (U-channel
3532 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
3533 /// palette size/colours (lane-palette2 r1).
3534 above_palette_uv_size: Vec<usize>,
3535 left_palette_uv_size: Vec<usize>,
3536 above_palette_uv_colors: Vec<[u16; 8]>,
3537 left_palette_uv_colors: Vec<[u16; 8]>,
3538 /// This tile's own top-left corner, in 4x4 mode-info units (spec
3539 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
3540 /// neighbour" check compares against this instead of literal `0`, since a
3541 /// block at the tile's own top/left edge has no usable neighbour even
3542 /// though a decoded block sits there in the picture (spec `decode_tile`'s
3543 /// per-tile `clear_above_context`/`left_available`/`up_available`).
3544 /// `0` for a single-tile frame, matching every existing caller exactly.
3545 tile_row0_mi: usize,
3546 tile_col0_mi: usize,
3547}
3548
3549impl Neighbours {
3550 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
3551 /// true (unpadded) size in 4x4 mode-info units.
3552 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
3553 Self {
3554 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
3555 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
3556 above_mode: vec![DC_PRED; cols],
3557 left_mode: vec![DC_PRED; rows],
3558 above_uv_mode: vec![DC_PRED; cols],
3559 left_uv_mode: vec![DC_PRED; rows],
3560 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
3561 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
3562 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
3563 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
3564 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3565 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3566 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3567 uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3568 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
3569 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
3570 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
3571 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
3572 // 16x16 block beside it, which a SUB-grid slot cannot name
3573 // (class context-read-from-one-cell).
3574 above_skip: vec![false; cols * (SUB / MI)],
3575 left_skip: vec![false; rows * (SUB / MI)],
3576 above_skip_mode: vec![false; cols * (SUB / MI)],
3577 left_skip_mode: vec![false; rows * (SUB / MI)],
3578 above_inter: vec![false; cols * (SUB / MI)],
3579 left_inter: vec![false; rows * (SUB / MI)],
3580 above_ref: vec![-1; cols * (SUB / MI)],
3581 left_ref: vec![-1; rows * (SUB / MI)],
3582 above_ref1: vec![None; cols * (SUB / MI)],
3583 left_ref1: vec![None; rows * (SUB / MI)],
3584 above_comp_group_idx: vec![0; cols * (SUB / MI)],
3585 left_comp_group_idx: vec![0; rows * (SUB / MI)],
3586 above_compound_idx: vec![0; cols * (SUB / MI)],
3587 left_compound_idx: vec![0; rows * (SUB / MI)],
3588 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
3589 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
3590 mi_cols,
3591 mi_rows,
3592 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
3593 skip_grid_cols_mi: cols * (SUB / MI),
3594 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3595 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3596 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3597 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3598 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
3599 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
3600 above_palette_size: vec![0; cols],
3601 left_palette_size: vec![0; rows],
3602 above_palette_colors: vec![[0u16; 8]; cols],
3603 left_palette_colors: vec![[0u16; 8]; rows],
3604 above_palette_uv_size: vec![0; cols],
3605 left_palette_uv_size: vec![0; rows],
3606 above_palette_uv_colors: vec![[0u16; 8]; cols],
3607 left_palette_uv_colors: vec![[0u16; 8]; rows],
3608 tile_row0_mi: 0,
3609 tile_col0_mi: 0,
3610 }
3611 }
3612
3613 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
3614 /// tile's own column span (`col1_mi` exclusive), plus recording
3615 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
3616 /// availability check below. Left context resets every superblock row
3617 /// regardless of tile ([`Self::start_row`], already called once per SB
3618 /// row by every caller) so it needs no tile-specific reset here.
3619 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
3620 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
3621 // are tile-relative, same as every other neighbour lookup here.
3622 SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
3623 self.tile_row0_mi = row0_mi;
3624 self.tile_col0_mi = col0_mi;
3625 let end = col1_mi.min(self.above.len());
3626 for i in col0_mi.min(end)..end {
3627 self.above[i] = Default::default();
3628 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE;
3629 }
3630 let (sc0, sc1) = (
3631 col0_mi / (SUB / MI),
3632 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
3633 );
3634 for i in sc0.min(sc1)..sc1 {
3635 self.above_mode[i] = DC_PRED;
3636 self.above_side[i] = NO_NEIGHBOUR_SIDE;
3637 }
3638 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
3639 // the tile's own mi column span directly.
3640 let mend = col1_mi.min(self.above_skip.len());
3641 for i in col0_mi.min(mend)..mend {
3642 self.above_skip[i] = false;
3643 self.above_skip_mode[i] = false;
3644 self.above_inter[i] = false;
3645 self.above_ref[i] = -1;
3646 self.above_ref1[i] = None;
3647 self.above_comp_group_idx[i] = 0;
3648 self.above_compound_idx[i] = 0;
3649 self.above_filter[i] = [3u8; 2];
3650 }
3651 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
3652 // stale `(row, mode)` from the tile to the LEFT names an mi row this
3653 // tile's first block would read as its own above neighbour.
3654 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
3655 for i in col0_mi.min(mcol_end)..mcol_end {
3656 self.sub8_mode_col[i] = (usize::MAX, 0);
3657 self.uv_mode_col[i] = (usize::MAX, 0);
3658 }
3659 }
3660
3661 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
3662 /// for a non-palette block, clearing any stale neighbour state) into every
3663 /// [`SUB`]-grid cell it covers on both the above and left edges --
3664 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
3665 /// call sites are all square blocks).
3666 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3667 self.record_palette_y_rect(at, side, side, size, colors);
3668 }
3669
3670 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
3671 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
3672 /// [`Self::record`]): a true rect strip's above/left neighbour spans
3673 /// differ.
3674 fn record_palette_y_rect(
3675 &mut self,
3676 at: (usize, usize),
3677 w: usize,
3678 h: usize,
3679 size: usize,
3680 colors: [u16; 8],
3681 ) {
3682 let (r, c) = at;
3683 // `.max(1)`: a below-16px span covers no whole SUB cell, so the plain
3684 // `w / SUB` loop was a NO-OP for every 16x8/8x16/8x8/4x4 leaf and the
3685 // next block read a long-dead palette out of the above/left arrays
3686 // (class [[cdf-row-held-constant]], lane-palette2 r8). libaom keeps
3687 // `palette_size` per 4px mi cell; corner-cut: our grid is 16px, so a
3688 // sub-16 leaf stamps its whole containing cell -- safe today because
3689 // every sub-16 leaf path refuses palette outright (so it can only
3690 // ever stamp `size == 0`, and its cell holds no palette sibling).
3691 // Upgrade path: widen the palette arrays to mi granularity.
3692 for cell in 0..(w / SUB).max(1) {
3693 self.above_palette_size[c + cell] = size;
3694 self.above_palette_colors[c + cell] = colors;
3695 }
3696 for cell in 0..(h / SUB).max(1) {
3697 self.left_palette_size[r + cell] = size;
3698 self.left_palette_colors[r + cell] = colors;
3699 }
3700 }
3701
3702 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
3703 /// neighbours that are themselves a palette-Y block, plus
3704 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
3705 /// cache (pred_common.c:73).
3706 ///
3707 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
3708 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
3709 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
3710 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
3711 /// the ctx too made every superblock in the frame's second SB row read
3712 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
3713 /// palette block decoded as "no palette" and the tile desynced from
3714 /// there (class [[cdf-row-held-constant]]).
3715 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
3716 let (r, c) = at;
3717 let above_ok = r % 4 != 0;
3718 // `xd->above_mbmi` exists for every row but the tile's own first.
3719 let above_is_palette =
3720 r * (SUB / MI) > self.tile_row0_mi && self.above_palette_size[c] > 0;
3721 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
3722 (self.above_palette_size[c], self.above_palette_colors[c])
3723 } else {
3724 (0, [0u16; 8])
3725 };
3726 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
3727 // is NULL whenever the block sits at its TILE's own left column
3728 // (`left_available`), not the frame's -- without this guard a second
3729 // tile column reads the previous tile's palette colours into its cache
3730 // and its `palette_y_mode` ctx.
3731 let left_ok = c > self.tile_col0_mi / (SUB / MI);
3732 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
3733 (self.left_palette_size[r], self.left_palette_colors[r])
3734 } else {
3735 (0, [0u16; 8])
3736 };
3737 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
3738 let mut cache = Vec::with_capacity(16);
3739 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3740 if cache.last() != Some(&v) {
3741 cache.push(v);
3742 }
3743 };
3744 let (mut ai, mut li) = (0usize, 0usize);
3745 while ai < above_n && li < left_n {
3746 let (va, vl) = (above_colors[ai], left_colors[li]);
3747 if vl < va {
3748 push_dedup(&mut cache, vl);
3749 li += 1;
3750 } else {
3751 push_dedup(&mut cache, va);
3752 ai += 1;
3753 if vl == va {
3754 li += 1;
3755 }
3756 }
3757 }
3758 while ai < above_n {
3759 push_dedup(&mut cache, above_colors[ai]);
3760 ai += 1;
3761 }
3762 while li < left_n {
3763 push_dedup(&mut cache, left_colors[li]);
3764 li += 1;
3765 }
3766 (ctx, cache)
3767 }
3768
3769 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
3770 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
3771 /// same way (lane-palette2 r1).
3772 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3773 self.record_palette_uv_rect(at, side, side, size, colors);
3774 }
3775
3776 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
3777 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
3778 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
3779 /// luma resolution regardless of which plane the recorded state is for).
3780 fn record_palette_uv_rect(
3781 &mut self,
3782 at: (usize, usize),
3783 w: usize,
3784 h: usize,
3785 size: usize,
3786 colors: [u16; 8],
3787 ) {
3788 let (r, c) = at;
3789 // See [`Self::record_palette_y_rect`] for the `.max(1)`.
3790 for cell in 0..(w / SUB).max(1) {
3791 self.above_palette_uv_size[c + cell] = size;
3792 self.above_palette_uv_colors[c + cell] = colors;
3793 }
3794 for cell in 0..(h / SUB).max(1) {
3795 self.left_palette_uv_size[r + cell] = size;
3796 self.left_palette_uv_colors[r + cell] = colors;
3797 }
3798 }
3799
3800 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
3801 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
3802 /// no neighbour lookup at all (it is this block's own just-decided Y
3803 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
3804 /// so only the cache is wanted here.
3805 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
3806 let (r, c) = at;
3807 let above_ok = r % 4 != 0;
3808 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
3809 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
3810 } else {
3811 (0, [0u16; 8])
3812 };
3813 // Same tile-relative left availability as the luma cache above.
3814 let left_ok = c > self.tile_col0_mi / (SUB / MI);
3815 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
3816 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
3817 } else {
3818 (0, [0u16; 8])
3819 };
3820 let mut cache = Vec::with_capacity(16);
3821 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3822 if cache.last() != Some(&v) {
3823 cache.push(v);
3824 }
3825 };
3826 let (mut ai, mut li) = (0usize, 0usize);
3827 while ai < above_n && li < left_n {
3828 let (va, vl) = (above_colors[ai], left_colors[li]);
3829 if vl < va {
3830 push_dedup(&mut cache, vl);
3831 li += 1;
3832 } else {
3833 push_dedup(&mut cache, va);
3834 ai += 1;
3835 if vl == va {
3836 li += 1;
3837 }
3838 }
3839 }
3840 while ai < above_n {
3841 push_dedup(&mut cache, above_colors[ai]);
3842 ai += 1;
3843 }
3844 while li < left_n {
3845 push_dedup(&mut cache, left_colors[li]);
3846 li += 1;
3847 }
3848 cache
3849 }
3850
3851 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
3852 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
3853 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
3854 /// units as [`Self::fill_skip_grid`].
3855 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
3856 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
3857 }
3858
3859 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
3860 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
3861 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
3862 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
3863 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
3864 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
3865 fn fill_lf_grid_rect(
3866 &mut self,
3867 at_mi: (usize, usize),
3868 w_mi: usize,
3869 h_mi: usize,
3870 tx_px: u8,
3871 tx_h_px: u8,
3872 ref_frame: i8,
3873 ) {
3874 let (mi_r, mi_c) = at_mi;
3875 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
3876 // half its luma one (min 4 px, the smallest transform), capped at
3877 // TX_32X32 -- independent of this block's luma `tx_depth`.
3878 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
3879 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
3880 let cur = CURRENT_DELTA_LF.with(|c| c.get());
3881 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
3882 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
3883 } else {
3884 [cur[0].clamp(-63, 63) as i8; 4]
3885 };
3886 for rr in 0..h_mi {
3887 for cc in 0..w_mi {
3888 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
3889 if let Some(cell) = self.tx_grid.get_mut(idx) {
3890 *cell = tx_px;
3891 }
3892 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
3893 *cell = tx_h_px;
3894 }
3895 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
3896 *cell = uv_tx_w;
3897 }
3898 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
3899 *cell = uv_tx_h;
3900 }
3901 if let Some(cell) = self.ref_grid.get_mut(idx) {
3902 *cell = ref_frame;
3903 }
3904 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
3905 *cell = snapshot;
3906 }
3907 }
3908 }
3909 }
3910
3911 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
3912 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
3913 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
3914 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
3915 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
3916 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
3917 }
3918
3919 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
3920 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
3921 let (mi_r, mi_c) = at_mi;
3922 for rr in 0..h_mi {
3923 for cc in 0..w_mi {
3924 if let Some(cell) = self
3925 .skip_grid
3926 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
3927 {
3928 *cell = skip;
3929 }
3930 }
3931 }
3932 }
3933
3934 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
3935 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
3936 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
3937 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
3938 /// straddle the region with a mix of skip/non-skip blocks).
3939 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
3940 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
3941 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
3942 /// filtered edge's two sides are each exactly one coded block wide.
3943 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
3944 self.skip_grid
3945 .get(mi_r * self.skip_grid_cols_mi + mi_c)
3946 .copied()
3947 .unwrap_or(false)
3948 }
3949
3950 /// The `skip_txfm` context of a block whose top-left mi cell is
3951 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
3952 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
3953 /// with an absent neighbour contributing 0. The mi grid is per tile, so
3954 /// row/column 0 is a tile edge and has no neighbour on that axis.
3955 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
3956 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
3957 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
3958 }
3959
3960 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
3961 (0..2).all(|rr| {
3962 (0..2).all(|cc| {
3963 self.skip_grid
3964 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
3965 .copied()
3966 .unwrap_or(false)
3967 })
3968 })
3969 }
3970
3971 fn start_row(&mut self) {
3972 self.left.iter_mut().for_each(|l| *l = Default::default());
3973 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
3974 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
3975 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3976 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3977 self.left_skip.iter_mut().for_each(|s| *s = false);
3978 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
3979 self.left_inter.iter_mut().for_each(|i| *i = false);
3980 self.left_ref.iter_mut().for_each(|r| *r = -1);
3981 self.left_ref1.iter_mut().for_each(|r| *r = None);
3982 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
3983 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
3984 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
3985 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
3986 // context (a tile/SB-row boundary has no left neighbour).
3987 self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
3988 self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
3989 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
3990 // are per-mi maps like every other one here, so they reset with the
3991 // row too -- the left guard above is what actually stops a cross-tile
3992 // read, this keeps a stale colour out of the arrays at all.
3993 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
3994 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
3995 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
3996 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
3997 }
3998
3999 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
4000 /// block that reads it as a neighbour -- [`crate::tile`]'s
4001 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
4002 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
4003 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
4004 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
4005 /// the real value, not just `is_inter`).
4006 fn record_inter(
4007 &mut self,
4008 at: (usize, usize),
4009 side: usize,
4010 skip: bool,
4011 is_inter: bool,
4012 ref_frame: i8,
4013 filter: [u8; 2],
4014 skip_mode: bool,
4015 ) {
4016 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
4017 }
4018
4019 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
4020 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
4021 /// r1: a true rectangular strip's above-context span (its own width) and
4022 /// left-context span (its own height) differ, unlike every caller before
4023 /// this round (class neighbour-votes-all-its-fields).
4024 #[allow(clippy::too_many_arguments)]
4025 fn record_inter_rect(
4026 &mut self,
4027 at: (usize, usize),
4028 w_sub: usize,
4029 h_sub: usize,
4030 skip: bool,
4031 is_inter: bool,
4032 ref_frame: i8,
4033 filter: [u8; 2],
4034 skip_mode: bool,
4035 ) {
4036 let (r, c) = at;
4037 self.record_inter_rect_mi(
4038 (r * (SUB / MI), c * (SUB / MI)),
4039 w_sub / MI,
4040 h_sub / MI,
4041 skip,
4042 is_inter,
4043 ref_frame,
4044 filter,
4045 skip_mode,
4046 );
4047 }
4048
4049 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
4050 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
4051 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
4052 /// routes through the wrapper above.
4053 #[allow(clippy::too_many_arguments)]
4054 fn record_inter_rect_mi(
4055 &mut self,
4056 at_mi: (usize, usize),
4057 w_mi: usize,
4058 h_mi: usize,
4059 skip: bool,
4060 is_inter: bool,
4061 ref_frame: i8,
4062 filter: [u8; 2],
4063 skip_mode: bool,
4064 ) {
4065 let (r, c) = at_mi;
4066 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
4067 for cell in 0..w_mi {
4068 self.above_skip[c + cell] = skip;
4069 self.above_skip_mode[c + cell] = skip_mode;
4070 self.above_inter[c + cell] = is_inter;
4071 self.above_ref[c + cell] = ref_frame;
4072 // lane-av1comp: no caller of `record_inter` ever decodes a
4073 // compound block yet (see [`Self::above_ref1`]'s doc); the
4074 // parameter this becomes lands with `read_ref_frames`.
4075 self.above_ref1[c + cell] = None;
4076 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
4077 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
4078 // as `3`/`1` even though this block has no second reference.
4079 // `record_compound_ctx` overwrites this with the real bit for an
4080 // actual compound block's cells, called right after this one.
4081 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
4082 self.above_compound_idx[c + cell] = u8::from(altref);
4083 self.above_filter[c + cell] = filter;
4084 }
4085 for cell in 0..h_mi {
4086 self.left_skip[r + cell] = skip;
4087 self.left_skip_mode[r + cell] = skip_mode;
4088 self.left_inter[r + cell] = is_inter;
4089 self.left_ref[r + cell] = ref_frame;
4090 self.left_ref1[r + cell] = None;
4091 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
4092 self.left_compound_idx[r + cell] = u8::from(altref);
4093 self.left_filter[r + cell] = filter;
4094 }
4095 }
4096
4097 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
4098 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
4099 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
4100 /// `get_comp_index_context`) -- called right after `record_inter` for
4101 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
4102 /// stamps `above_ref1`/`left_ref1` with the block's real second
4103 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
4104 /// this is the one caller that actually knows it) -- so the next block's
4105 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
4106 /// neighbour instead of `record_inter`'s single-ref default.
4107 fn record_compound_ctx(
4108 &mut self,
4109 at: (usize, usize),
4110 side: usize,
4111 ref1: i8,
4112 comp_group_idx: u8,
4113 compound_idx: u8,
4114 ) {
4115 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
4116 }
4117
4118 /// [`Self::record_compound_ctx`] with independent above/left extents,
4119 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
4120 #[allow(clippy::too_many_arguments)]
4121 fn record_compound_ctx_rect(
4122 &mut self,
4123 at: (usize, usize),
4124 w_sub: usize,
4125 h_sub: usize,
4126 ref1: i8,
4127 comp_group_idx: u8,
4128 compound_idx: u8,
4129 ) {
4130 let (r, c) = at;
4131 self.record_compound_ctx_rect_mi(
4132 (r * (SUB / MI), c * (SUB / MI)),
4133 w_sub / MI,
4134 h_sub / MI,
4135 ref1,
4136 comp_group_idx,
4137 compound_idx,
4138 );
4139 }
4140
4141 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
4142 /// [`Self::record_inter_rect_mi`]).
4143 fn record_compound_ctx_rect_mi(
4144 &mut self,
4145 at_mi: (usize, usize),
4146 w_mi: usize,
4147 h_mi: usize,
4148 ref1: i8,
4149 comp_group_idx: u8,
4150 compound_idx: u8,
4151 ) {
4152 let (r, c) = at_mi;
4153 for cell in 0..w_mi {
4154 self.above_ref1[c + cell] = Some(ref1);
4155 self.above_comp_group_idx[c + cell] = comp_group_idx;
4156 self.above_compound_idx[c + cell] = compound_idx;
4157 }
4158 for cell in 0..h_mi {
4159 self.left_ref1[r + cell] = Some(ref1);
4160 self.left_comp_group_idx[r + cell] = comp_group_idx;
4161 self.left_compound_idx[r + cell] = compound_idx;
4162 }
4163 }
4164
4165 /// The context of a block's partition symbol: delegates to the mi-precise
4166 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
4167 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
4168 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
4169 /// only touches the finer mi arrays -- leaves them stale for the *next*
4170 /// sibling's own partition symbol.
4171 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
4172 let (r, c) = at;
4173 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
4174 }
4175
4176 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
4177 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
4178 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
4179 /// than the enclosing 16x16 slot's stale, shared state.
4180 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
4181 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
4182 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
4183 }
4184
4185 /// The gathered coded/DC-sign state of the blocks above and to the left
4186 /// of a block `side` samples across, per plane.
4187 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
4188 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
4189 }
4190
4191 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
4192 /// units, for the same reason [`Self::record_mi`] does.
4193 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
4194 let side_mi = side / MI;
4195 std::array::from_fn(|plane| {
4196 let mut above_coded = false;
4197 let mut left_coded = false;
4198 let mut vote = 0;
4199 for cell in 0..side_mi {
4200 let above = &self.above[mi_c + cell][plane];
4201 let left = &self.left[mi_r + cell][plane];
4202 above_coded |= above.level != 0;
4203 left_coded |= left.level != 0;
4204 vote += dc_vote(above.dc) + dc_vote(left.dc);
4205 }
4206 (above_coded, left_coded, vote)
4207 })
4208 }
4209
4210 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
4211 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
4212 /// extent pattern for a true rectangular strip's own coefficient context.
4213 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
4214 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
4215 }
4216
4217 /// [`Self::around_rect`] taking the block's position directly in 4x4
4218 /// mode-info units, mirroring [`Self::around_mi`].
4219 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
4220 let (w_mi, h_mi) = (w / MI, h / MI);
4221 std::array::from_fn(|plane| {
4222 let mut above_coded = false;
4223 let mut left_coded = false;
4224 let mut vote = 0;
4225 for cell in 0..w_mi {
4226 let above = &self.above[mi_c + cell][plane];
4227 above_coded |= above.level != 0;
4228 vote += dc_vote(above.dc);
4229 }
4230 for cell in 0..h_mi {
4231 let left = &self.left[mi_r + cell][plane];
4232 left_coded |= left.level != 0;
4233 vote += dc_vote(left.dc);
4234 }
4235 (above_coded, left_coded, vote)
4236 })
4237 }
4238
4239 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
4240 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
4241 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
4242 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
4243 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
4244 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
4245 /// is always 0, spec's `plane_bsize == tx_size` branch).
4246 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
4247 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
4248 }
4249
4250 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
4251 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
4252 /// context over `tx_size_wide` and the left one over `tx_size_high`.
4253 fn luma_skip_ctx_rect(
4254 &self,
4255 (mi_r, mi_c): (usize, usize),
4256 w_mi: usize,
4257 h_mi: usize,
4258 ) -> usize {
4259 let side_mi = w_mi;
4260 let mut top = 0u8;
4261 let mut left = 0u8;
4262 for cell in 0..w_mi {
4263 top |= self.above[mi_c + cell][0].level;
4264 }
4265 for cell in 0..h_mi {
4266 left |= self.left[mi_r + cell][0].level;
4267 }
4268 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
4269 if std::env::var_os("EC_AV1_TRACE").is_some() {
4270 eprintln!(
4271 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
4272 );
4273 }
4274 ctx
4275 }
4276
4277 /// Writes one coded block into every cell it covers, on both grids: the
4278 /// mode/side arrays up to `side`'s own width, and the coefficient-context
4279 /// arrays up to the true frame edge — the units past it are left at their
4280 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
4281 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
4282 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
4283 /// not from this block's own side).
4284 fn record(
4285 &mut self,
4286 at: (usize, usize),
4287 side: usize,
4288 mode: usize,
4289 uv_mode: usize,
4290 grids: &[Vec<i32>; 3],
4291 ) {
4292 self.record_rect(at, side, side, mode, uv_mode, grids);
4293 }
4294
4295 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
4296 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
4297 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
4298 /// spec's per-edge partition-context rule, so a true rectangular block
4299 /// naturally wants two different values here rather than one.
4300 /// Writes this block's luma `mode` into the mi-granular
4301 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
4302 /// position a *later* neighbour would read it from: the block's LAST mi
4303 /// row for every column it spans (what the block below reads via
4304 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
4305 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
4306 /// read these back, and only when the recorded position is exactly their
4307 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
4308 fn record_mode_mi(
4309 &mut self,
4310 mi_r: usize,
4311 mi_c: usize,
4312 mi_w: usize,
4313 mi_h: usize,
4314 mode: usize,
4315 ) {
4316 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
4317 for cell in 0..mi_w {
4318 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
4319 *slot = (last_r, mode);
4320 }
4321 }
4322 for cell in 0..mi_h {
4323 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
4324 *slot = (last_c, mode);
4325 }
4326 }
4327 }
4328
4329 /// The mi-exact above/left neighbour luma mode for a block whose top-left
4330 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
4331 /// mi position (then the coarse [`SUB`]-grid slot is right by
4332 /// construction). See [`Self::record_mode_mi`].
4333 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
4334 match self.sub8_mode_col.get(mi_c) {
4335 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m),
4336 _ => None,
4337 }
4338 }
4339
4340 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
4341 match self.sub8_mode_row.get(mi_r) {
4342 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m),
4343 _ => None,
4344 }
4345 }
4346
4347 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
4348 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
4349 fn record_uv_mode_mi(
4350 &mut self,
4351 mi_r: usize,
4352 mi_c: usize,
4353 mi_w: usize,
4354 mi_h: usize,
4355 uv_mode: usize,
4356 ) {
4357 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
4358 for cell in 0..mi_w {
4359 if let Some(slot) = self.uv_mode_col.get_mut(mi_c + cell) {
4360 *slot = (last_r, uv_mode);
4361 }
4362 }
4363 for cell in 0..mi_h {
4364 if let Some(slot) = self.uv_mode_row.get_mut(mi_r + cell) {
4365 *slot = (last_c, uv_mode);
4366 }
4367 }
4368 }
4369
4370 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
4371 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
4372 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
4373 /// block has recorded the exact neighbouring mi.
4374 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
4375 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
4376 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
4377 // array that `start_tile` does not clear, so a block on a tile's first
4378 // mi row used to read the uv_mode of the block above it in the tile
4379 // ABOVE and filter its chroma edge at that neighbour's strength
4380 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
4381 // at chroma (120, 32), the top-right tile's first block).
4382 let have_above = mi_r > self.tile_row0_mi;
4383 let have_left = mi_c > self.tile_col0_mi;
4384 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
4385 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
4386 {
4387 UV_TILE_EDGE_SUPPRESSED_HITS.with(|h| h.set(h.get() + 1));
4388 }
4389 let above = match self.uv_mode_col.get(mi_c) {
4390 Some(&(row, m)) if have_above && row == mi_r - 1 => m,
4391 _ if have_above => self.above_uv_mode[c],
4392 _ => DC_PRED,
4393 };
4394 let left = match self.uv_mode_row.get(mi_r) {
4395 Some(&(col, m)) if have_left && col == mi_c - 1 => m,
4396 _ if have_left => self.left_uv_mode[r],
4397 _ => DC_PRED,
4398 };
4399 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
4400 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
4401 // have been filtered at the wrong strength by the coarse map alone.
4402 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
4403 UV_MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
4404 }
4405 is_smooth_mode(above) || is_smooth_mode(left)
4406 }
4407
4408 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
4409 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
4410 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
4411 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
4412 /// holding an OLDER, larger block's mode -- it only ever recorded into the
4413 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
4414 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
4415 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
4416 /// a different CDF for the same mode value).
4417 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
4418 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
4419 /// only when `up_available` and `left_mbmi` only when `left_available`;
4420 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
4421 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
4422 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
4423 /// strip's mode as its "left neighbour" (measured on the band fixture at
4424 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
4425 fn modes_above_left_mi(
4426 &self,
4427 mi_r: usize,
4428 mi_c: usize,
4429 fallback: (usize, usize),
4430 ) -> (usize, usize) {
4431 let above = if mi_r > self.tile_row0_mi {
4432 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
4433 } else {
4434 DC_PRED
4435 };
4436 let left = if mi_c > self.tile_col0_mi {
4437 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
4438 } else {
4439 DC_PRED
4440 };
4441 (above, left)
4442 }
4443
4444 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
4445 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
4446 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
4447 /// per superblock row and never per tile, so the first block column of
4448 /// tile 2..N read the previous tile's mode as its left neighbour, and the
4449 /// above band survives across a tile ROW boundary the same way lane-mtfix's
4450 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
4451 /// `up_available`/`left_available` and uses DC_PRED otherwise
4452 /// ([`Self::modes_above_left_mi`]).
4453 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
4454 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4455 let (above, left) =
4456 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
4457 if above != self.above_mode[c] || left != self.left_mode[r] {
4458 MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
4459 }
4460 // A neighbour the coarse band offered where the tile edge makes it
4461 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
4462 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
4463 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
4464 {
4465 MODE_TILE_EDGE_COARSE_LEAKS.with(|h| h.set(h.get() + 1));
4466 }
4467 (above, left)
4468 }
4469
4470 fn record_rect(
4471 &mut self,
4472 at: (usize, usize),
4473 w: usize,
4474 h: usize,
4475 mode: usize,
4476 uv_mode: usize,
4477 grids: &[Vec<i32>; 3],
4478 ) {
4479 let (r, c) = at;
4480 for cell in 0..w / SUB {
4481 self.above_mode[c + cell] = mode;
4482 self.above_uv_mode[c + cell] = uv_mode;
4483 self.above_side[c + cell] = w;
4484 }
4485 for cell in 0..h / SUB {
4486 self.left_mode[r + cell] = mode;
4487 self.left_uv_mode[r + cell] = uv_mode;
4488 self.left_side[r + cell] = h;
4489 }
4490 self.record_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, mode);
4491 self.record_uv_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, uv_mode);
4492 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
4493 }
4494
4495 /// The coefficient-context half of [`Self::record`], taking the block's
4496 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
4497 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
4498 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
4499 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
4500 self.record_mi_rect(at_mi, side, side, grids);
4501 }
4502
4503 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
4504 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
4505 fn record_mi_rect(
4506 &mut self,
4507 at_mi: (usize, usize),
4508 w: usize,
4509 h: usize,
4510 grids: &[Vec<i32>; 3],
4511 ) {
4512 let (mi_r, mi_c) = at_mi;
4513 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
4514 let (w_mi, h_mi) = (w / MI, h / MI);
4515 for cell in 0..h_mi {
4516 self.left_side_mi[mi_r + cell] = h;
4517 }
4518 for cell in 0..w_mi {
4519 self.above_side_mi[mi_c + cell] = w;
4520 }
4521 // A chroma 4x4 unit straddling the true luma edge is still whole in
4522 // chroma's own halved grid, so libaom rounds the luma bound up to the
4523 // plane's own 4x4 unit before clamping a subsampled plane
4524 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
4525 let round_up_even = |n: usize| n.div_ceil(2) * 2;
4526 let bound_h = [
4527 self.mi_rows,
4528 round_up_even(self.mi_rows),
4529 round_up_even(self.mi_rows),
4530 ];
4531 let bound_w = [
4532 self.mi_cols,
4533 round_up_even(self.mi_cols),
4534 round_up_even(self.mi_cols),
4535 ];
4536 for cell in 0..h_mi {
4537 self.left[mi_r + cell] = std::array::from_fn(|plane| {
4538 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
4539 states[plane]
4540 } else {
4541 Default::default()
4542 }
4543 });
4544 }
4545 for cell in 0..w_mi {
4546 self.above[mi_c + cell] = std::array::from_fn(|plane| {
4547 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
4548 states[plane]
4549 } else {
4550 Default::default()
4551 }
4552 });
4553 }
4554 }
4555
4556 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
4557 /// inside a coded block whose luma transform is smaller than its own
4558 /// side (`TxMode::Select`): the real per-transform-unit coefficient
4559 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
4560 /// coarse per-block `tx_grid`/`fill_lf_grid` state
4561 /// [`Self::record_split_luma`] still writes once for the whole block.
4562 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
4563 /// the caller's own [`Self::record_split_luma`] call sets those once,
4564 /// at the block's own true side, not this TU's.
4565 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
4566 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
4567 }
4568
4569 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
4570 /// r1): the above context spans the unit's width, the left context its
4571 /// height, which for a square unit is the same loop it always was.
4572 fn record_mi_luma_rect(
4573 &mut self,
4574 (mi_r, mi_c): (usize, usize),
4575 w_px: usize,
4576 h_px: usize,
4577 grid: &[i32],
4578 ) {
4579 let state = neighbour_state(grid);
4580 for cell in 0..h_px / MI {
4581 if mi_r + cell < self.mi_rows {
4582 self.left[mi_r + cell][0] = state;
4583 }
4584 }
4585 for cell in 0..w_px / MI {
4586 if mi_c + cell < self.mi_cols {
4587 self.above[mi_c + cell][0] = state;
4588 }
4589 }
4590 }
4591
4592 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
4593 /// block whose luma was decoded as several transform units through
4594 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
4595 /// whole-block luma write -- everything [`Self::record`] does except
4596 /// plane 0, which is already correct per-TU by the time this runs.
4597 fn record_split_luma(
4598 &mut self,
4599 at: (usize, usize),
4600 side: usize,
4601 mode: usize,
4602 uv_mode: usize,
4603 chroma_grids: [&[i32]; 2],
4604 ) {
4605 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
4606 }
4607
4608 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
4609 /// extents in pixels (lane-rectsplit r1), the same relationship
4610 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
4611 /// luma transform split into several square units needs exactly this
4612 /// bookkeeping, at its own true rectangular extents.
4613 fn record_split_luma_rect(
4614 &mut self,
4615 at: (usize, usize),
4616 w: usize,
4617 h: usize,
4618 mode: usize,
4619 uv_mode: usize,
4620 chroma_grids: [&[i32]; 2],
4621 ) {
4622 let (r, c) = at;
4623 self.record_split_luma_rect_mi(
4624 (r * (SUB / MI), c * (SUB / MI)),
4625 w,
4626 h,
4627 mode,
4628 uv_mode,
4629 chroma_grids,
4630 );
4631 }
4632
4633 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
4634 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
4635 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
4636 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
4637 /// convention [`decode_block_rect4`] already established for 1:4 strips.
4638 fn record_split_luma_rect_mi(
4639 &mut self,
4640 at_mi: (usize, usize),
4641 w: usize,
4642 h: usize,
4643 mode: usize,
4644 uv_mode: usize,
4645 chroma_grids: [&[i32]; 2],
4646 ) {
4647 let (mi_r, mi_c) = at_mi;
4648 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
4649 for cell in 0..w.div_ceil(SUB) {
4650 self.above_mode[c + cell] = mode;
4651 self.above_uv_mode[c + cell] = uv_mode;
4652 self.above_side[c + cell] = w;
4653 }
4654 for cell in 0..h.div_ceil(SUB) {
4655 self.left_mode[r + cell] = mode;
4656 self.left_uv_mode[r + cell] = uv_mode;
4657 self.left_side[r + cell] = h;
4658 }
4659 let (w_mi, h_mi) = (w / MI, h / MI);
4660 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
4661 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
4662 for cell in 0..h_mi {
4663 self.left_side_mi[mi_r + cell] = h;
4664 }
4665 for cell in 0..w_mi {
4666 self.above_side_mi[mi_c + cell] = w;
4667 }
4668 let round_up_even = |n: usize| n.div_ceil(2) * 2;
4669 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
4670 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
4671 let plane = plane_idx + 1;
4672 let state = neighbour_state(grid);
4673 for cell in 0..h_mi {
4674 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
4675 self.left[mi_r + cell][plane] = state;
4676 }
4677 }
4678 for cell in 0..w_mi {
4679 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
4680 self.above[mi_c + cell][plane] = state;
4681 }
4682 }
4683 }
4684 }
4685}
4686
4687/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
4688/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
4689/// exactly — including its skip context, which the real key-frame writer
4690/// always writes at a fixed context of zero (it never tracks a neighbour-based
4691/// one for intra blocks; that is the inter-frame writer's rule instead).
4692/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
4693/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
4694/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
4695/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
4696/// plain DC chroma.
4697/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
4698/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
4699/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
4700/// instead (the defect commit 1a89ed9 fixed at the square sites).
4701fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
4702 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
4703 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
4704}
4705
4706/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
4707/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
4708/// bound (spec `filter_intra_mode_info` never reads a symbol there).
4709fn filter_intra_size_class(side: usize) -> Option<usize> {
4710 match side {
4711 4 => Some(0),
4712 8 => Some(1),
4713 16 => Some(2),
4714 32 => Some(3),
4715 _ => None,
4716 }
4717}
4718
4719/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
4720/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
4721/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
4722/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
4723fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
4724 match (bw, bh) {
4725 (32, 16) => Some(4),
4726 (16, 32) => Some(5),
4727 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
4728 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
4729 // here dropped that symbol on every DC_PRED strip of that size and
4730 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
4731 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
4732 (16, 8) => Some(6),
4733 (8, 16) => Some(7),
4734 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
4735 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
4736 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
4737 (4, 8) => Some(8),
4738 (8, 4) => Some(9),
4739 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
4740 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
4741 // `use_filter_intra` symbol on those strips although aomenc writes
4742 // one for every DC_PRED block of that shape with
4743 // `--enable-filter-intra=1` (its default), silently desyncing the
4744 // tile (class symbol-consumption-gap).
4745 (32, 8) => Some(10),
4746 (8, 32) => Some(11),
4747 _ if bw == bh => filter_intra_size_class(bw),
4748 _ => None,
4749 }
4750}
4751
4752/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
4753/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
4754/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
4755/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
4756/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
4757fn palette_bsize_ctx(side: usize) -> Option<usize> {
4758 palette_bsize_ctx_wh(side, side)
4759}
4760
4761/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
4762/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
4763/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
4764/// for ANY bsize, not just the square ones a hand-picked table happened to
4765/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
4766/// row breaks the moment its indexing field moves off the diagonal, and a
4767/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
4768/// block dimension is a power of two, so `bw*bh` always is too and
4769/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
4770/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
4771fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
4772 if !(8..=64).contains(&bw) || !(8..=64).contains(&bh) {
4773 return None;
4774 }
4775 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
4776}
4777
4778/// A just-decoded palette-Y block's own size, base colours (only the first
4779/// `size` entries are real), and per-pixel colour-index map (`side*side`,
4780/// row-major, each entry `< size`).
4781struct PaletteY {
4782 size: usize,
4783 colors: [u16; 8],
4784 map: Vec<u8>,
4785}
4786
4787/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
4788/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
4789/// shared between U and V, both co-located after 4:2:0 subsampling) plus
4790/// each plane's own base colours.
4791struct PaletteUv {
4792 size: usize,
4793 u_colors: [u16; 8],
4794 v_colors: [u16; 8],
4795 map: Vec<u8>,
4796}
4797
4798/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
4799/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
4800/// `get_unsigned_bits`, which is the same formula): smallest `n` with
4801/// `2^n >= x`, `0` for `x <= 1`.
4802fn ceil_log2(x: u32) -> u32 {
4803 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
4804}
4805
4806/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
4807/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
4808fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
4809 let l = ceil_log2(n as u32);
4810 let m = (1usize << l) - n;
4811 let v = dec.literal(l - 1) as usize;
4812 if v < m {
4813 v
4814 } else {
4815 (v << 1) - m + dec.literal(1) as usize
4816 }
4817}
4818
4819/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
4820/// colours (already-known, from the above/left neighbours) with the
4821/// ascending `transmitted` ones (delta-coded off the wire) back into one
4822/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
4823/// value picks the cached copy first, matching the C `<=`.
4824fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
4825 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
4826 let (mut ci, mut ti) = (0, 0);
4827 while ci < cached.len() && ti < transmitted.len() {
4828 if cached[ci] <= transmitted[ti] {
4829 out.push(cached[ci]);
4830 ci += 1;
4831 } else {
4832 out.push(transmitted[ti]);
4833 ti += 1;
4834 }
4835 }
4836 out.extend_from_slice(&cached[ci..]);
4837 out.extend_from_slice(&transmitted[ti..]);
4838 out
4839}
4840
4841/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this
4842/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
4843/// (one flag bit each, in cache order), then delta-codes the remainder
4844/// (first value raw, each following delta `>= 1` off a shrinking bit width),
4845/// and merges the two ascending lists back together.
4846fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
4847 let mut cached = Vec::with_capacity(n);
4848 for &c in cache {
4849 if cached.len() >= n {
4850 break;
4851 }
4852 if dec.literal(1) == 1 {
4853 cached.push(c);
4854 }
4855 }
4856 let mut colors = [0u16; 8];
4857 let n_cached = cached.len();
4858 if n_cached < n {
4859 let mut transmitted = Vec::with_capacity(n - n_cached);
4860 let first = dec.literal(8) as u16;
4861 transmitted.push(first);
4862 if n_cached + 1 < n {
4863 let min_bits = 8u32 - 3;
4864 let mut bits = min_bits + dec.literal(2);
4865 let mut range = 255i32 - i32::from(first) - 1;
4866 for _ in (n_cached + 1)..n {
4867 let delta = dec.literal(bits) as i32 + 1;
4868 let prev = *transmitted.last().unwrap();
4869 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
4870 range -= i32::from(val) - i32::from(prev);
4871 bits = bits.min(ceil_log2(range.max(0) as u32));
4872 transmitted.push(val);
4873 }
4874 }
4875 let merged = merge_colors(&transmitted, &cached);
4876 colors[..n].copy_from_slice(&merged);
4877 } else {
4878 colors[..n].copy_from_slice(&cached[..n]);
4879 }
4880 colors
4881}
4882
4883/// `read_palette_colors_uv` (decodemv.c:509), bit_depth fixed at 8: U reads
4884/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
4885/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
4886/// unbiased by `+1` -- both differences from Y's own reader, matching the C
4887/// side by side). V never uses a cache: a leading bit picks either `n` raw
4888/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
4889/// rather than clamp.
4890fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
4891 let mut cached = Vec::with_capacity(n);
4892 for &c in cache {
4893 if cached.len() >= n {
4894 break;
4895 }
4896 if dec.literal(1) == 1 {
4897 cached.push(c);
4898 }
4899 }
4900 let mut u_colors = [0u16; 8];
4901 let n_cached = cached.len();
4902 if n_cached < n {
4903 let mut transmitted = Vec::with_capacity(n - n_cached);
4904 let first = dec.literal(8) as u16;
4905 transmitted.push(first);
4906 if n_cached + 1 < n {
4907 let min_bits = 8u32 - 3;
4908 let mut bits = min_bits + dec.literal(2);
4909 let mut range = 255i32 - i32::from(first);
4910 for _ in (n_cached + 1)..n {
4911 let delta = dec.literal(bits) as i32;
4912 let prev = *transmitted.last().unwrap();
4913 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
4914 range -= i32::from(val) - i32::from(prev);
4915 bits = bits.min(ceil_log2(range.max(0) as u32));
4916 transmitted.push(val);
4917 }
4918 }
4919 let merged = merge_colors(&transmitted, &cached);
4920 u_colors[..n].copy_from_slice(&merged);
4921 } else {
4922 u_colors[..n].copy_from_slice(&cached[..n]);
4923 }
4924 let mut v_colors = [0u16; 8];
4925 if dec.literal(1) == 1 {
4926 let min_bits_v = 8u32 - 4;
4927 let bits = min_bits_v + dec.literal(2);
4928 v_colors[0] = dec.literal(8) as u16;
4929 for i in 1..n {
4930 let mut delta = dec.literal(bits) as i32;
4931 if delta != 0 && dec.literal(1) == 1 {
4932 delta = -delta;
4933 }
4934 let mut val = i32::from(v_colors[i - 1]) + delta;
4935 if val < 0 {
4936 val += 256;
4937 }
4938 if val >= 256 {
4939 val -= 256;
4940 }
4941 v_colors[i] = val as u16;
4942 }
4943 } else {
4944 for i in 0..n {
4945 v_colors[i] = dec.literal(8) as u16;
4946 }
4947 }
4948 (u_colors, v_colors)
4949}
4950
4951/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
4952/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
4953/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
4954const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
4955
4956/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
4957/// map's own per-pixel context and colour-order permutation, from the
4958/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
4959/// selection sort). `map`'s stride is `side` (this decoder never crops a
4960/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
4961/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
4962/// actual colour index to store.
4963fn palette_color_index_context(
4964 map: &[u8],
4965 side: usize,
4966 row: usize,
4967 col: usize,
4968 n: usize,
4969) -> (usize, [u8; 8]) {
4970 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
4971 let up_left = if col >= 1 && row >= 1 {
4972 Some(map[(row - 1) * side + col - 1])
4973 } else {
4974 None
4975 };
4976 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
4977 let mut scores = [0i32; 8];
4978 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
4979 if let Some(v) = neighbour {
4980 scores[v as usize] += weight;
4981 }
4982 }
4983 let mut color_order = [0u8; 8];
4984 for i in 0..8 {
4985 color_order[i] = i as u8;
4986 }
4987 for i in 0..3 {
4988 let mut max = scores[i];
4989 let mut max_idx = i;
4990 for j in (i + 1)..n {
4991 if scores[j] > max {
4992 max = scores[j];
4993 max_idx = j;
4994 }
4995 }
4996 if max_idx != i {
4997 let max_score = scores[max_idx];
4998 let max_color = color_order[max_idx];
4999 for k in (i + 1..=max_idx).rev() {
5000 scores[k] = scores[k - 1];
5001 color_order[k] = color_order[k - 1];
5002 }
5003 scores[i] = max_score;
5004 color_order[i] = max_color;
5005 }
5006 }
5007 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
5008 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
5009 (ctx as usize, color_order)
5010}
5011
5012/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
5013/// map's wavefront decode over a `side x side` grid -- this decoder's
5014/// palette blocks are always square and never straddle the frame's true
5015/// (possibly odd) edge without already allocating the full `side*side`
5016/// region (every other skip/residual path here does the same), so no
5017/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
5018/// libaom's own non-block-aligned split.
5019fn decode_color_index_map(
5020 dec: &mut SymbolDecoder,
5021 cdfs: &mut Cdfs,
5022 n: usize,
5023 side: usize,
5024 uv: bool,
5025) -> Vec<u8> {
5026 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
5027}
5028
5029/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
5030/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
5031/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
5032/// independently rather than one shared `side` -- the square call above is
5033/// just `bw == bh`.
5034fn decode_color_index_map_wh(
5035 dec: &mut SymbolDecoder,
5036 cdfs: &mut Cdfs,
5037 n: usize,
5038 bw: usize,
5039 bh: usize,
5040 uv: bool,
5041) -> Vec<u8> {
5042 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
5043 let mut map = vec![0u8; bw * bh];
5044 if trace {
5045 let (rng, _) = dec.debug_state();
5046 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
5047 }
5048 map[0] = read_uniform(dec, n) as u8;
5049 if trace {
5050 let (rng, _) = dec.debug_state();
5051 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
5052 }
5053 for i in 1..(bw + bh - 1) {
5054 let j_hi = i.min(bw - 1);
5055 let j_lo = i.saturating_sub(bh - 1);
5056 for j in (j_lo..=j_hi).rev() {
5057 let row = i - j;
5058 let col = j;
5059 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
5060 if trace {
5061 let (rng, _) = dec.debug_state();
5062 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
5063 }
5064 let symbol = if uv {
5065 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
5066 } else {
5067 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
5068 };
5069 map[row * bw + col] = color_order[symbol];
5070 if trace {
5071 let (rng, _) = dec.debug_state();
5072 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
5073 }
5074 }
5075 }
5076 map
5077}
5078
5079/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
5080/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
5081/// size class comes from [`filter_intra_size_class_rect`] instead of the
5082/// square-only [`filter_intra_size_class`], and the palette read (when
5083/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
5084/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
5085/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
5086/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
5087#[allow(clippy::too_many_arguments)]
5088fn read_intra_mode_rect(
5089 dec: &mut SymbolDecoder,
5090 cdfs: &mut Cdfs,
5091 above_mode: usize,
5092 left_mode: usize,
5093 cfl: bool,
5094 bw: usize,
5095 bh: usize,
5096 enable_filter_intra: bool,
5097 skip_ctx: usize,
5098 allow_screen_content_tools: bool,
5099 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
5100 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
5101 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
5102 palette: Option<(usize, &[u16])>,
5103 palette_uv_cache: &[u16],
5104 mi_r: usize,
5105 mi_c: usize,
5106) -> Result<(
5107 bool,
5108 usize,
5109 i32,
5110 usize,
5111 i32,
5112 Option<(i32, i32)>,
5113 Option<usize>,
5114 Option<PaletteY>,
5115 Option<PaletteUv>,
5116)> {
5117 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
5118 macro_rules! istep {
5119 ($name:literal, $val:expr) => {
5120 if ec_istep {
5121 let (rng, _) = dec.debug_state();
5122 eprintln!(
5123 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
5124 $name, $val
5125 );
5126 }
5127 };
5128 }
5129 // Same `intra_segment_id` placement as the square reader above.
5130 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
5131 if seg_id_pre_skip() {
5132 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
5133 }
5134 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
5135 istep!("skip", skip as i32);
5136 if !seg_id_pre_skip() {
5137 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
5138 }
5139 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
5140 istep!("cdef", 0);
5141 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
5142 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
5143 // `false`.
5144 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
5145 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
5146 istep!("dq", 0);
5147 let above_ctx = INTRA_MODE_CTX[above_mode];
5148 let left_ctx = INTRA_MODE_CTX[left_mode];
5149 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
5150 istep!("mode", mode as i32);
5151 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
5152 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
5153 } else {
5154 0
5155 };
5156 istep!("angle_y", angle_delta_y);
5157 let uv_mode = if cfl {
5158 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
5159 } else {
5160 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
5161 };
5162 istep!("uv_mode", uv_mode as i32);
5163 let alpha = if cfl && uv_mode == UV_CFL_PRED {
5164 Some(read_cfl_alphas(dec, cdfs))
5165 } else {
5166 None
5167 };
5168 if (9..=12).contains(&uv_mode) {
5169 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
5170 }
5171 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
5172 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
5173 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
5174 } else {
5175 0
5176 };
5177 istep!("angle_uv", angle_delta_uv);
5178 if angle_delta_uv != 0 {
5179 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
5180 }
5181 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
5182 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
5183 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
5184 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
5185 // colours only here, the colour-index maps deferred past `filter_intra`
5186 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
5187 // runs from the caller, after the whole mode-info read).
5188 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
5189 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
5190 if allow_screen_content_tools
5191 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
5192 {
5193 // r6: this is the exact site the removed blanket refusal used to
5194 // guard -- reached for EVERY rect strip in a screen-content frame,
5195 // independent of whether the block ends up using a palette.
5196 RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1));
5197 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
5198 let use_palette_y =
5199 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
5200 if use_palette_y {
5201 if palette.is_none() {
5202 return Err(unsupported(
5203 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
5204 ));
5205 }
5206 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
5207 let colors = read_palette_colors_y(dec, n, cache);
5208 palette_y_pending = Some((n, colors));
5209 }
5210 let palette_uv_mode_ctx = usize::from(use_palette_y);
5211 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
5212 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
5213 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
5214 palette_uv_pending = Some((n, u_colors, v_colors));
5215 }
5216 }
5217 let mut filter_intra = None;
5218 if std::env::var_os("EC_AV1_TRACE").is_some() {
5219 let (rng, _) = dec.debug_state();
5220 eprintln!(
5221 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
5222 class={:?} rng={rng}",
5223 enable_filter_intra as i32,
5224 filter_intra_size_class_rect(bw, bh)
5225 );
5226 }
5227 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
5228 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
5229 if mode == DC_PRED
5230 && enable_filter_intra
5231 && palette_y_pending.is_none()
5232 && let Some(class) = filter_intra_size_class_rect(bw, bh)
5233 {
5234 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
5235 if std::env::var_os("EC_AV1_TRACE").is_some() {
5236 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
5237 }
5238 if use_filter_intra {
5239 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
5240 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
5241 filter_intra = Some(fi_mode);
5242 }
5243 }
5244 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
5245 // same order as [`read_intra_mode`]'s own square path.
5246 let palette_y = palette_y_pending.map(|(n, colors)| {
5247 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
5248 PALETTE_HITS.with(|c| c.set(c.get() + 1));
5249 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
5250 PaletteY { size: n, colors, map }
5251 });
5252 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
5253 let map = decode_color_index_map_wh(dec, cdfs, n, bw / 2, bh / 2, true);
5254 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
5255 PaletteUv { size: n, u_colors, v_colors, map }
5256 });
5257 Ok((
5258 skip,
5259 mode,
5260 angle_delta_y,
5261 uv_mode,
5262 angle_delta_uv,
5263 alpha,
5264 filter_intra,
5265 palette_y,
5266 palette_uv,
5267 ))
5268}
5269
5270/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
5271/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
5272/// above against this block's own *width* and the neighbour to the left
5273/// against its own *height* -- for a square block those are the same value,
5274/// which is why the square-only version can get away with one `own_side`.
5275fn tx_size_context_rect(
5276 n: &Neighbours,
5277 (mi_r, mi_c): (usize, usize),
5278 own_w: usize,
5279 own_h: usize,
5280) -> usize {
5281 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
5282 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
5283 usize::from(above) + usize::from(left)
5284}
5285
5286/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
5287fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
5288 let (cw, ch) = (bw / 2, bh / 2);
5289 let mut ac = vec![0i32; cw * ch];
5290 let mut sum = 0i32;
5291 for cy in 0..ch {
5292 for cx in 0..cw {
5293 let (lx, ly) = (px + cx * 2, py + cy * 2);
5294 let q3 = (i32::from(y.data[ly * y.width + lx])
5295 + i32::from(y.data[ly * y.width + lx + 1])
5296 + i32::from(y.data[(ly + 1) * y.width + lx])
5297 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
5298 << 1;
5299 ac[cy * cw + cx] = q3;
5300 sum += q3;
5301 }
5302 }
5303 let num_pel = (cw * ch) as i32;
5304 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
5305 ac.iter_mut().for_each(|v| *v -= avg);
5306 ac
5307}
5308
5309/// Everything a rect strip already read out of the stream before its luma
5310/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
5311/// (nine values that would otherwise be nine more parameters).
5312struct RectStripModes {
5313 skip: bool,
5314 mode: usize,
5315 angle_delta_y: i32,
5316 uv_predict_mode: usize,
5317 angle_delta_uv: i32,
5318 alpha: Option<(i32, i32)>,
5319 filter_intra: Option<usize>,
5320 smooth_neighbor: bool,
5321 smooth_neighbor_uv: bool,
5322 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
5323 /// mapped through the colour table), sliced per transform unit below --
5324 /// palette prediction reads no edge pixels, so a unit's slice of the
5325 /// whole-block map IS its prediction. Without this a palette strip whose
5326 /// transform splits predicted DC and came out flat grey while the entropy
5327 /// stream stayed in sync (the coefficients are read either way).
5328 palette_y: Option<Vec<u16>>,
5329 /// As `palette_y`, for the un-split chroma transform (U, V).
5330 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
5331}
5332
5333/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
5334/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
5335/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
5336/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
5337/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
5338/// TX_32X16`) and only the second reaches a square -- the reason
5339/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
5340/// already square) mis-tiled 1:4 strips.
5341fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) {
5342 let (mut w, mut h) = (bw.min(64), bh.min(64));
5343 for _ in 0..depth {
5344 match w.cmp(&h) {
5345 std::cmp::Ordering::Greater => w /= 2,
5346 std::cmp::Ordering::Less => h /= 2,
5347 std::cmp::Ordering::Equal => {
5348 w /= 2;
5349 h /= 2;
5350 }
5351 }
5352 }
5353 (w, h)
5354}
5355
5356/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
5357/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
5358/// rect path here refused by name until now ("per-unit rect prediction is not
5359/// ported").
5360///
5361/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
5362/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
5363/// strip the very first step already lands on a SQUARE transform
5364/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
5365/// every further step halves a square) -- so each unit is square and reads
5366/// through the ordinary square [`read_plane`]. What is genuinely rectangular
5367/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
5368/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
5369/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
5370/// split by luma's depth.
5371///
5372/// Each unit predicts off whatever the earlier units of this same block
5373/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
5374/// inside `av1_foreach_transformed_block`, raster order), which is exactly
5375/// what predicting the whole strip in one shot got wrong.
5376#[allow(clippy::too_many_arguments)]
5377fn decode_rect_split(
5378 dec: &mut SymbolDecoder,
5379 cdfs: &mut Cdfs,
5380 neighbours: &mut Neighbours,
5381 at_mi: (usize, usize),
5382 bw: usize,
5383 bh: usize,
5384 // The transform unit's own width and height in pixels. Square for every
5385 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
5386 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
5387 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
5388 tx_w: usize,
5389 tx_h: usize,
5390 m: &RectStripModes,
5391 y: &mut PlaneBuf,
5392 u: &mut PlaneBuf,
5393 v: &mut PlaneBuf,
5394 base_q_idx: u8,
5395 reduced_tx_set: bool,
5396) -> Result<()> {
5397 let (mi_r, mi_c) = at_mi;
5398 let (px, py) = (mi_c * MI, mi_r * MI);
5399 let (cpx, cpy) = (px / 2, py / 2);
5400 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5401 // The chroma transform is picked before any symbol is read, so an
5402 // unsupported chroma shape refuses before this strip desyncs the tile.
5403 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
5404 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
5405 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
5406 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
5407 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
5408 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
5409 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
5410 // squares a rect transform down to a CDF set by
5411 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
5412 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
5413 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
5414 // paths already prove for these same shapes.
5415 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
5416 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
5417 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
5418 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
5419 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
5420 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
5421 _ => None,
5422 };
5423 if !m.skip {
5424 if let Some(i) = match (chroma_w, chroma_h) {
5425 (32, 8) => Some(0),
5426 (8, 32) => Some(1),
5427 (8, 4) => Some(2),
5428 (4, 8) => Some(3),
5429 _ => None,
5430 } {
5431 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
5432 let mut hits = c.get();
5433 hits[i] += 1;
5434 c.set(hits);
5435 });
5436 }
5437 if chroma.is_none() {
5438 // Diagnostic for the next caller that lands here (class
5439 // refusal-names-a-correlate: the message names the tool, not the
5440 // shape); the refusal below keeps its inventory-pinned wording.
5441 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
5442 }
5443 }
5444 // lane-rectsplit r2 (verifier finding): with both callers wired
5445 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
5446 // 64x32/32x64) every shape that reaches here has a table above, so this
5447 // arm is UNREACHABLE today. It stays as the shape guard for the next
5448 // caller -- a new strip size would otherwise hit the `expect` below and
5449 // panic instead of refusing by name -- and so stays in
5450 // `refusal_inventory::REFUSALS`.
5451 if !m.skip && chroma.is_none() {
5452 return Err(unsupported(
5453 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
5454 ));
5455 }
5456 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
5457 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
5458 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1));
5459 }
5460 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
5461 // A square unit reads through the ordinary square [`read_plane`]; a rect
5462 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
5463 // the very tables the unsplit 16x8/32x16 paths use.
5464 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
5465 (w, h) if w == h => None,
5466 (16, 8) | (8, 16) => Some((
5467 if reduced_tx_set {
5468 TxbSet::LumaRect16x8
5469 } else {
5470 TxbSet::LumaRect16x8Set1
5471 },
5472 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
5473 )),
5474 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
5475 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
5476 _ => {
5477 return Err(unsupported(format!(
5478 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
5479 coefficient tables for that shape here)"
5480 )))
5481 }
5482 };
5483 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
5484 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
5485 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
5486 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
5487 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
5488 // per-unit rect walk stay wired above/below; the round that finds that
5489 // defect deletes this refusal and nothing else.
5490 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
5491 let luma_scan = default_scan(tx_w.min(tx_h));
5492 let zero_tu = vec![0i32; tx_w * tx_h];
5493 // The strip's OWN edge availability, the fallback for a transform unit
5494 // whose top-right/bottom-left pixels fall outside the strip.
5495 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5496 for tu_row in 0..bh / tx_h {
5497 for tu_col in 0..bw / tx_w {
5498 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
5499 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
5500 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
5501 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
5502 // transform unit INSIDE a block, which is a different rule from
5503 // the standalone-block table [`Reach::of`] applies -- and the
5504 // reason a depth-2 superblock strip came out one sample off
5505 // before this: `Reach::of(tx, ..)` answered as if the unit were
5506 // its own block at that superblock position.
5507 // * top-right: if the unit's right neighbour is still inside the
5508 // strip the pixels are already reconstructed (`col_off +
5509 // tx_wide < plane_bw`); otherwise only the strip's own top row
5510 // of units can reach past it, through the block-level answer.
5511 // * bottom-left: a unit that is not in the strip's left column
5512 // has none (`col_off > 0` returns 0); inside the strip
5513 // (`row_off + tx_high < plane_bh`) they are the left
5514 // neighbour's, already reconstructed; the last row falls back
5515 // to the block-level answer.
5516 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
5517 // The unit's own window on the block's palette prediction.
5518 if let Some(buf) = &m.palette_y {
5519 let tu_buf: Vec<u16> = (0..tx_h)
5520 .flat_map(|i| {
5521 let base = (row_off + i) * bw + col_off;
5522 buf[base..base + tx_w].iter().copied()
5523 })
5524 .collect();
5525 set_palette_pred(tu_buf);
5526 }
5527 if m.skip {
5528 y.reconstruct_rect(
5529 tu_px,
5530 tu_py,
5531 tx_w,
5532 tx_h,
5533 m.mode,
5534 m.angle_delta_y,
5535 tu_reach,
5536 &zero_tu,
5537 None,
5538 m.filter_intra,
5539 m.smooth_neighbor,
5540 );
5541 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
5542 } else if let Some((rect_set, rect_scan)) = luma_rect {
5543 // The rect-unit twin of the square arm below: same contexts,
5544 // same order, through the rect coefficient reader. The
5545 // `tx_type` CDF row of a filter-intra block is
5546 // `fimode_to_intradir[filter_intra_mode]`, never the block's
5547 // own (always DC_PRED) mode -- [`read_plane`] applies that
5548 // for the square arm, so this one must too.
5549 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
5550 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
5551 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
5552 let (tu_grid, tu_tx_type) = read_coeffs_rect(
5553 dec,
5554 &mut coding,
5555 rect_scan,
5556 tx_w,
5557 tx_h,
5558 tu_skip_ctx,
5559 dc_sign_ctx(tu_around.2),
5560 TxType::DctDct,
5561 )?;
5562 let residual = dequant_and_inverse_typed_wh(
5563 &tu_grid,
5564 tx_w,
5565 tx_h,
5566 crate::decode::bit_depth(),
5567 block_q_idx(),
5568 plane_q_delta(0).0,
5569 plane_q_delta(0).1,
5570 tu_tx_type,
5571 );
5572 y.reconstruct_rect(
5573 tu_px,
5574 tu_py,
5575 tx_w,
5576 tx_h,
5577 m.mode,
5578 m.angle_delta_y,
5579 tu_reach,
5580 &residual,
5581 None,
5582 m.filter_intra,
5583 m.smooth_neighbor,
5584 );
5585 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
5586 } else {
5587 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
5588 // This unit is smaller than the block it sits in, so
5589 // `txb_skip_ctx` is the neighbour-magnitude table, not the
5590 // lone-TU 0 (spec `get_txb_ctx_general`).
5591 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
5592 let tu_grid = read_plane(
5593 dec,
5594 cdfs,
5595 luma_set,
5596 &luma_scan,
5597 0,
5598 tu_around,
5599 m.mode,
5600 m.mode,
5601 m.angle_delta_y,
5602 tu_reach,
5603 y,
5604 tu_px,
5605 tu_py,
5606 tx_w,
5607 tx_w,
5608 base_q_idx,
5609 None,
5610 m.filter_intra,
5611 Some(tu_skip_ctx),
5612 m.smooth_neighbor,
5613 )?;
5614 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
5615 }
5616 }
5617 }
5618 // CHROMA: one un-split rect transform for the whole strip.
5619 let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5620 let reach = block_reach;
5621 let (u_grid, v_grid) = if m.skip {
5622 let zero = vec![0i32; chroma_w * chroma_h];
5623 if let Some((ub, _)) = &m.palette_uv {
5624 set_palette_pred(ub.clone());
5625 }
5626 u.reconstruct_rect(
5627 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
5628 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
5629 );
5630 if let Some((_, vb)) = &m.palette_uv {
5631 set_palette_pred(vb.clone());
5632 }
5633 v.reconstruct_rect(
5634 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
5635 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
5636 );
5637 (zero.clone(), zero)
5638 } else {
5639 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
5640 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
5641 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
5642 // so only the 16x8/8x16 pair takes the mode-indexed default.
5643 let default_tx = if chroma_w.max(chroma_h) >= 32 {
5644 TxType::DctDct
5645 } else {
5646 default_intra_tx_type(m.uv_predict_mode as u8)
5647 };
5648 let around = neighbours.around_mi_rect(at_mi, bw, bh);
5649 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
5650 for plane_idx in 1..=2 {
5651 let skip_ctx =
5652 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
5653 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
5654 let (levels, tx_type) = read_coeffs_rect(
5655 dec,
5656 &mut coding,
5657 chroma_scan,
5658 chroma_w,
5659 chroma_h,
5660 skip_ctx,
5661 dc_sign_ctx(around[plane_idx].2),
5662 default_tx,
5663 )?;
5664 // The same delta_q proof the unsplit rect64 path records
5665 // (lane-rectsplit r4: lifting the split-transform refusal moved
5666 // superblock strips onto this path, so only counting there would
5667 // leave the delta_q gate's counter silent for them).
5668 if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) {
5669 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
5670 }
5671 let residual = dequant_and_inverse_typed_wh(
5672 &levels,
5673 chroma_w,
5674 chroma_h,
5675 crate::decode::bit_depth(),
5676 CURRENT_Q_IDX.with(|c| c.get()),
5677 plane_q_delta(plane_idx).0,
5678 plane_q_delta(plane_idx).1,
5679 tx_type,
5680 );
5681 let cfl = m
5682 .alpha
5683 .zip(ac.as_deref())
5684 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
5685 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
5686 if let Some((ub, vb)) = &m.palette_uv {
5687 let buf = if plane_idx == 1 { ub } else { vb };
5688 set_palette_pred(buf.clone());
5689 }
5690 plane.reconstruct_rect(
5691 cpx,
5692 cpy,
5693 chroma_w,
5694 chroma_h,
5695 m.uv_predict_mode,
5696 m.angle_delta_uv,
5697 reach,
5698 &residual,
5699 cfl,
5700 None,
5701 m.smooth_neighbor_uv,
5702 );
5703 grids.push(levels);
5704 }
5705 let mut it = grids.into_iter();
5706 (it.next().unwrap(), it.next().unwrap())
5707 };
5708 neighbours.record_split_luma_rect_mi(
5709 at_mi,
5710 bw,
5711 bh,
5712 m.mode,
5713 m.uv_predict_mode,
5714 [&u_grid, &v_grid],
5715 );
5716 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
5717 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
5718 if std::env::var_os("EC_AV1_TRACE").is_some() {
5719 let (rng, _) = dec.debug_state();
5720 eprintln!(
5721 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
5722 tx={tx_w}x{tx_h} rng={rng}"
5723 );
5724 }
5725 Ok(())
5726}
5727
5728/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
5729/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
5730/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
5731/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
5732/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
5733/// has no rectangular-transform coefficient reader, and a chroma plane here
5734/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
5735/// with no depth-based square-tiling escape the way luma's own resolved
5736/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
5737/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
5738#[allow(clippy::too_many_arguments)]
5739fn decode_block_rect(
5740 dec: &mut SymbolDecoder,
5741 cdfs: &mut Cdfs,
5742 neighbours: &mut Neighbours,
5743 at: (usize, usize),
5744 bw: usize,
5745 bh: usize,
5746 y: &mut PlaneBuf,
5747 u: &mut PlaneBuf,
5748 v: &mut PlaneBuf,
5749 enable_filter_intra: bool,
5750 allow_screen_content_tools: bool,
5751 base_q_idx: u8,
5752 tx_select: bool,
5753 reduced_tx_set: bool,
5754) -> Result<()> {
5755 let (r, c) = at;
5756 let (px, py) = (c * SUB, r * SUB);
5757 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
5758 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
5759 let palette_uv_cache = neighbours.palette_uv_cache(at);
5760 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
5761 read_intra_mode_rect(
5762 dec,
5763 cdfs,
5764 nb_above_mode,
5765 nb_left_mode,
5766 true,
5767 bw,
5768 bh,
5769 enable_filter_intra,
5770 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
5771 allow_screen_content_tools,
5772 Some((palette_ctx, &palette_cache)),
5773 &palette_uv_cache,
5774 r * (SUB / MI),
5775 c * (SUB / MI),
5776 )?;
5777 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
5778 if smooth_neighbor {
5779 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5780 }
5781 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
5782 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
5783 // `uv_mode`, not the luma one.
5784 let smooth_neighbor_uv =
5785 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
5786 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
5787 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
5788 // rectangle just as happily), so a `use_filter_intra` strip at this level
5789 // predicts instead of refusing. The below-16x16 leaf arm
5790 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
5791 if filter_intra.is_some() {
5792 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
5793 }
5794 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
5795 DC_PRED
5796 } else {
5797 uv_mode
5798 };
5799 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5800 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
5801 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
5802 // one did not, so with `--enable-tx-size-search=0` -- which several gate
5803 // recipes use -- the decoder consumed a symbol the encoder never wrote and
5804 // desynced the tile from that point on. That is why both strips of the
5805 // pinned HORZ quadrant were wrong from their very first pixel, and why our
5806 // range after the read equalled the oracle's range for the whole block.
5807 let depth = if tx_select {
5808 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
5809 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
5810 } else {
5811 0
5812 };
5813 if depth != 0 {
5814 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
5815 // lane-rectsplit r1: a split transform is predicted and reconstructed
5816 // per transform unit, each unit taking its edges from the previous
5817 // unit's reconstruction inside this same strip (spec 5.11.36) --
5818 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
5819 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
5820 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
5821 eprintln!(
5822 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
5823 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
5824 angle_y={angle_delta_y}"
5825 );
5826 }
5827 let modes = RectStripModes {
5828 skip,
5829 mode,
5830 angle_delta_y,
5831 uv_predict_mode,
5832 angle_delta_uv,
5833 alpha,
5834 filter_intra,
5835 smooth_neighbor,
5836 smooth_neighbor_uv,
5837 palette_y: palette_y
5838 .as_ref()
5839 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
5840 palette_uv: palette_uv.as_ref().map(|p| {
5841 (
5842 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
5843 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
5844 )
5845 }),
5846 };
5847 if palette_y.is_some() || palette_uv.is_some() {
5848 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
5849 }
5850 decode_rect_split(
5851 dec,
5852 cdfs,
5853 neighbours,
5854 (mi_r, mi_c),
5855 bw,
5856 bh,
5857 tx_w,
5858 tx_h,
5859 &modes,
5860 y,
5861 u,
5862 v,
5863 base_q_idx,
5864 reduced_tx_set,
5865 )?;
5866 // This early return skips this fn's own tail, so the palette
5867 // neighbour state has to be stamped HERE too: without it a split-tx
5868 // strip left the above/left palette arrays holding a DEAD block's
5869 // colours, and the next block's colour cache
5870 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
5871 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
5872 // and only those pixels were wrong (lane-palette2 r10).
5873 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
5874 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
5875 let (puv_size, puv_colors) =
5876 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
5877 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
5878 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
5879 return Ok(());
5880 }
5881 let (tx_w, tx_h) = (bw, bh);
5882 let (cpx, cpy) = (px / 2, py / 2);
5883 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5884 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5885 if std::env::var_os("EC_AV1_TRACE").is_some() {
5886 let (rng, _) = dec.debug_state();
5887 eprintln!(
5888 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
5889 skip={} tx={depth} rng={rng}",
5890 skip as i32
5891 );
5892 }
5893 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
5894 // block's prediction is the reconstructed colour-index map, set fresh
5895 // right before each `reconstruct_rect` call below (lane-palette2 r4).
5896 if let Some(ref pyv) = palette_y {
5897 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
5898 set_palette_pred(buf);
5899 }
5900 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
5901 (
5902 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
5903 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
5904 )
5905 });
5906 if skip {
5907 y.reconstruct_rect(
5908 px,
5909 py,
5910 bw,
5911 bh,
5912 mode,
5913 angle_delta_y,
5914 reach,
5915 &vec![0i32; bw * bh],
5916 None,
5917 filter_intra,
5918 smooth_neighbor,
5919 );
5920 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5921 if let Some((ub, _)) = &palette_uv_bufs {
5922 set_palette_pred(ub.clone());
5923 }
5924 u.reconstruct_rect(
5925 cpx,
5926 cpy,
5927 chroma_w,
5928 chroma_h,
5929 uv_predict_mode,
5930 angle_delta_uv,
5931 reach,
5932 &vec![0i32; chroma_w * chroma_h],
5933 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5934 None,
5935 smooth_neighbor_uv,
5936 );
5937 if let Some((_, vb)) = &palette_uv_bufs {
5938 set_palette_pred(vb.clone());
5939 }
5940 v.reconstruct_rect(
5941 cpx,
5942 cpy,
5943 chroma_w,
5944 chroma_h,
5945 uv_predict_mode,
5946 angle_delta_uv,
5947 reach,
5948 &vec![0i32; chroma_w * chroma_h],
5949 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5950 None,
5951 smooth_neighbor_uv,
5952 );
5953 neighbours.record_rect(
5954 at,
5955 bw,
5956 bh,
5957 mode,
5958 uv_predict_mode,
5959 &[
5960 vec![0i32; bw * bh],
5961 vec![0i32; chroma_w * chroma_h],
5962 vec![0i32; chroma_w * chroma_h],
5963 ],
5964 );
5965 } else {
5966 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
5967 // reduces both size pairs to their square-up CDF sets
5968 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
5969 // doc comments); the scan order and 2D context tables are the real
5970 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
5971 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
5972 (&SCAN_32X16, &SCAN_16X8)
5973 } else {
5974 (&SCAN_16X32, &SCAN_8X16)
5975 };
5976 // lane-rectwire r3: real coefficients desync a pixel-exact gate
5977 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
5978 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
5979 // pixel (not a subtle context-table off-by-one), while the sibling
5980 // non-rect quadrants of the same frame match. Range-ladder bisection
5981 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
5982 // but the intra key-frame path has no traced symbol between the
5983 // partition read and the first coefficient block (mode/skip/tx_depth
5984 // reads are all untraced in libaom's decodeframe.c intra path, unlike
5985 // the inter EC_TRACE_MODE this round added), so a same-length range
5986 // comparison wasn't reachable within budget -- see
5987 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
5988 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
5989 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
5990 // libaom and match). lane-rectwire r4: range-ladder against the
5991 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
5992 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
5993 // both confirmed in sync -- rng=58692 on both sides right after
5994 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
5995 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
5996 // immediately after: ours moves rng 58692 -> 43570, which cannot be
5997 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
5998 // its own tx_size read) unless oracle's tx symbol is a near-certainty
5999 // CDF that barely narrows the range -- i.e. this decoder's
6000 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
6001 // a 32x16/16x32 strip is the first diverging symbol, not the
6002 // coefficient-context math r3 already cleared. Not confirmed byte-
6003 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
6004 // `read_tx_size`'s own rng, not attempted this round -- budget), so
6005 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
6006 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
6007 // it unconditionally where both square paths gate on `tx_select`. With
6008 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
6009 // decoder consumed one that was never there.
6010 {
6011 let around = neighbours.around_rect(at, bw, bh);
6012 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
6013 let (luma_levels, luma_tx_type) = read_coeffs_rect(
6014 dec,
6015 &mut luma_coding,
6016 luma_scan,
6017 bw,
6018 bh,
6019 0,
6020 dc_sign_ctx(around[0].2),
6021 TxType::DctDct,
6022 )?;
6023 if std::env::var_os("EC_AV1_TRACE").is_some() {
6024 let (rng, _) = dec.debug_state();
6025 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
6026 }
6027 let luma_residual = dequant_and_inverse_typed_wh(
6028 &luma_levels,
6029 bw,
6030 bh,
6031 crate::decode::bit_depth(),
6032 block_q_idx(),
6033 plane_q_delta(0).0,
6034 plane_q_delta(0).1,
6035 luma_tx_type,
6036 );
6037 y.reconstruct_rect(
6038 px,
6039 py,
6040 bw,
6041 bh,
6042 mode,
6043 angle_delta_y,
6044 reach,
6045 &luma_residual,
6046 None,
6047 filter_intra,
6048 smooth_neighbor,
6049 );
6050 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6051 if let Some((ub, _)) = &palette_uv_bufs {
6052 set_palette_pred(ub.clone());
6053 }
6054 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
6055 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
6056 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
6057 let (u_levels, u_tx_type) = read_coeffs_rect(
6058 dec,
6059 &mut u_coding,
6060 chroma_scan,
6061 chroma_w,
6062 chroma_h,
6063 u_skip_ctx,
6064 dc_sign_ctx(around[1].2),
6065 u_default_tx,
6066 )?;
6067 if std::env::var_os("EC_AV1_TRACE").is_some() {
6068 let (rng, _) = dec.debug_state();
6069 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
6070 }
6071 let u_residual = dequant_and_inverse_typed_wh(
6072 &u_levels,
6073 chroma_w,
6074 chroma_h,
6075 crate::decode::bit_depth(),
6076 block_q_idx(),
6077 plane_q_delta(1).0,
6078 plane_q_delta(1).1,
6079 u_tx_type,
6080 );
6081 u.reconstruct_rect(
6082 cpx,
6083 cpy,
6084 chroma_w,
6085 chroma_h,
6086 uv_predict_mode,
6087 angle_delta_uv,
6088 reach,
6089 &u_residual,
6090 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6091 None,
6092 smooth_neighbor_uv,
6093 );
6094 if let Some((_, vb)) = &palette_uv_bufs {
6095 set_palette_pred(vb.clone());
6096 }
6097 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
6098 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
6099 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
6100 let (v_levels, v_tx_type) = read_coeffs_rect(
6101 dec,
6102 &mut v_coding,
6103 chroma_scan,
6104 chroma_w,
6105 chroma_h,
6106 v_skip_ctx,
6107 dc_sign_ctx(around[2].2),
6108 v_default_tx,
6109 )?;
6110 if std::env::var_os("EC_AV1_TRACE").is_some() {
6111 let (rng, _) = dec.debug_state();
6112 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
6113 }
6114 let v_residual = dequant_and_inverse_typed_wh(
6115 &v_levels,
6116 chroma_w,
6117 chroma_h,
6118 crate::decode::bit_depth(),
6119 block_q_idx(),
6120 plane_q_delta(2).0,
6121 plane_q_delta(2).1,
6122 v_tx_type,
6123 );
6124 v.reconstruct_rect(
6125 cpx,
6126 cpy,
6127 chroma_w,
6128 chroma_h,
6129 uv_predict_mode,
6130 angle_delta_uv,
6131 reach,
6132 &v_residual,
6133 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6134 None,
6135 smooth_neighbor_uv,
6136 );
6137 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
6138 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
6139 }
6140 }
6141 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
6142 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
6143 let (puv_size, puv_colors) =
6144 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
6145 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
6146 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
6147 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
6148 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
6149 if std::env::var_os("EC_AV1_TRACE").is_some() {
6150 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
6151 }
6152 Ok(())
6153}
6154
6155/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
6156/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
6157/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
6158/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
6159/// the second strip of a HORZ/VERT split sits offset by half the 16x16
6160/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
6161/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
6162/// previous strip is directly above (same column, `mi_h` rows up) or
6163/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
6164/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
6165/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
6166/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
6167/// this strip's real position, never the coarse `record_rect` (which the
6168/// caller uses once, after both strips, exactly like the `VERT_B` arm next
6169/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
6170/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
6171/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
6172/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
6173#[allow(clippy::too_many_arguments)]
6174fn decode_leaf_rect(
6175 dec: &mut SymbolDecoder,
6176 cdfs: &mut Cdfs,
6177 neighbours: &mut Neighbours,
6178 outer_at: (usize, usize),
6179 leaf_mi: (usize, usize),
6180 bw: usize,
6181 bh: usize,
6182 prev_leaf: Option<((usize, usize), usize)>,
6183 y: &mut PlaneBuf,
6184 u: &mut PlaneBuf,
6185 v: &mut PlaneBuf,
6186 enable_filter_intra: bool,
6187 allow_screen_content_tools: bool,
6188 base_q_idx: u8,
6189 tx_select: bool,
6190 reduced_tx_set: bool,
6191) -> Result<usize> {
6192 let _ = base_q_idx;
6193 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
6194 eprintln!(
6195 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
6196 dec.debug_state().0
6197 );
6198 }
6199 let (r, c) = outer_at;
6200 let mut above_mode = neighbours.above_mode[c];
6201 let mut left_mode = neighbours.left_mode[r];
6202 let (mi_w, mi_h) = (bw / MI, bh / MI);
6203 if let Some(((pr, pc), pmode)) = prev_leaf {
6204 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
6205 above_mode = pmode;
6206 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
6207 left_mode = pmode;
6208 }
6209 }
6210 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
6211 // cannot hold the modes a split (or a pair of strips) leaves behind, so
6212 // when the map holds the block at exactly this strip's above/left mi it
6213 // is the neighbour libaom's `above_mi`/`left_mi` reads.
6214 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
6215 // availability-correct -- four 16x8 strips share one coarse 16x16
6216 // `left_mode` cell too, so the fallback must not stand in for an absent
6217 // tile-edge neighbour.
6218 let (above_mode, left_mode) =
6219 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
6220 let smooth_neighbor =
6221 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
6222 if smooth_neighbor {
6223 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6224 }
6225 // The palette-Y mode CDF row is picked by the neighbours' palette use
6226 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
6227 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
6228 // a palette narrows the wrong interval and desyncs the tile even when the
6229 // decoded bit is the same. The cell is the 16px-SUB cell containing the
6230 // leaf (the palette neighbour arrays have no finer granularity).
6231 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
6232 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(pal_at);
6233 let palette_uv_cache = neighbours.palette_uv_cache(pal_at);
6234 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
6235 read_intra_mode_rect(
6236 dec,
6237 cdfs,
6238 above_mode,
6239 left_mode,
6240 true,
6241 bw,
6242 bh,
6243 enable_filter_intra,
6244 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
6245 allow_screen_content_tools,
6246 Some((palette_ctx, &palette_cache)),
6247 &palette_uv_cache,
6248 leaf_mi.0,
6249 leaf_mi.1,
6250 )?;
6251 if palette_y.is_some() || palette_uv.is_some() {
6252 // Symbols (mode/size/colours/index map) are all read above, so the
6253 // tile stays in sync; only the *pixel* reconstruction of a palette on
6254 // a below-16x16 strip is unported and ungated (lane-palette2 r7).
6255 return Err(unsupported(
6256 "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)",
6257 ));
6258 }
6259 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
6260 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
6261 }
6262 if filter_intra.is_some() {
6263 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
6264 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
6265 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
6266 // below already makes; this refusal was square-only prose.
6267 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
6268 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.set(c.get() + 1));
6269 }
6270 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
6271 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
6272 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
6273 // a constant `false`.
6274 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
6275 let depth = if tx_select {
6276 let ctx = tx_size_context_rect(neighbours, leaf_mi, bw, bh);
6277 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
6278 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
6279 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
6280 // count (3), different CDF row: a wrong-table read of a real symbol,
6281 // the class that cost lane-rectsplit r1 its 64x32 depth.
6282 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
6283 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
6284 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
6285 // function also decodes) sit at depth 2, so they read
6286 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
6287 // while `tx_size_cat2` belongs to the 32-level shapes
6288 // ([`decode_block_rect`]). Both tables carry three symbols, so the
6289 // wrong one decodes a plausible depth from the wrong probabilities:
6290 // the range diverges silently at the first such leaf and every later
6291 // symbol in the tile is read from the wrong place (class
6292 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
6293 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
6294 } else {
6295 0
6296 };
6297 if depth != 0 {
6298 // The same per-transform-unit walk the bigger strips take
6299 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
6300 // depth 2), addressed at this leaf's own mi position.
6301 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
6302 SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
6303 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
6304 let modes = RectStripModes {
6305 skip,
6306 mode,
6307 angle_delta_y,
6308 uv_predict_mode,
6309 angle_delta_uv,
6310 alpha,
6311 filter_intra,
6312 smooth_neighbor,
6313 // lane-rectsplitx r3: the split arm hard-coded `false` here while
6314 // the unsplit arm below passes the real neighbour answer -- chroma
6315 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
6316 smooth_neighbor_uv,
6317 // Both callers refuse a palette on this shape above (pixel
6318 // reconstruction is unported here), so the split units carry none.
6319 palette_y: None,
6320 palette_uv: None,
6321 };
6322 decode_rect_split(
6323 dec,
6324 cdfs,
6325 neighbours,
6326 leaf_mi,
6327 bw,
6328 bh,
6329 tx_w,
6330 tx_h,
6331 &modes,
6332 y,
6333 u,
6334 v,
6335 base_q_idx,
6336 reduced_tx_set,
6337 )?;
6338 return Ok(mode);
6339 }
6340 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
6341 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6342 let (cpx, cpy) = (px / 2, py / 2);
6343 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
6344 let (luma_levels, u_levels, v_levels);
6345 if skip {
6346 luma_levels = vec![0i32; bw * bh];
6347 u_levels = vec![0i32; chroma_w * chroma_h];
6348 v_levels = vec![0i32; chroma_w * chroma_h];
6349 y.reconstruct_rect(
6350 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
6351 smooth_neighbor,
6352 );
6353 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6354 u.reconstruct_rect(
6355 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
6356 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
6357 );
6358 v.reconstruct_rect(
6359 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
6360 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
6361 );
6362 } else {
6363 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
6364 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
6365 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
6366 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
6367 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
6368 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
6369 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
6370 (&SCAN_16X8, &SCAN_8X4)
6371 } else {
6372 (&SCAN_8X16, &SCAN_4X8)
6373 };
6374 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
6375 let luma_set = if reduced_tx_set {
6376 TxbSet::LumaRect16x8
6377 } else {
6378 TxbSet::LumaRect16x8Set1
6379 };
6380 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
6381 let (l_levels, luma_tx_type) = read_coeffs_rect(
6382 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
6383 )?;
6384 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
6385 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
6386 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
6387 }
6388 luma_levels = l_levels;
6389 let luma_residual = dequant_and_inverse_typed_wh(
6390 &luma_levels, bw, bh, crate::decode::bit_depth(),
6391 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,
6392 );
6393 y.reconstruct_rect(
6394 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
6395 smooth_neighbor,
6396 );
6397 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6398 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
6399 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
6400 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
6401 let (u_l, u_tx_type) = read_coeffs_rect(
6402 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
6403 dc_sign_ctx(around[1].2), u_default_tx,
6404 )?;
6405 u_levels = u_l;
6406 let u_residual = dequant_and_inverse_typed_wh(
6407 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
6408 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,
6409 );
6410 u.reconstruct_rect(
6411 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
6412 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
6413 );
6414 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
6415 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
6416 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
6417 let (v_l, v_tx_type) = read_coeffs_rect(
6418 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
6419 dc_sign_ctx(around[2].2), v_default_tx,
6420 )?;
6421 v_levels = v_l;
6422 let v_residual = dequant_and_inverse_typed_wh(
6423 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
6424 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,
6425 );
6426 v.reconstruct_rect(
6427 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
6428 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
6429 );
6430 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
6431 }
6432 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
6433 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
6434 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
6435 // This leaf is necessarily non-palette (a palette one refused above), so
6436 // it must CLEAR the above/left palette state over its own span -- without
6437 // this the next block's `palette_y_mode` ctx and colour cache were read
6438 // off whatever block last covered the cell (lane-palette2 r8).
6439 neighbours.record_palette_y_rect(pal_at, bw, bh, 0, [0u16; 8]);
6440 neighbours.record_palette_uv_rect(pal_at, bw, bh, 0, [0u16; 8]);
6441 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
6442 // rows -- record the whole span, not one cell.
6443 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
6444 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
6445 Ok(mode)
6446}
6447
6448/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
6449/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
6450/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
6451/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
6452/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
6453/// strip's mode so this one's mode context sees its true above/left
6454/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
6455///
6456/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
6457/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
6458/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
6459/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
6460/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
6461/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
6462/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
6463///
6464/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
6465/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
6466/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
6467/// unexamined.
6468#[allow(clippy::too_many_arguments)]
6469fn decode_block_rect4(
6470 dec: &mut SymbolDecoder,
6471 cdfs: &mut Cdfs,
6472 neighbours: &mut Neighbours,
6473 strip_mi: (usize, usize),
6474 bw: usize,
6475 bh: usize,
6476 prev_strip: Option<((usize, usize), usize)>,
6477 y: &mut PlaneBuf,
6478 u: &mut PlaneBuf,
6479 v: &mut PlaneBuf,
6480 enable_filter_intra: bool,
6481 allow_screen_content_tools: bool,
6482 base_q_idx: u8,
6483 tx_select: bool,
6484) -> Result<(usize, usize)> {
6485 let _ = base_q_idx;
6486 let (mi_r, mi_c) = strip_mi;
6487 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
6488 let (mi_w, mi_h) = (bw / MI, bh / MI);
6489 let mut above_mode = neighbours.above_mode[c];
6490 let mut left_mode = neighbours.left_mode[r];
6491 if let Some(((pr, pc), pmode)) = prev_strip {
6492 if pc == mi_c && mi_r == pr + mi_h {
6493 above_mode = pmode;
6494 } else if pr == mi_r && mi_c == pc + mi_w {
6495 left_mode = pmode;
6496 }
6497 }
6498 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
6499 // availability-correct neighbour modes (see
6500 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
6501 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
6502 let (above_mode, left_mode) =
6503 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
6504 let (
6505 skip,
6506 mode,
6507 angle_delta_y,
6508 uv_mode,
6509 angle_delta_uv,
6510 alpha,
6511 filter_intra,
6512 palette_y,
6513 palette_uv,
6514 ) = read_intra_mode_rect(
6515 dec,
6516 cdfs,
6517 above_mode,
6518 left_mode,
6519 true,
6520 bw,
6521 bh,
6522 enable_filter_intra,
6523 neighbours.skip_txfm_ctx(mi_r, mi_c),
6524 allow_screen_content_tools,
6525 None,
6526 &[],
6527 mi_r,
6528 mi_c,
6529 )?;
6530 // Merge of lane-palette2: `read_intra_mode_rect` now reads the palette
6531 // syntax for every rect strip, but this 1:4 decoder has no palette
6532 // reconstruction path (its caller never passes a cache). The symbols are
6533 // still read, so the stream stays in sync; a strip that ACTUALLY uses a
6534 // palette is refused rather than reconstructed wrong.
6535 if palette_y.is_some() || palette_uv.is_some() {
6536 return Err(unsupported(
6537 "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)",
6538 ));
6539 }
6540 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
6541 if smooth_neighbor {
6542 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6543 }
6544 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
6545 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
6546 // `r * (SUB / MI)` names a different mi column and the chroma
6547 // edge-filter strength was read from the wrong neighbour (measured:
6548 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
6549 // with luma bit-exact).
6550 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
6551 if filter_intra.is_some() {
6552 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
6553 if bw > bh {
6554 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1));
6555 } else {
6556 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1));
6557 }
6558 }
6559 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
6560 DC_PRED
6561 } else {
6562 uv_mode
6563 };
6564 let depth = if tx_select {
6565 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
6566 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
6567 } else {
6568 0
6569 };
6570 if depth != 0 {
6571 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
6572 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
6573 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
6574 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
6575 // both interleave in every real stream.
6576 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
6577 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
6578 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
6579 // predicted -- depth 1 fires FIRST in every attempt that splits at
6580 // all, so a depth-2-only lift could never be gated. The r1 mismatch
6581 // was never the rect unit: it was the neighbour MODE the strip reads
6582 // (see `modes_above_left_mi`).
6583 let which = if depth == 1 {
6584 &RECT4_SPLIT_DEPTH1_HITS
6585 } else {
6586 &RECT4_SPLIT_DEPTH2_HITS
6587 };
6588 which.with(|c| c.set(c.get() + 1));
6589 let modes = RectStripModes {
6590 skip,
6591 mode,
6592 angle_delta_y,
6593 uv_predict_mode,
6594 angle_delta_uv,
6595 alpha,
6596 filter_intra,
6597 smooth_neighbor,
6598 smooth_neighbor_uv,
6599 // Both callers refuse a palette on this shape above (pixel
6600 // reconstruction is unported here), so the split units carry none.
6601 palette_y: None,
6602 palette_uv: None,
6603 };
6604 decode_rect_split(
6605 dec,
6606 cdfs,
6607 neighbours,
6608 (mi_r, mi_c),
6609 bw,
6610 bh,
6611 tx_w,
6612 tx_h,
6613 &modes,
6614 y,
6615 u,
6616 v,
6617 base_q_idx,
6618 false,
6619 )?;
6620 if bw > bh {
6621 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
6622 } else {
6623 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
6624 }
6625 if !skip {
6626 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
6627 }
6628 return Ok((mode, uv_predict_mode));
6629 }
6630 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
6631 // that is 8 px tall, so each strip stamps every cell it touches and the
6632 // LAST strip wins -- which is the right answer for the block below/right
6633 // of the 32x32, the only reader outside it. Written after this strip's
6634 // own context read above, never before.
6635 for cell in 0..bw.div_ceil(SUB) {
6636 neighbours.above_mode[c + cell] = mode;
6637 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
6638 neighbours.above_side[c + cell] = bw;
6639 }
6640 for cell in 0..bh.div_ceil(SUB) {
6641 neighbours.left_mode[r + cell] = mode;
6642 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
6643 neighbours.left_side[r + cell] = bh;
6644 }
6645 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
6646 // [`decode_leaf_rect`] does (the split arm above records these through
6647 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
6648 // `sub8_mode_row` holding the previous block, and the next 32x32's
6649 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
6650 // fixture).
6651 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
6652 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
6653 let (px, py) = (mi_c * MI, mi_r * MI);
6654 let (cpx, cpy) = (px / 2, py / 2);
6655 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
6656 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6657 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
6658 (&SCAN_32X8, &SCAN_16X4)
6659 } else {
6660 (&SCAN_8X32, &SCAN_4X16)
6661 };
6662 let (luma_levels, u_levels, v_levels) = if skip {
6663 (
6664 vec![0i32; bw * bh],
6665 vec![0i32; chroma_w * chroma_h],
6666 vec![0i32; chroma_w * chroma_h],
6667 )
6668 } else {
6669 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
6670 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
6671 let (luma_levels, luma_tx_type) = read_coeffs_rect(
6672 dec,
6673 &mut luma_coding,
6674 luma_scan,
6675 bw,
6676 bh,
6677 0,
6678 dc_sign_ctx(around[0].2),
6679 TxType::DctDct,
6680 )?;
6681 let mut planes = Vec::with_capacity(2);
6682 for plane in 1..3 {
6683 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
6684 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
6685 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
6686 let (levels, tx_type) = read_coeffs_rect(
6687 dec,
6688 &mut coding,
6689 chroma_scan,
6690 chroma_w,
6691 chroma_h,
6692 skip_ctx,
6693 dc_sign_ctx(around[plane].2),
6694 default_tx,
6695 )?;
6696 planes.push((levels, tx_type));
6697 }
6698 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
6699 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
6700 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
6701 let luma_residual = dequant_and_inverse_typed_wh(
6702 &luma_levels,
6703 bw,
6704 bh,
6705 crate::decode::bit_depth(),
6706 block_q_idx(),
6707 plane_q_delta(0).0,
6708 plane_q_delta(0).1,
6709 luma_tx_type,
6710 );
6711 y.reconstruct_rect(
6712 px,
6713 py,
6714 bw,
6715 bh,
6716 mode,
6717 angle_delta_y,
6718 reach,
6719 &luma_residual,
6720 None,
6721 filter_intra,
6722 smooth_neighbor,
6723 );
6724 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6725 for (plane, buf, levels, tx_type) in [
6726 (1usize, &mut *u, &u_levels, u_tx_type),
6727 (2, &mut *v, &v_levels, v_tx_type),
6728 ] {
6729 let residual = dequant_and_inverse_typed_wh(
6730 levels,
6731 chroma_w,
6732 chroma_h,
6733 crate::decode::bit_depth(),
6734 block_q_idx(),
6735 plane_q_delta(plane).0,
6736 plane_q_delta(plane).1,
6737 tx_type,
6738 );
6739 buf.reconstruct_rect(
6740 cpx,
6741 cpy,
6742 chroma_w,
6743 chroma_h,
6744 uv_predict_mode,
6745 angle_delta_uv,
6746 reach,
6747 &residual,
6748 alpha
6749 .zip(ac.as_deref())
6750 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
6751 None,
6752 smooth_neighbor_uv,
6753 );
6754 }
6755 neighbours.record_mi_rect(
6756 (mi_r, mi_c),
6757 bw,
6758 bh,
6759 &[luma_levels, u_levels, v_levels],
6760 );
6761 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
6762 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
6763 if bw > bh {
6764 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
6765 } else {
6766 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
6767 }
6768 return Ok((mode, uv_predict_mode));
6769 };
6770 y.reconstruct_rect(
6771 px,
6772 py,
6773 bw,
6774 bh,
6775 mode,
6776 angle_delta_y,
6777 reach,
6778 &luma_levels,
6779 None,
6780 filter_intra,
6781 smooth_neighbor,
6782 );
6783 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6784 u.reconstruct_rect(
6785 cpx,
6786 cpy,
6787 chroma_w,
6788 chroma_h,
6789 uv_predict_mode,
6790 angle_delta_uv,
6791 reach,
6792 &u_levels,
6793 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6794 None,
6795 smooth_neighbor_uv,
6796 );
6797 v.reconstruct_rect(
6798 cpx,
6799 cpy,
6800 chroma_w,
6801 chroma_h,
6802 uv_predict_mode,
6803 angle_delta_uv,
6804 reach,
6805 &v_levels,
6806 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6807 None,
6808 smooth_neighbor_uv,
6809 );
6810 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
6811 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
6812 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
6813 if bw > bh {
6814 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
6815 } else {
6816 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
6817 }
6818 Ok((mode, uv_predict_mode))
6819}
6820
6821/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
6822/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
6823/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
6824/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
6825/// cap, so LUMA needs the same corner truncation [`decode_block`] already
6826/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
6827/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
6828/// this function's own charter/report), so both strips read a real 32x32
6829/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
6830/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
6831/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
6832/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
6833/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
6834/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
6835/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
6836/// that function, only the single-transform-unit (`tx_depth == 0`) case is
6837/// supported: a split transform refuses by name rather than guess-decode.
6838#[allow(clippy::too_many_arguments)]
6839fn decode_block_rect64(
6840 dec: &mut SymbolDecoder,
6841 cdfs: &mut Cdfs,
6842 neighbours: &mut Neighbours,
6843 at: (usize, usize),
6844 bw: usize,
6845 bh: usize,
6846 y: &mut PlaneBuf,
6847 u: &mut PlaneBuf,
6848 v: &mut PlaneBuf,
6849 enable_filter_intra: bool,
6850 allow_screen_content_tools: bool,
6851 base_q_idx: u8,
6852 tx_select: bool,
6853 reduced_tx_set: bool,
6854) -> Result<()> {
6855 let (r, c) = at;
6856 let (px, py) = (c * SUB, r * SUB);
6857 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
6858 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
6859 let palette_uv_cache = neighbours.palette_uv_cache(at);
6860 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
6861 read_intra_mode_rect(
6862 dec,
6863 cdfs,
6864 nb_above_mode,
6865 nb_left_mode,
6866 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
6867 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
6868 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
6869 // correct), CFL must never be offered here -- passing `true`
6870 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
6871 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
6872 // from this block's very first symbol (lane-sbpart r3 bisect).
6873 false,
6874 bw,
6875 bh,
6876 enable_filter_intra,
6877 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
6878 allow_screen_content_tools,
6879 Some((palette_ctx, &palette_cache)),
6880 &palette_uv_cache,
6881 r * (SUB / MI),
6882 c * (SUB / MI),
6883 )?;
6884 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
6885 // The luma coefficient path here is the corner-cropped 32x32 real
6886 // transform embedded in a 64x32/32x64 grid ([`decode_block_rect64`]'s
6887 // own doc comment) -- a real (non-skip) palette block's residual
6888 // needs the plain, uncropped rect reader [`decode_block_rect`] already
6889 // has, not this one's truncation. `skip` (no residual at all) is
6890 // still supported below (lane-palette2 r4).
6891 return Err(unsupported(
6892 "a palette block with a real transform on a superblock-level HORZ/VERT \
6893 strip (corner-cropped luma coefficients not ported for palette)",
6894 ));
6895 }
6896 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
6897 if smooth_neighbor {
6898 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6899 }
6900 let smooth_neighbor_uv =
6901 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
6902 if filter_intra.is_some() {
6903 // `filter_intra_size_class_rect` already returns `None` for both
6904 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
6905 // 32 on both axes), so this symbol is never read at this level --
6906 // kept only as the same defensive refusal [`decode_block_rect`] has.
6907 return Err(unsupported(
6908 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
6909 av1_filter_intra_allowed_bsize caps at 32x32)",
6910 ));
6911 }
6912 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
6913 DC_PRED
6914 } else {
6915 uv_mode
6916 };
6917 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
6918 let depth = if tx_select {
6919 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
6920 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
6921 // counts `sub_tx_size_map` steps from the block's own max rect
6922 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
6923 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
6924 // steps, so this level's category is 3 (the same one a 64x64 square
6925 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
6926 // here was a wrong-table read of a real symbol.
6927 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
6928 } else {
6929 0
6930 };
6931 if depth != 0 {
6932 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
6933 // lane-rectsplit r1/r4: the superblock-level strip splits its
6934 // transform through the very same per-unit path as its 32x32-level
6935 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
6936 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
6937 // measured the old square formula mis-tiling exactly that strip).
6938 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
6939 if bw.max(bh) / bw.min(bh) == 4 {
6940 let which = if depth == 1 {
6941 &RECT4_SPLIT_DEPTH1_HITS
6942 } else {
6943 &RECT4_SPLIT_DEPTH2_HITS
6944 };
6945 which.with(|c| c.set(c.get() + 1));
6946 }
6947 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
6948 eprintln!(
6949 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
6950 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
6951 angle_y={angle_delta_y}"
6952 );
6953 }
6954 let modes = RectStripModes {
6955 skip,
6956 mode,
6957 angle_delta_y,
6958 uv_predict_mode,
6959 angle_delta_uv,
6960 alpha,
6961 filter_intra,
6962 smooth_neighbor,
6963 smooth_neighbor_uv,
6964 palette_y: palette_y
6965 .as_ref()
6966 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
6967 palette_uv: palette_uv.as_ref().map(|p| {
6968 (
6969 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
6970 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
6971 )
6972 }),
6973 };
6974 if palette_y.is_some() || palette_uv.is_some() {
6975 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
6976 }
6977 decode_rect_split(
6978 dec,
6979 cdfs,
6980 neighbours,
6981 (mi_r, mi_c),
6982 bw,
6983 bh,
6984 tx_w,
6985 tx_h,
6986 &modes,
6987 y,
6988 u,
6989 v,
6990 base_q_idx,
6991 reduced_tx_set,
6992 )?;
6993 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
6994 // (lane-palette2 r10): this return skips the fn's own tail, so a
6995 // split-tx superblock strip would otherwise leave the above/left
6996 // palette arrays holding a dead block's colours.
6997 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
6998 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
6999 let (puv_size, puv_colors) =
7000 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7001 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
7002 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
7003 return Ok(());
7004 }
7005 let (tx_w, tx_h) = (bw, bh);
7006 let (cpx, cpy) = (px / 2, py / 2);
7007 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
7008 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
7009 if let Some(ref pyv) = palette_y {
7010 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
7011 set_palette_pred(buf);
7012 }
7013 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
7014 (
7015 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
7016 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
7017 )
7018 });
7019 if skip {
7020 y.reconstruct_rect(
7021 px,
7022 py,
7023 bw,
7024 bh,
7025 mode,
7026 angle_delta_y,
7027 reach,
7028 &vec![0i32; bw * bh],
7029 None,
7030 filter_intra,
7031 smooth_neighbor,
7032 );
7033 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7034 if let Some((ub, _)) = &palette_uv_bufs {
7035 set_palette_pred(ub.clone());
7036 }
7037 u.reconstruct_rect(
7038 cpx,
7039 cpy,
7040 chroma_w,
7041 chroma_h,
7042 uv_predict_mode,
7043 angle_delta_uv,
7044 reach,
7045 &vec![0i32; chroma_w * chroma_h],
7046 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7047 None,
7048 smooth_neighbor_uv,
7049 );
7050 if let Some((_, vb)) = &palette_uv_bufs {
7051 set_palette_pred(vb.clone());
7052 }
7053 v.reconstruct_rect(
7054 cpx,
7055 cpy,
7056 chroma_w,
7057 chroma_h,
7058 uv_predict_mode,
7059 angle_delta_uv,
7060 reach,
7061 &vec![0i32; chroma_w * chroma_h],
7062 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7063 None,
7064 smooth_neighbor_uv,
7065 );
7066 neighbours.record_rect(
7067 at,
7068 bw,
7069 bh,
7070 mode,
7071 uv_predict_mode,
7072 &[
7073 vec![0i32; bw * bh],
7074 vec![0i32; chroma_w * chroma_h],
7075 vec![0i32; chroma_w * chroma_h],
7076 ],
7077 );
7078 } else {
7079 let around = neighbours.around_rect(at, bw, bh);
7080 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
7081 // (see this function's own doc comment). A 64-length axis codes only
7082 // its low 32 coefficients, so the corner is `min(bw, 32)` x
7083 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
7084 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
7085 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
7086 let scan32 = default_scan(TX32);
7087 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7088 let (rng, _) = dec.debug_state();
7089 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
7090 }
7091 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
7092 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
7093 read_coeffs(
7094 dec,
7095 &mut luma_coding,
7096 &scan32,
7097 0,
7098 dc_sign_ctx(around[0].2),
7099 TxType::DctDct,
7100 Some((bw, bh)),
7101 )?
7102 } else {
7103 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
7104 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
7105 // (`scan.c`) gives both the very same `default_scan_32x16` /
7106 // `default_scan_16x32` the 2:1 sizes use ("Half of the
7107 // coefficients of tx64 at higher frequencies are set to zeros. So
7108 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
7109 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
7110 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
7111 // 512-position eob group) -- BOTH identical to TX_32X16, so the
7112 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
7113 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
7114 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
7115 // what `base_ctx_rect` computes at (32, 16).
7116 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
7117 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
7118 read_coeffs_rect(
7119 dec,
7120 &mut luma_coding,
7121 luma_scan,
7122 luma_cw,
7123 luma_ch,
7124 0,
7125 dc_sign_ctx(around[0].2),
7126 TxType::DctDct,
7127 )?
7128 };
7129 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7130 let (rng, _) = dec.debug_state();
7131 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
7132 }
7133 let mut luma_levels = vec![0i32; bw * bh];
7134 for row in 0..luma_ch {
7135 luma_levels[row * bw..][..luma_cw]
7136 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
7137 }
7138 {
7139 let cur = block_q_idx();
7140 if cur != i32::from(base_q_idx) {
7141 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
7142 }
7143 if std::env::var_os("EC_AV1_TRACE").is_some() {
7144 eprintln!(
7145 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
7146 );
7147 }
7148 }
7149 let luma_residual = dequant_and_inverse_typed_wh(
7150 &luma_levels,
7151 bw,
7152 bh,
7153 crate::decode::bit_depth(),
7154 block_q_idx(),
7155 plane_q_delta(0).0,
7156 plane_q_delta(0).1,
7157 luma_tx_type,
7158 );
7159 y.reconstruct_rect(
7160 px,
7161 py,
7162 bw,
7163 bh,
7164 mode,
7165 angle_delta_y,
7166 reach,
7167 &luma_residual,
7168 None,
7169 filter_intra,
7170 smooth_neighbor,
7171 );
7172 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
7173 let leftcol: Vec<u16> = if px > 0 {
7174 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
7175 } else {
7176 vec![]
7177 };
7178 eprintln!(
7179 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
7180 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
7181 luma_corner.iter().any(|&v| v != 0),
7182 &y.data[py * y.width + px..][..bw],
7183 leftcol,
7184 );
7185 }
7186 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
7187 // corner crop needed (see doc comment).
7188 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7189 // The chroma plane is never truncated (both axes <= 32 after
7190 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
7191 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
7192 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
7193 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
7194 // set, and only the scan is new (lane-tx64x16).
7195 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
7196 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
7197 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
7198 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
7199 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
7200 };
7201 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
7202 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
7203 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7204 let (rng, _) = dec.debug_state();
7205 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
7206 }
7207 let (u_levels, u_tx_type) = read_coeffs_rect(
7208 dec,
7209 &mut u_coding,
7210 chroma_scan,
7211 chroma_w,
7212 chroma_h,
7213 u_skip_ctx,
7214 dc_sign_ctx(around[1].2),
7215 TxType::DctDct,
7216 )?;
7217 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7218 let (rng, _) = dec.debug_state();
7219 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
7220 }
7221 {
7222 let cur = block_q_idx();
7223 if cur != i32::from(base_q_idx) {
7224 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
7225 }
7226 if std::env::var_os("EC_AV1_TRACE").is_some() {
7227 eprintln!(
7228 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
7229 );
7230 }
7231 }
7232 let u_residual = dequant_and_inverse_typed_wh(
7233 &u_levels,
7234 chroma_w,
7235 chroma_h,
7236 crate::decode::bit_depth(),
7237 block_q_idx(),
7238 plane_q_delta(1).0,
7239 plane_q_delta(1).1,
7240 u_tx_type,
7241 );
7242 u.reconstruct_rect(
7243 cpx,
7244 cpy,
7245 chroma_w,
7246 chroma_h,
7247 uv_predict_mode,
7248 angle_delta_uv,
7249 reach,
7250 &u_residual,
7251 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7252 None,
7253 smooth_neighbor_uv,
7254 );
7255 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
7256 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
7257 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7258 let (rng, _) = dec.debug_state();
7259 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
7260 }
7261 let (v_levels, v_tx_type) = read_coeffs_rect(
7262 dec,
7263 &mut v_coding,
7264 chroma_scan,
7265 chroma_w,
7266 chroma_h,
7267 v_skip_ctx,
7268 dc_sign_ctx(around[2].2),
7269 TxType::DctDct,
7270 )?;
7271 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7272 let (rng, _) = dec.debug_state();
7273 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
7274 }
7275 {
7276 let cur = block_q_idx();
7277 if cur != i32::from(base_q_idx) {
7278 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
7279 }
7280 if std::env::var_os("EC_AV1_TRACE").is_some() {
7281 eprintln!(
7282 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
7283 );
7284 }
7285 }
7286 let v_residual = dequant_and_inverse_typed_wh(
7287 &v_levels,
7288 chroma_w,
7289 chroma_h,
7290 crate::decode::bit_depth(),
7291 block_q_idx(),
7292 plane_q_delta(2).0,
7293 plane_q_delta(2).1,
7294 v_tx_type,
7295 );
7296 v.reconstruct_rect(
7297 cpx,
7298 cpy,
7299 chroma_w,
7300 chroma_h,
7301 uv_predict_mode,
7302 angle_delta_uv,
7303 reach,
7304 &v_residual,
7305 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7306 None,
7307 smooth_neighbor_uv,
7308 );
7309 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
7310 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
7311 }
7312 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
7313 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
7314 let (puv_size, puv_colors) =
7315 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7316 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
7317 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
7318 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
7319 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
7320 match (bw, bh) {
7321 (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)),
7322 (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)),
7323 _ => {}
7324 }
7325 if std::env::var_os("EC_AV1_TRACE").is_some() {
7326 let (rng, _) = dec.debug_state();
7327 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
7328 }
7329 Ok(())
7330}
7331
7332/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
7333/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
7334/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
7335/// it lands away from zero, for gate tests to prove a real stream fired one.
7336fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
7337 let symbol = dec.symbol(cdf);
7338 if symbol != ANGLE_DELTA_ZERO {
7339 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
7340 }
7341 symbol as i32 - ANGLE_DELTA_ZERO as i32
7342}
7343
7344#[allow(clippy::too_many_arguments)]
7345fn read_intra_mode(
7346 dec: &mut SymbolDecoder,
7347 cdfs: &mut Cdfs,
7348 above_mode: usize,
7349 left_mode: usize,
7350 cfl: bool,
7351 side: usize,
7352 enable_filter_intra: bool,
7353 skip_ctx: usize,
7354 allow_screen_content_tools: bool,
7355 allow_intrabc: bool,
7356 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
7357 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
7358 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
7359 // `None` at the excluded call sites (the 8x8-leaf path), which still read
7360 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
7361 // decoder reads either way -- but refuse by name the moment it fires,
7362 // exactly the old behaviour.
7363 palette: Option<(usize, &[u16])>,
7364 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
7365 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
7366 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
7367 // `use_palette_y`, not a neighbour lookup).
7368 palette_uv_cache: &[u16],
7369 mi_r: usize,
7370 mi_c: usize,
7371) -> Result<(
7372 bool,
7373 usize,
7374 i32,
7375 usize,
7376 i32,
7377 Option<(i32, i32)>,
7378 Option<usize>,
7379 Option<PaletteY>,
7380 Option<PaletteUv>,
7381)> {
7382 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
7383 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
7384 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
7385 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
7386 // line against the instrumented aomdec, not just `tell()`.
7387 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
7388 macro_rules! istep {
7389 ($name:literal, $val:expr) => {
7390 if ec_istep {
7391 let (rng, _) = dec.debug_state();
7392 eprintln!(
7393 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
7394 $name, $val
7395 );
7396 }
7397 };
7398 }
7399 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
7400 // `skip` when `SegIdPreSkip`, and after it otherwise.
7401 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
7402 if seg_id_pre_skip() {
7403 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
7404 }
7405 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
7406 if trace {
7407 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
7408 }
7409 istep!("skip", skip as i32);
7410 if !seg_id_pre_skip() {
7411 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
7412 }
7413 // spec order (see the comment below on `read_intrabc_info`): `skip`,
7414 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
7415 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
7416 istep!("cdef", 0);
7417 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, side == 64, skip);
7418 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, side == 64, skip);
7419 istep!("dq", 0);
7420 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
7421 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
7422 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
7423 // intra frame whose header set `allow_intrabc`. Actual intra block copy
7424 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
7425 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
7426 // draws the line at consuming this one flag symbol and refusing by name
7427 // when it fires, so the arithmetic decoder still resyncs for a stream
7428 // that merely allows (but never uses) intrabc.
7429 if allow_intrabc {
7430 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
7431 if trace {
7432 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
7433 }
7434 if use_intrabc {
7435 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
7436 if trace {
7437 eprintln!("TRACE intrabc dv={dv:?}");
7438 }
7439 INTRABC_DV.with(|c| c.set(Some(dv)));
7440 INTRABC_HITS.with(|c| c.set(c.get() + 1));
7441 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
7442 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
7443 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
7444 // `DC_PRED` (which is also what the neighbour mode contexts and
7445 // the loop filter then see).
7446 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
7447 }
7448 }
7449 let above_ctx = INTRA_MODE_CTX[above_mode];
7450 let left_ctx = INTRA_MODE_CTX[left_mode];
7451 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
7452 if trace {
7453 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
7454 }
7455 istep!("mode", mode as i32);
7456 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
7457 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
7458 if trace {
7459 eprintln!(
7460 "TRACE angle_delta value={}",
7461 delta + ANGLE_DELTA_ZERO as i32
7462 );
7463 }
7464 delta
7465 } else {
7466 0
7467 };
7468 istep!("angle_y", angle_delta_y);
7469 let uv_mode = if cfl {
7470 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
7471 } else {
7472 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
7473 };
7474 if trace {
7475 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
7476 }
7477 istep!("uv_mode", uv_mode as i32);
7478 let alpha = if cfl && uv_mode == UV_CFL_PRED {
7479 Some(read_cfl_alphas(dec, cdfs))
7480 } else {
7481 None
7482 };
7483 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
7484 // from this lane's directional chroma: a corner block with neither
7485 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
7486 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
7487 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
7488 // bug in that fallback this lane's own scope does not cover. Keep it
7489 // refused here rather than ship a silently-wrong decode.
7490 if (9..=12).contains(&uv_mode) {
7491 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
7492 }
7493 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
7494 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
7495 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
7496 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
7497 // the `else` branch below and never reads one either way.
7498 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
7499 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
7500 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
7501 } else {
7502 0
7503 };
7504 istep!("angle_uv", angle_delta_uv);
7505 if angle_delta_uv != 0 {
7506 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
7507 }
7508 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
7509 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
7510 // gated by `av1_allow_palette` (blockd.h -- size bound only,
7511 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
7512 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
7513 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
7514 // read the same CDF row whenever every neighbour really is non-palette).
7515 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
7516 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
7517 // neighbour lookup at all), so it is exact even at the excluded call
7518 // sites once Y decodes real syntax there too.
7519 //
7520 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
7521 // inline from `read_palette_mode_info` -- it runs later, from
7522 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
7523 // after the WHOLE mode-info read for the block, including UV palette
7524 // mode_info (`read_palette_mode_info`'s own second half, right below)
7525 // and `read_filter_intra_mode_info`. So this branch now only reads
7526 // mode/size/colours for both planes (deferring the two colour-index-map
7527 // decodes to after `filter_intra`, below) -- r6's range trace pinned
7528 // this exact ordering bug (`compare-range-not-tell`: ranges matched
7529 // bit-for-bit through the Y colours, diverged only at the old inline
7530 // `decode_color_index_map` call).
7531 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
7532 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
7533 if allow_screen_content_tools
7534 && let Some(bsize_ctx) = palette_bsize_ctx(side)
7535 {
7536 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
7537 if mode == DC_PRED {
7538 if trace {
7539 let (rng, _) = dec.debug_state();
7540 eprintln!(
7541 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
7542 );
7543 }
7544 }
7545 let use_palette_y =
7546 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
7547 if mode == DC_PRED && trace {
7548 let (rng, _) = dec.debug_state();
7549 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
7550 }
7551 if use_palette_y {
7552 if palette.is_none() {
7553 return Err(unsupported(
7554 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
7555 ));
7556 }
7557 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
7558 if trace {
7559 let (rng, _) = dec.debug_state();
7560 eprintln!("TRACE palette_y_size n={n} rng={rng}");
7561 }
7562 let colors = read_palette_colors_y(dec, n, cache);
7563 if trace {
7564 let (rng, _) = dec.debug_state();
7565 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
7566 }
7567 palette_y_pending = Some((n, colors));
7568 }
7569 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
7570 // unconditionally at this bit position whenever `uv_mode ==
7571 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
7572 // scope always reconstructs chroma alongside luma (`decode_block`
7573 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
7574 // is always true here and does not need threading in.
7575 let palette_uv_mode_ctx = usize::from(use_palette_y);
7576 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
7577 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
7578 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
7579 palette_uv_pending = Some((n, u_colors, v_colors));
7580 }
7581 }
7582 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
7583 // `use_filter_intra` symbol this decoder never read at all until
7584 // lane-av1real r10 -- silently skipping it left every bit past a
7585 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
7586 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
7587 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
7588 // symbol's bits were never consumed).
7589 let mut filter_intra = None;
7590 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
7591 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
7592 // `use_filter_intra` symbol for a Y-palette block, and reading one here
7593 // desynced every screen-content stream from the first palette block on
7594 // (it surfaced as a bogus "partition below 8x8" refusal further down the
7595 // tile).
7596 if mode == DC_PRED
7597 && enable_filter_intra
7598 && palette_y_pending.is_none()
7599 && let Some(class) = filter_intra_size_class(side)
7600 {
7601 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
7602 if trace {
7603 eprintln!(
7604 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
7605 use_filter_intra as i32
7606 );
7607 }
7608 istep!("use_filter_intra", use_filter_intra as i32);
7609 if use_filter_intra {
7610 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
7611 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
7612 if trace {
7613 eprintln!("TRACE filter_intra_mode value={fi_mode}");
7614 }
7615 istep!("filter_intra_mode", fi_mode as i32);
7616 filter_intra = Some(fi_mode);
7617 }
7618 }
7619 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
7620 // shared U/V map) -- the same order libaom's own loop visits them in.
7621 let palette_y = palette_y_pending.map(|(n, colors)| {
7622 let map = decode_color_index_map(dec, cdfs, n, side, false);
7623 PALETTE_HITS.with(|c| c.set(c.get() + 1));
7624 if trace {
7625 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
7626 }
7627 PaletteY { size: n, colors, map }
7628 });
7629 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
7630 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
7631 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
7632 if trace {
7633 eprintln!(
7634 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
7635 &u_colors[..n],
7636 &v_colors[..n]
7637 );
7638 }
7639 PaletteUv { size: n, u_colors, v_colors, map }
7640 });
7641 Ok((
7642 skip,
7643 mode,
7644 angle_delta_y,
7645 uv_mode,
7646 angle_delta_uv,
7647 alpha,
7648 filter_intra,
7649 palette_y,
7650 palette_uv,
7651 ))
7652}
7653
7654/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
7655/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
7656/// intra modes.
7657const UV_CFL_PRED: usize = 13;
7658
7659/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
7660/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
7661/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
7662/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
7663/// joint sign the same way. Returns each plane's final signed `alpha_q3`
7664/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
7665fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
7666 CFL_BLOCK_HITS.with(|c| c.set(c.get() + 1));
7667 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
7668 let sign_u = ((joint_sign + 1) * 11) >> 5;
7669 let sign_v = (joint_sign + 1) - 3 * sign_u;
7670 let alpha_u = if sign_u == 0 {
7671 0
7672 } else {
7673 let ctx_u = (joint_sign + 1 - 3) as usize;
7674 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
7675 if sign_u == 2 { mag } else { -mag }
7676 };
7677 let alpha_v = if sign_v == 0 {
7678 0
7679 } else {
7680 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
7681 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
7682 if sign_v == 2 { mag } else { -mag }
7683 };
7684 (alpha_u, alpha_v)
7685}
7686
7687/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
7688/// the reconstructed luma samples under a `side`-square block, subsampled
7689/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
7690/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
7691/// to give the AC values [`cfl_scaled`] scales by alpha.
7692fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
7693 let cside = side / 2;
7694 let mut ac = vec![0i32; cside * cside];
7695 let mut sum = 0i32;
7696 for cy in 0..cside {
7697 for cx in 0..cside {
7698 let (lx, ly) = (px + cx * 2, py + cy * 2);
7699 let q3 = (i32::from(y.data[ly * y.width + lx])
7700 + i32::from(y.data[ly * y.width + lx + 1])
7701 + i32::from(y.data[(ly + 1) * y.width + lx])
7702 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
7703 << 1;
7704 ac[cy * cside + cx] = q3;
7705 sum += q3;
7706 }
7707 }
7708 let num_pel = (cside * cside) as i32;
7709 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
7710 ac.iter_mut().for_each(|v| *v -= avg);
7711 ac
7712}
7713
7714/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
7715/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
7716/// ties away from zero on the shifted-out sign).
7717fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
7718 let v = alpha_q3 * ac_q3;
7719 if v >= 0 {
7720 (v + 32) >> 6
7721 } else {
7722 -((-v + 32) >> 6)
7723 }
7724}
7725
7726/// One plane's reconstruction buffer, `width * height` samples, and the
7727/// prediction/residual reads and writes into it — the decode-side twin of
7728/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
7729/// (own-edge and reach clamps both), passing what it gathers straight to
7730/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
7731/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
7732/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
7733fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
7734 use std::io::Write;
7735 if let Ok(path) = std::env::var(var)
7736 && let Ok(mut f) = std::fs::File::create(format!("{path}.f0"))
7737 {
7738 for p in [y, u, v] {
7739 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
7740 let _ = f.write_all(&narrow);
7741 }
7742 }
7743}
7744
7745#[derive(Clone)]
7746struct PlaneBuf {
7747 data: Vec<u16>,
7748 width: usize,
7749 height: usize,
7750 /// The frame's true, decodable extent in this plane's own units — past
7751 /// this, samples are the padded coding surface's invented tail, never a
7752 /// real decoder's edge or reach reads.
7753 true_width: usize,
7754 true_height: usize,
7755 /// This plane's own tile's top-left pixel origin (spec: intra prediction
7756 /// never reaches across a tile boundary even though an earlier-decoded
7757 /// tile's real pixels sit right there in the shared buffer) — set via
7758 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
7759 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
7760 /// is threaded (the two-tile column-split stage 1 fixture's tile always
7761 /// ends at the frame's own right/bottom edge); a non-last tile's own
7762 /// right/bottom reach bound is still open, tracked in the report.
7763 tile_x0: usize,
7764 tile_y0: usize,
7765 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
7766 /// (exclusive) -- a non-last tile column/row's own reach must stop at
7767 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
7768 /// full padded extent) for the single-tile/last-tile case, matching the
7769 /// old unclipped behaviour exactly.
7770 tile_x1: usize,
7771 tile_y1: usize,
7772}
7773
7774/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
7775/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
7776/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
7777/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
7778/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
7779/// `ALTREF2`/`ALTREF`).
7780type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
7781
7782impl PlaneBuf {
7783 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
7784 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
7785 /// are already in this plane's own units (luma pixels for `y`, chroma
7786 /// pixels — halved — for `u`/`v`).
7787 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
7788 self.tile_x0 = x0;
7789 self.tile_y0 = y0;
7790 self.tile_x1 = x1;
7791 self.tile_y1 = y1;
7792 }
7793
7794 fn edges(
7795 &self,
7796 x: usize,
7797 y: usize,
7798 side: usize,
7799 reach: Reach,
7800 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
7801 let own_across = x + side.min(self.true_width.saturating_sub(x));
7802 let across = if reach.above_right {
7803 own_across + side.min(self.true_width.saturating_sub(own_across))
7804 } else {
7805 own_across
7806 }
7807 .min(self.width)
7808 .min(self.tile_x1);
7809 let own_down = y + side.min(self.true_height.saturating_sub(y));
7810 let down = if reach.below_left {
7811 own_down + side.min(self.true_height.saturating_sub(own_down))
7812 } else {
7813 own_down
7814 }
7815 .min(self.height)
7816 .min(self.tile_y1);
7817 let above = (y > self.tile_y0 && across > x)
7818 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
7819 let left = (x > self.tile_x0 && down > y).then(|| {
7820 (y..down)
7821 .map(|row| self.data[row * self.width + x - 1])
7822 .collect::<Vec<_>>()
7823 });
7824 let corner =
7825 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
7826 (above, left, corner)
7827 }
7828
7829 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
7830 /// the above/left reach each extend by their OWN axis (`bw` across,
7831 /// `bh` down), not one shared `side`.
7832 fn edges_rect(
7833 &self,
7834 x: usize,
7835 y: usize,
7836 bw: usize,
7837 bh: usize,
7838 reach: Reach,
7839 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
7840 let own_across = x + bw.min(self.true_width.saturating_sub(x));
7841 let across = if reach.above_right {
7842 own_across + bw.min(self.true_width.saturating_sub(own_across))
7843 } else {
7844 own_across
7845 }
7846 .min(self.width)
7847 .min(self.tile_x1);
7848 let own_down = y + bh.min(self.true_height.saturating_sub(y));
7849 let down = if reach.below_left {
7850 own_down + bh.min(self.true_height.saturating_sub(own_down))
7851 } else {
7852 own_down
7853 }
7854 .min(self.height)
7855 .min(self.tile_y1);
7856 let above = (y > self.tile_y0 && across > x)
7857 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
7858 let left = (x > self.tile_x0 && down > y).then(|| {
7859 (y..down)
7860 .map(|row| self.data[row * self.width + x - 1])
7861 .collect::<Vec<_>>()
7862 });
7863 let corner =
7864 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
7865 if matches!((bw, bh), (16, 8) | (8, 16)) {
7866 RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1));
7867 if across > own_across || down > own_down {
7868 RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1));
7869 }
7870 }
7871 (above, left, corner)
7872 }
7873
7874 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
7875 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
7876 /// already-rect-capable `(bw, bh)` pair.
7877 #[allow(clippy::too_many_arguments)]
7878 fn reconstruct_rect(
7879 &mut self,
7880 x: usize,
7881 y: usize,
7882 bw: usize,
7883 bh: usize,
7884 mode: usize,
7885 angle_delta: i32,
7886 reach: Reach,
7887 residual: &[i32],
7888 cfl: Option<(i32, &[i32])>,
7889 filter_intra: Option<usize>,
7890 smooth_neighbor: bool,
7891 ) {
7892 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
7893 // (lane-palette2 r4): a palette block's prediction is the
7894 // reconstructed colour-index map, needing no edge pixels at all.
7895 let prediction = if let Some(buf) = take_palette_pred() {
7896 buf
7897 } else {
7898 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
7899 if std::env::var_os("EC_DEBUG_EDGES").is_some() {
7900 eprintln!(
7901 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
7902 above.as_ref().map(|a| (a.len(), a[0])),
7903 left.as_ref().map(|l| l.len()),
7904 left.as_ref().map(|l| l[0]),
7905 self.tile_x0, self.tile_y0, self.true_width, self.true_height
7906 );
7907 }
7908 let mut prediction = vec![0u16; bw * bh];
7909 if let Some(fi_mode) = filter_intra {
7910 crate::intra::predict_filter_intra(
7911 fi_mode,
7912 above.as_deref(),
7913 left.as_deref(),
7914 corner,
7915 bw,
7916 bh,
7917 &mut prediction,
7918 );
7919 } else {
7920 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
7921 predict(
7922 mode as u8,
7923 angle_delta,
7924 above.as_deref(),
7925 left.as_deref(),
7926 corner,
7927 bw,
7928 bh,
7929 enable_edge_filter,
7930 smooth_neighbor,
7931 &mut prediction,
7932 );
7933 }
7934 prediction
7935 };
7936 for row in 0..bh {
7937 for col in 0..bw {
7938 let idx = row * bw + col;
7939 let mut base = i32::from(prediction[idx]);
7940 if let Some((alpha_q3, ac_q3)) = cfl {
7941 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
7942 }
7943 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
7944 self.data[(y + row) * self.width + x + col] = sample;
7945 }
7946 }
7947 }
7948
7949 /// Predicts under `mode` then adds `residual` (side*side, raster),
7950 /// writing the clamped reconstruction back into the plane at `(x, y)`.
7951 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
7952 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
7953 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
7954 /// order (cfl.c).
7955 fn reconstruct(
7956 &mut self,
7957 x: usize,
7958 y: usize,
7959 side: usize,
7960 mode: usize,
7961 angle_delta: i32,
7962 reach: Reach,
7963 residual: &[i32],
7964 cfl: Option<(i32, &[i32])>,
7965 filter_intra: Option<usize>,
7966 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
7967 // libaom `get_filt_type`): true when the block's above OR left
7968 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
7969 // Callers pass their own plane's neighbour-mode check
7970 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
7971 // callers until a smooth/paeth `uv_mode` can reach this call at all
7972 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
7973 // keeps `false` exact for chroma without this fn needing to know why.
7974 smooth_neighbor: bool,
7975 ) {
7976 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
7977 // takes priority over `predict()`/`predict_filter_intra` entirely --
7978 // palette prediction needs no edge pixels at all.
7979 let prediction = if let Some(buf) = take_palette_pred() {
7980 buf
7981 } else {
7982 let (above, left, corner) = self.edges(x, y, side, reach);
7983 let mut prediction = vec![0u16; side * side];
7984 if let Some(fi_mode) = filter_intra {
7985 crate::intra::predict_filter_intra(
7986 fi_mode,
7987 above.as_deref(),
7988 left.as_deref(),
7989 corner,
7990 side,
7991 side,
7992 &mut prediction,
7993 );
7994 } else {
7995 // `enable_intra_edge_filter` is the sequence header's own flag
7996 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
7997 // call, never per-block) -- threading it through every
7998 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
7999 // dozen sites for a value that never changes mid-decode, so it
8000 // rides a thread-local instead (this decoder is single-threaded
8001 // per stream).
8002 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
8003 predict(
8004 mode as u8,
8005 angle_delta,
8006 above.as_deref(),
8007 left.as_deref(),
8008 corner,
8009 side,
8010 side,
8011 enable_edge_filter,
8012 smooth_neighbor,
8013 &mut prediction,
8014 );
8015 }
8016 prediction
8017 };
8018 for row in 0..side {
8019 for col in 0..side {
8020 let idx = row * side + col;
8021 let mut base = i32::from(prediction[idx]);
8022 if let Some((alpha_q3, ac_q3)) = cfl {
8023 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
8024 }
8025 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
8026 self.data[(y + row) * self.width + x + col] = sample;
8027 }
8028 }
8029 }
8030}
8031
8032/// Reads one plane's transform block, reconstructs it into `plane` at
8033/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
8034#[allow(clippy::too_many_arguments)]
8035fn read_plane(
8036 dec: &mut SymbolDecoder,
8037 cdfs: &mut Cdfs,
8038 set: TxbSet,
8039 scan: &[u16],
8040 plane_idx: usize,
8041 around: (bool, bool, i32),
8042 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
8043 // it for every plane's `txb` lookup (it is what an intra transform type's
8044 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
8045 tx_mode: usize,
8046 predict_mode: usize,
8047 angle_delta: i32,
8048 reach: Reach,
8049 plane: &mut PlaneBuf,
8050 x: usize,
8051 y: usize,
8052 side: usize,
8053 tx_side: usize,
8054 base_q_idx: u8,
8055 cfl: Option<(i32, &[i32])>,
8056 filter_intra: Option<usize>,
8057 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
8058 // smaller than its own block (spec `get_txb_ctx_general`'s
8059 // `plane_bsize != tx_size` branch), carrying the already-looked-up
8060 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
8061 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
8062 // formula below.
8063 luma_skip_ctx: Option<usize>,
8064 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
8065 smooth_neighbor: bool,
8066) -> Result<Vec<i32>> {
8067 let skip_ctx = if plane_idx == 0 {
8068 luma_skip_ctx.unwrap_or(0)
8069 } else {
8070 usize::from(around.0) + usize::from(around.1)
8071 };
8072 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
8073 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
8074 // not by the block's ordinary `mode` (which is always DC_PRED whenever
8075 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
8076 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
8077 // filter-intra in AV1).
8078 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
8079 let mut coding = cdfs.txb(set, tx_mode);
8080 // Luma's `default_tx_type` is only a fallback for the sizes whose
8081 // `TxbSet` carries no symbol at all (32-point and up), which the spec
8082 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
8083 // *never* its own coded symbol (`coding.tx_type` is always `None` for
8084 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
8085 // the plane's own predicted mode (`default_intra_tx_type`) -- except
8086 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
8087 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
8088 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
8089 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
8090 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
8091 // narrows there — only `Chroma32` and up do).
8092 let default_tx_type = if plane_idx == 0 || side >= 32 {
8093 TxType::DctDct
8094 } else {
8095 default_intra_tx_type(predict_mode as u8)
8096 };
8097 let (grid, tx_type) = read_coeffs(
8098 dec,
8099 &mut coding,
8100 scan,
8101 skip_ctx,
8102 dc_sign_ctx(around.2),
8103 default_tx_type,
8104 None,
8105 )?;
8106 note_chroma_class1(plane_idx, tx_type);
8107 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
8108 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
8109 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
8110 // guard also assumes.
8111 let levels = if tx_side == side {
8112 grid
8113 } else {
8114 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
8115 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
8116 // keyed by that true size, not the coded corner's -- so the corner
8117 // goes into the top-left of a `side`-sized grid, not the reverse.
8118 let mut full = vec![0i32; side * side];
8119 for row in 0..tx_side {
8120 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
8121 }
8122 full
8123 };
8124 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
8125 let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
8126 if std::env::var_os("EC_AV1_TRACE").is_some() {
8127 eprintln!(
8128 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
8129 );
8130 }
8131 plane.reconstruct(
8132 x,
8133 y,
8134 side,
8135 predict_mode,
8136 angle_delta,
8137 reach,
8138 &residual,
8139 cfl,
8140 filter_intra,
8141 smooth_neighbor,
8142 );
8143 Ok(if tx_side == side {
8144 residual_grid_placeholder(&levels, side)
8145 } else {
8146 levels
8147 })
8148}
8149
8150/// `record`'s neighbour state only reads whether *the coded grid* (not the
8151/// residual) has nonzero entries, so the levels this function already built
8152/// are what it wants back; this helper exists only to name that clearly at
8153/// the one call site where `tx_side == side`.
8154fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
8155 levels.to_vec()
8156}
8157
8158/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
8159/// three planes, reconstructing them into `y`/`u`/`v` and updating
8160/// `neighbours`.
8161#[allow(clippy::too_many_arguments)]
8162fn decode_block(
8163 dec: &mut SymbolDecoder,
8164 cdfs: &mut Cdfs,
8165 neighbours: &mut Neighbours,
8166 at: (usize, usize),
8167 side: usize,
8168 luma_set: TxbSet,
8169 chroma_set: TxbSet,
8170 luma_tx: usize,
8171 chroma_tx: usize,
8172 scans: (&[u16], &[u16]),
8173 cfl: bool,
8174 y: &mut PlaneBuf,
8175 u: &mut PlaneBuf,
8176 v: &mut PlaneBuf,
8177 base_q_idx: u8,
8178 enable_filter_intra: bool,
8179 allow_screen_content_tools: bool,
8180 allow_intrabc: bool,
8181 scan32: &[u16],
8182 scan16: &[u16],
8183 scan8: &[u16],
8184 scan4: &[u16],
8185 tx_select: bool,
8186 reduced_tx_set: bool,
8187) -> Result<()> {
8188 let (r, c) = at;
8189 let (px, py) = (c * SUB, r * SUB);
8190 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
8191 let palette_uv_cache = neighbours.palette_uv_cache(at);
8192 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
8193 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
8194 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
8195 read_intra_mode(
8196 dec,
8197 cdfs,
8198 nb_above_mode,
8199 nb_left_mode,
8200 cfl,
8201 side,
8202 enable_filter_intra,
8203 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
8204 allow_screen_content_tools,
8205 allow_intrabc,
8206 Some((palette_ctx, &palette_cache)),
8207 &palette_uv_cache,
8208 r * (SUB / MI),
8209 c * (SUB / MI),
8210 )?;
8211 if at_tile_left && palette_y.is_some() {
8212 PALETTE_TILE_LEFT_HITS.with(|c| c.set(c.get() + 1));
8213 }
8214 let intrabc_dv = INTRABC_DV.with(|c| c.take());
8215 // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
8216 // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
8217 // partition tree (`read_var_tx_size`), a syntax element this decoder has
8218 // nowhere -- reading the intra `tx_depth` symbol instead would desync.
8219 if intrabc_dv.is_some() && tx_select && !skip {
8220 return Err(unsupported(
8221 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
8222 ));
8223 }
8224 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
8225 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
8226 // actual chroma-from-luma correlation, same as this decoder always did.
8227 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8228 DC_PRED
8229 } else {
8230 uv_mode
8231 };
8232 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
8233 if smooth_neighbor {
8234 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8235 }
8236 let smooth_neighbor_uv =
8237 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
8238 if std::env::var_os("EC_AV1_TRACE").is_some() {
8239 eprintln!(
8240 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
8241 angle_delta_uv={angle_delta_uv}"
8242 );
8243 }
8244 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8245 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
8246 // block, skipped or not. `logical_tx` is what the loop filter's edge
8247 // lookup and the next block's own `tx_size_context` want (the *nominal*
8248 // transform size -- 64 even for the 64x64 corner-scanned case, spec
8249 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
8250 // which only differs from it at that one corner case.
8251 let (logical_tx, coeff_tx_side) = if tx_select {
8252 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
8253 (resolved, if resolved == 64 { 32 } else { resolved })
8254 } else {
8255 (side, luma_tx)
8256 };
8257 if tx_select && logical_tx < side && uv_mode != DC_PRED {
8258 SQ_CHROMA_TX_HITS.with(|c| c.set(c.get() + 1));
8259 }
8260 let luma_set = if tx_select {
8261 txbset_for(logical_tx, reduced_tx_set)
8262 } else {
8263 luma_set
8264 };
8265 let luma_set = if intrabc_dv.is_some() {
8266 txbset_for_inter(logical_tx, reduced_tx_set)
8267 } else {
8268 luma_set
8269 };
8270 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
8271 let reach = Reach::of(side, px, py, y.width, y.height);
8272 let (cpx, cpy) = (px / 2, py / 2);
8273 let chroma_side = side / 2;
8274 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
8275 // frame's own pre-loop-filter reconstruction (all loop filters are off
8276 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
8277 // block vector, with the BILINEAR kernel libaom forces for intrabc --
8278 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
8279 // odd, which is exactly what the bilinear taps then interpolate.
8280 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
8281 let mut yb = vec![0u16; side * side];
8282 mc::predict_with_filter(
8283 &y.data, y.width, y.true_width, y.true_height,
8284 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
8285 side, side, mc::InterpFilterKind::Bilinear, &mut yb,
8286 );
8287 let mut ub = vec![0u16; chroma_side * chroma_side];
8288 mc::predict_with_filter(
8289 &u.data, u.width, u.true_width, u.true_height,
8290 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
8291 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
8292 );
8293 let mut vb = vec![0u16; chroma_side * chroma_side];
8294 mc::predict_with_filter(
8295 &v.data, v.width, v.true_width, v.true_height,
8296 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
8297 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
8298 );
8299 (yb, ub, vb)
8300 });
8301 if let Some((yb, _, _)) = &intrabc_bufs {
8302 set_palette_pred(yb.clone());
8303 }
8304 // A palette-Y block's own prediction is the reconstructed colour-index
8305 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
8306 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
8307 // parameter through this function's dozen `y.reconstruct`/`read_plane`
8308 // sites. A split luma transform (`tx_select && logical_tx != side`)
8309 // would need the map sliced per-TU -- untested against a real
8310 // `--enable-palette=1` stream this round, so refuse by name rather than
8311 // guess at the slicing (charter's own named-acceptable fallback).
8312 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
8313 py.map
8314 .iter()
8315 .map(|&idx| py.colors[idx as usize])
8316 .collect()
8317 });
8318 // With one luma transform unit the whole `side`x`side` map is the
8319 // prediction; with several (`logical_tx != side`) each unit takes its own
8320 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
8321 // below (lane-palette2 r7) -- setting the full-block buffer here would be
8322 // taken by the FIRST unit and indexed at the wrong stride.
8323 if let Some(buf) = &palette_y_buf
8324 && logical_tx == side
8325 {
8326 set_palette_pred(buf.clone());
8327 }
8328 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
8329 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
8330 // plane's own `reconstruct`/`read_plane` call below (never both planes at
8331 // once), since Y's own set-then-take already emptied the slot by the time
8332 // either of these run.
8333 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
8334 (
8335 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
8336 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
8337 )
8338 });
8339 // The chroma half of the intrabc prediction rides the same per-plane
8340 // override slot the UV-palette buffers do (set fresh before each plane's
8341 // own `reconstruct`/`read_plane` call below).
8342 let palette_uv_bufs = match &intrabc_bufs {
8343 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
8344 None => palette_uv_bufs,
8345 };
8346 if skip {
8347 // A skipped block codes no residual syntax at all (spec 5.11.34):
8348 // straight prediction, on every plane.
8349 y.reconstruct(
8350 px,
8351 py,
8352 side,
8353 mode,
8354 angle_delta_y,
8355 reach,
8356 &vec![0i32; side * side],
8357 None,
8358 filter_intra,
8359 smooth_neighbor,
8360 );
8361 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8362 if let Some((ub, _)) = &palette_uv_bufs {
8363 set_palette_pred(ub.clone());
8364 }
8365 u.reconstruct(
8366 cpx,
8367 cpy,
8368 chroma_side,
8369 uv_predict_mode,
8370 angle_delta_uv,
8371 reach,
8372 &vec![0i32; chroma_side * chroma_side],
8373 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8374 None,
8375 smooth_neighbor_uv,
8376 );
8377 if let Some((_, vb)) = &palette_uv_bufs {
8378 set_palette_pred(vb.clone());
8379 }
8380 v.reconstruct(
8381 cpx,
8382 cpy,
8383 chroma_side,
8384 uv_predict_mode,
8385 angle_delta_uv,
8386 reach,
8387 &vec![0i32; chroma_side * chroma_side],
8388 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8389 None,
8390 smooth_neighbor_uv,
8391 );
8392 let luma_grid = vec![0i32; side * side];
8393 let u_grid = vec![0i32; chroma_side * chroma_side];
8394 let v_grid = vec![0i32; chroma_side * chroma_side];
8395 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
8396 } else if !tx_select || logical_tx == side {
8397 // A single luma transform unit -- the old path, unchanged (including
8398 // the 64x64 corner case, `logical_tx == side == 64` with
8399 // `coeff_tx_side == 32`).
8400 let around = neighbours.around(at, side);
8401 let luma_grid = read_plane(
8402 dec,
8403 cdfs,
8404 luma_set,
8405 luma_scan,
8406 0,
8407 around[0],
8408 mode,
8409 mode,
8410 angle_delta_y,
8411 reach,
8412 y,
8413 px,
8414 py,
8415 side,
8416 coeff_tx_side,
8417 base_q_idx,
8418 None,
8419 filter_intra,
8420 None,
8421 smooth_neighbor,
8422 )?;
8423 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8424 if let Some((ub, _)) = &palette_uv_bufs {
8425 set_palette_pred(ub.clone());
8426 }
8427 let u_grid = read_plane(
8428 dec,
8429 cdfs,
8430 chroma_set,
8431 scans.1,
8432 1,
8433 around[1],
8434 mode,
8435 uv_predict_mode,
8436 angle_delta_uv,
8437 reach,
8438 u,
8439 cpx,
8440 cpy,
8441 chroma_side,
8442 chroma_tx,
8443 base_q_idx,
8444 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8445 None,
8446 None,
8447 smooth_neighbor_uv,
8448 )?;
8449 if std::env::var_os("EC_AV1_TRACE").is_some() {
8450 eprintln!(
8451 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
8452 &u.data[cpy * u.width + cpx..][..chroma_side]
8453 );
8454 }
8455 if let Some((_, vb)) = &palette_uv_bufs {
8456 set_palette_pred(vb.clone());
8457 }
8458 let v_grid = read_plane(
8459 dec,
8460 cdfs,
8461 chroma_set,
8462 scans.1,
8463 2,
8464 around[2],
8465 mode,
8466 uv_predict_mode,
8467 angle_delta_uv,
8468 reach,
8469 v,
8470 cpx,
8471 cpy,
8472 chroma_side,
8473 chroma_tx,
8474 base_q_idx,
8475 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8476 None,
8477 None,
8478 smooth_neighbor_uv,
8479 )?;
8480 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
8481 } else {
8482 // Several luma transform units, raster order (spec
8483 // `transform_block`'s loop): the block's resolved transform is
8484 // genuinely smaller than its own side, so each tile of it predicts
8485 // and codes independently, its own context read fresh off whatever
8486 // the earlier tiles in this same block already wrote -- the same
8487 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
8488 let n_axis = side / logical_tx;
8489 for tu_row in 0..n_axis {
8490 for tu_col in 0..n_axis {
8491 let tu_mi = (
8492 mi_r + tu_row * (logical_tx / MI),
8493 mi_c + tu_col * (logical_tx / MI),
8494 );
8495 let tu_px = px + tu_col * logical_tx;
8496 let tu_py = py + tu_row * logical_tx;
8497 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
8498 // A transform unit inside a block is NOT a block at that
8499 // position (lane-palette2 r12): `Reach::of` granted the
8500 // top-right 8x8 unit of a 16x16 D203 block bottom-left
8501 // pixels libaom refuses outright (`col_off > 0`), which is
8502 // the diagonal wedge seed 46 reconstructed wrong.
8503 let tu_reach = tu_reach(
8504 side,
8505 side,
8506 tu_col * logical_tx,
8507 tu_row * logical_tx,
8508 logical_tx,
8509 reach,
8510 px,
8511 py,
8512 y.width,
8513 y.height,
8514 );
8515 // This transform unit's own bsize (`logical_tx`) is smaller
8516 // than the block it sits in (`side`), so `txb_skip_ctx` is
8517 // the neighbour-magnitude table, not the lone-TU 0 (spec
8518 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
8519 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
8520 if let Some(buf) = &palette_y_buf {
8521 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8522 let mut window = vec![0u16; logical_tx * logical_tx];
8523 for row in 0..logical_tx {
8524 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
8525 window[row * logical_tx..][..logical_tx]
8526 .copy_from_slice(&buf[src..][..logical_tx]);
8527 }
8528 set_palette_pred(window);
8529 }
8530 let tu_grid = read_plane(
8531 dec,
8532 cdfs,
8533 luma_set,
8534 luma_scan,
8535 0,
8536 tu_around,
8537 mode,
8538 mode,
8539 angle_delta_y,
8540 tu_reach,
8541 y,
8542 tu_px,
8543 tu_py,
8544 logical_tx,
8545 logical_tx,
8546 base_q_idx,
8547 None,
8548 filter_intra,
8549 Some(tu_skip_ctx),
8550 smooth_neighbor,
8551 )?;
8552 if std::env::var_os("EC_AV1_TRACE").is_some() {
8553 eprintln!(
8554 "TRACE tu_bitpos mi=({},{}) tell={}",
8555 tu_mi.0,
8556 tu_mi.1,
8557 dec.debug_bitpos()
8558 );
8559 }
8560 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
8561 }
8562 }
8563 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8564 let chroma_around = neighbours.around(at, side);
8565 if let Some((ub, _)) = &palette_uv_bufs {
8566 set_palette_pred(ub.clone());
8567 }
8568 let u_grid = read_plane(
8569 dec,
8570 cdfs,
8571 chroma_set,
8572 scans.1,
8573 1,
8574 chroma_around[1],
8575 mode,
8576 uv_predict_mode,
8577 angle_delta_uv,
8578 reach,
8579 u,
8580 cpx,
8581 cpy,
8582 chroma_side,
8583 chroma_tx,
8584 base_q_idx,
8585 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8586 None,
8587 None,
8588 smooth_neighbor_uv,
8589 )?;
8590 if let Some((_, vb)) = &palette_uv_bufs {
8591 set_palette_pred(vb.clone());
8592 }
8593 let v_grid = read_plane(
8594 dec,
8595 cdfs,
8596 chroma_set,
8597 scans.1,
8598 2,
8599 chroma_around[2],
8600 mode,
8601 uv_predict_mode,
8602 angle_delta_uv,
8603 reach,
8604 v,
8605 cpx,
8606 cpy,
8607 chroma_side,
8608 chroma_tx,
8609 base_q_idx,
8610 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8611 None,
8612 None,
8613 smooth_neighbor_uv,
8614 )?;
8615 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]);
8616 }
8617 // Unconditional, `size == 0` for a non-palette block: clears any stale
8618 // neighbour palette state the same way [`Neighbours::record`] always
8619 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
8620 // (the split-luma-TU branch above always refuses before reaching here
8621 // when `palette_y` is `Some`, so it is never live for that branch).
8622 let (py_size, py_colors) = palette_y
8623 .as_ref()
8624 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8625 neighbours.record_palette_y(at, side, py_size, py_colors);
8626 let (puv_size, puv_colors) = palette_uv
8627 .as_ref()
8628 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8629 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
8630 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
8631 neighbours.fill_lf_grid(
8632 (r * (SUB / MI), c * (SUB / MI)),
8633 side / MI,
8634 logical_tx as u8,
8635 0,
8636 );
8637 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
8638 Ok(())
8639}
8640
8641/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
8642/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
8643/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
8644/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
8645/// just-decoded mode, not the enclosing slot's stale one, is the true
8646/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
8647/// units, which is what its coefficient context (finer than [`SUB`]) is read
8648/// at. Returns the mode this leaf decoded, for the caller's own
8649/// `prev_leaf`/final mode-writeback bookkeeping.
8650#[allow(clippy::too_many_arguments)]
8651/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
8652/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
8653/// `above_mode[col]`, and its true above neighbour is the mi directly above
8654/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
8655/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
8656/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
8657/// (bottom-right) into both, as this path did, is right only when all four
8658/// leaves happen to share a mode. `done` may be short at the true frame edge
8659/// (the straddle caller filters positions off the frame), so each side falls
8660/// back to the last leaf actually decoded.
8661fn write_back_split_modes(
8662 neighbours: &mut Neighbours,
8663 done: &[((usize, usize), usize)],
8664 parent_mi: (usize, usize),
8665 slot: (usize, usize),
8666) {
8667 let (sr, sc) = slot;
8668 let Some(&(_, last)) = done.last() else {
8669 return;
8670 };
8671 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
8672 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
8673 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
8674}
8675
8676fn decode_leaf8(
8677 dec: &mut SymbolDecoder,
8678 cdfs: &mut Cdfs,
8679 neighbours: &mut Neighbours,
8680 outer_at: (usize, usize),
8681 leaf_mi: (usize, usize),
8682 scans: (&[u16], &[u16]),
8683 prev_leaf: Option<((usize, usize), usize)>,
8684 y: &mut PlaneBuf,
8685 u: &mut PlaneBuf,
8686 v: &mut PlaneBuf,
8687 base_q_idx: u8,
8688 enable_filter_intra: bool,
8689 allow_screen_content_tools: bool,
8690 allow_intrabc: bool,
8691 tx_select: bool,
8692 reduced_tx_set: bool,
8693) -> Result<usize> {
8694 let (r, c) = outer_at;
8695 // lane-modectx r1: the group's own availability-correct fallback pair, not
8696 // the raw coarse bands (which leak across a tile edge -- see
8697 // `modes_above_left`).
8698 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
8699 if let Some(((pr, pc), pmode)) = prev_leaf {
8700 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
8701 above_mode = pmode;
8702 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
8703 left_mode = pmode;
8704 }
8705 }
8706 // The mi-exact neighbour wins over both the coarse 16x16 slot and
8707 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
8708 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
8709 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
8710 // lane-rectsplitx r2 swept this arm into
8711 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
8712 // "no neighbour" at a tile edge, where the coarse cell holds the block
8713 // above/left of it inside the same 16x16.
8714 let (above_mode, left_mode) =
8715 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
8716 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
8717 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
8718 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
8719 // this leaf's `smooth_neighbor` is built from -- passing `false` here
8720 // filtered a directional chroma block's edge at the wrong strength
8721 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
8722 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
8723 // with the coarse [`SUB`] slot as the fallback when no block recorded
8724 // that exact mi cell.
8725 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
8726 if smooth_neighbor {
8727 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8728 }
8729 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
8730 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
8731 // `decode_block` caller at 16x16 and up.
8732 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y, _palette_uv) =
8733 read_intra_mode(
8734 dec,
8735 cdfs,
8736 above_mode,
8737 left_mode,
8738 true,
8739 8,
8740 enable_filter_intra,
8741 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
8742 allow_screen_content_tools,
8743 allow_intrabc,
8744 None,
8745 &[],
8746 leaf_mi.0,
8747 leaf_mi.1,
8748 )?;
8749 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8750 DC_PRED
8751 } else {
8752 uv_mode
8753 };
8754 neighbours.above_uv_mode[c] = uv_predict_mode;
8755 neighbours.left_uv_mode[r] = uv_predict_mode;
8756 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
8757 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
8758 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
8759 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
8760 // transform units, same raster-order per-TU pattern `decode_block`'s
8761 // multi-TU branch runs).
8762 let resolved = if tx_select {
8763 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
8764 } else {
8765 8
8766 };
8767 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8768 let reach = Reach::of(8, px, py, y.width, y.height);
8769 let (cpx, cpy) = (px / 2, py / 2);
8770 let (luma_grid, u_grid, v_grid);
8771 if skip {
8772 y.reconstruct(
8773 px,
8774 py,
8775 8,
8776 mode,
8777 angle_delta_y,
8778 reach,
8779 &vec![0i32; 64],
8780 None,
8781 filter_intra,
8782 smooth_neighbor,
8783 );
8784 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8785 u.reconstruct(
8786 cpx,
8787 cpy,
8788 4,
8789 uv_predict_mode,
8790 angle_delta_uv,
8791 reach,
8792 &vec![0i32; 16],
8793 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8794 None,
8795 smooth_neighbor_uv,
8796 );
8797 v.reconstruct(
8798 cpx,
8799 cpy,
8800 4,
8801 uv_predict_mode,
8802 angle_delta_uv,
8803 reach,
8804 &vec![0i32; 16],
8805 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8806 None,
8807 smooth_neighbor_uv,
8808 );
8809 luma_grid = vec![0i32; 64];
8810 u_grid = vec![0i32; 16];
8811 v_grid = vec![0i32; 16];
8812 } else if resolved != 4 {
8813 let around = neighbours.around_mi(leaf_mi, 8);
8814 luma_grid = read_plane(
8815 dec,
8816 cdfs,
8817 if reduced_tx_set {
8818 TxbSet::Luma8
8819 } else {
8820 TxbSet::Luma8Set1
8821 },
8822 scans.0,
8823 0,
8824 around[0],
8825 mode,
8826 mode,
8827 angle_delta_y,
8828 reach,
8829 y,
8830 px,
8831 py,
8832 8,
8833 TX8,
8834 base_q_idx,
8835 None,
8836 filter_intra,
8837 None,
8838 smooth_neighbor,
8839 )?;
8840 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8841 u_grid = read_plane(
8842 dec,
8843 cdfs,
8844 TxbSet::Chroma4,
8845 scans.1,
8846 1,
8847 around[1],
8848 mode,
8849 uv_predict_mode,
8850 angle_delta_uv,
8851 reach,
8852 u,
8853 cpx,
8854 cpy,
8855 4,
8856 TX4,
8857 base_q_idx,
8858 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8859 None,
8860 None,
8861 smooth_neighbor_uv,
8862 )?;
8863 v_grid = read_plane(
8864 dec,
8865 cdfs,
8866 TxbSet::Chroma4,
8867 scans.1,
8868 2,
8869 around[2],
8870 mode,
8871 uv_predict_mode,
8872 angle_delta_uv,
8873 reach,
8874 v,
8875 cpx,
8876 cpy,
8877 4,
8878 TX4,
8879 base_q_idx,
8880 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8881 None,
8882 None,
8883 smooth_neighbor_uv,
8884 )?;
8885 } else {
8886 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
8887 // grid of 4x4 transform units, each predicted from the leaf's own
8888 // 8x8 `mode` and reading its own fresh context off the earlier
8889 // units in this same leaf (the same per-TU pattern `decode_block`'s
8890 // multi-TU branch runs at bigger blocks).
8891 luma_grid = vec![0i32; 64];
8892 for tu_row in 0..2 {
8893 for tu_col in 0..2 {
8894 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
8895 let tu_px = px + tu_col * 4;
8896 let tu_py = py + tu_row * 4;
8897 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
8898 if crate::encode::Reach::in_vert_ab() {
8899 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));
8900 }
8901 let tu_reach = tu_reach(
8902 8,
8903 8,
8904 tu_col * 4,
8905 tu_row * 4,
8906 4,
8907 reach,
8908 px,
8909 py,
8910 y.width,
8911 y.height,
8912 );
8913 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
8914 let tu_grid = read_plane(
8915 dec,
8916 cdfs,
8917 if reduced_tx_set {
8918 TxbSet::Luma4
8919 } else {
8920 TxbSet::Luma4Set1
8921 },
8922 scans.1,
8923 0,
8924 tu_around,
8925 mode,
8926 mode,
8927 angle_delta_y,
8928 tu_reach,
8929 y,
8930 tu_px,
8931 tu_py,
8932 4,
8933 4,
8934 base_q_idx,
8935 None,
8936 filter_intra,
8937 Some(tu_skip_ctx),
8938 smooth_neighbor,
8939 )?;
8940 if std::env::var_os("EC_AV1_TRACE").is_some() {
8941 eprintln!(
8942 "TRACE tu_bitpos mi=({},{}) tell={}",
8943 tu_mi.0,
8944 tu_mi.1,
8945 dec.debug_bitpos()
8946 );
8947 }
8948 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
8949 }
8950 }
8951 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8952 let chroma_around = neighbours.around_mi(leaf_mi, 8);
8953 u_grid = read_plane(
8954 dec,
8955 cdfs,
8956 TxbSet::Chroma4,
8957 scans.1,
8958 1,
8959 chroma_around[1],
8960 mode,
8961 uv_predict_mode,
8962 angle_delta_uv,
8963 reach,
8964 u,
8965 cpx,
8966 cpy,
8967 4,
8968 TX4,
8969 base_q_idx,
8970 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8971 None,
8972 None,
8973 smooth_neighbor_uv,
8974 )?;
8975 v_grid = read_plane(
8976 dec,
8977 cdfs,
8978 TxbSet::Chroma4,
8979 scans.1,
8980 2,
8981 chroma_around[2],
8982 mode,
8983 uv_predict_mode,
8984 angle_delta_uv,
8985 reach,
8986 v,
8987 cpx,
8988 cpy,
8989 4,
8990 TX4,
8991 base_q_idx,
8992 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8993 None,
8994 None,
8995 smooth_neighbor_uv,
8996 )?;
8997 // `record_split_luma` expects a `record`-style `(r, c)` position in
8998 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
8999 // already in mi units, so calling it here double-scaled the
9000 // position. Plane 0 is already correct per-TU from the
9001 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
9002 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
9003 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
9004 // leaf's own 8x8 side over `MI`).
9005 let side_mi = 2;
9006 for cell in 0..side_mi {
9007 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
9008 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
9009 }
9010 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9011 let bound_h = round_up_even(neighbours.mi_rows);
9012 let bound_w = round_up_even(neighbours.mi_cols);
9013 let u_state = neighbour_state(&u_grid);
9014 let v_state = neighbour_state(&v_grid);
9015 for cell in 0..side_mi {
9016 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
9017 neighbours.left[leaf_mi.0 + cell][1] = u_state;
9018 neighbours.left[leaf_mi.0 + cell][2] = v_state;
9019 }
9020 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
9021 neighbours.above[leaf_mi.1 + cell][1] = u_state;
9022 neighbours.above[leaf_mi.1 + cell][2] = v_state;
9023 }
9024 }
9025 // Non-palette 8x8 leaf (this path never reads a palette): clear the
9026 // above/left palette state over its own cell so the next block's ctx and
9027 // colour cache do not read a previous block's palette (lane-palette2 r8).
9028 {
9029 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
9030 neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
9031 neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
9032 }
9033 neighbours.fill_skip_grid(leaf_mi, 2, skip);
9034 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
9035 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
9036 return Ok(mode);
9037 }
9038 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
9039 // Non-palette 8x8 leaf (this path never reads a palette): clear the
9040 // above/left palette state over its own cell so the next block's ctx and
9041 // colour cache do not read a previous block's palette (lane-palette2 r8).
9042 {
9043 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
9044 neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
9045 neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
9046 }
9047 neighbours.fill_skip_grid(leaf_mi, 2, skip);
9048 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
9049 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
9050 Ok(mode)
9051}
9052
9053/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
9054/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
9055/// bottom, where no partition symbol is read at all -- `decode_block` runs
9056/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
9057/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
9058/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
9059/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
9060/// of the 2x2 4x4 group carries chroma syntax at all.
9061#[allow(clippy::too_many_arguments)]
9062fn read_intra_mode_sub8(
9063 dec: &mut SymbolDecoder,
9064 cdfs: &mut Cdfs,
9065 above_mode: usize,
9066 left_mode: usize,
9067 has_chroma: bool,
9068 enable_filter_intra: bool,
9069 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
9070 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
9071 // from the wrong row is the same VALUE with a different interval, so it
9072 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
9073 fi_class: usize,
9074 skip_ctx: usize,
9075 allow_intrabc: bool,
9076 mi_r: usize,
9077 mi_c: usize,
9078) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
9079 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
9080 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
9081 if trace {
9082 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
9083 }
9084 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
9085 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
9086 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
9087 if allow_intrabc {
9088 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
9089 if use_intrabc {
9090 return Err(unsupported(
9091 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
9092 ));
9093 }
9094 }
9095 let above_ctx = INTRA_MODE_CTX[above_mode];
9096 let left_ctx = INTRA_MODE_CTX[left_mode];
9097 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
9098 if trace {
9099 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
9100 }
9101 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
9102 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
9103 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
9104 // symbol. Reading one consumed a symbol the encoder never wrote and
9105 // desynced the tile at the very next element.
9106 let angle_delta_y = 0;
9107 let chroma = if has_chroma {
9108 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
9109 if trace {
9110 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
9111 }
9112 if (9..=12).contains(&uv_mode) {
9113 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
9114 }
9115 let alpha = if uv_mode == UV_CFL_PRED {
9116 Some(read_cfl_alphas(dec, cdfs))
9117 } else {
9118 None
9119 };
9120 if (V_PRED..=D67_PRED).contains(&uv_mode) {
9121 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
9122 }
9123 // See the luma comment above: no angle delta below 8x8.
9124 let angle_delta_uv = 0;
9125 Some((uv_mode, angle_delta_uv, alpha))
9126 } else {
9127 None
9128 };
9129 let mut filter_intra = None;
9130 if mode == DC_PRED && enable_filter_intra {
9131 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
9132 if trace {
9133 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
9134 }
9135 if use_filter_intra {
9136 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
9137 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
9138 filter_intra = Some(fi_mode);
9139 }
9140 }
9141 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
9142}
9143
9144/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
9145/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
9146/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
9147/// bookkeeping needs no change. Each leaf reads its own luma mode info,
9148/// neighboured off the *previously decoded leaf in this same group* on
9149/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
9150/// pattern, one level deeper); chroma is read and reconstructed exactly
9151/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
9152/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
9153/// derivation.
9154#[allow(clippy::too_many_arguments)]
9155fn decode_leaf_split4(
9156 dec: &mut SymbolDecoder,
9157 cdfs: &mut Cdfs,
9158 neighbours: &mut Neighbours,
9159 outer_at: (usize, usize),
9160 leaf_mi: (usize, usize),
9161 scan4: &[u16],
9162 prev_leaf: Option<((usize, usize), usize)>,
9163 y: &mut PlaneBuf,
9164 u: &mut PlaneBuf,
9165 v: &mut PlaneBuf,
9166 base_q_idx: u8,
9167 enable_filter_intra: bool,
9168 allow_intrabc: bool,
9169 reduced_tx_set: bool,
9170 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
9171 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
9172 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1)).
9173) -> Result<(usize, usize)> {
9174 SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1));
9175 let (r, c) = outer_at;
9176 let mut above_mode = neighbours.above_mode[c];
9177 let mut left_mode = neighbours.left_mode[r];
9178 if let Some(((pr, pc), pmode)) = prev_leaf {
9179 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
9180 above_mode = pmode;
9181 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
9182 left_mode = pmode;
9183 }
9184 }
9185 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
9186 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
9187 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
9188 let mut leaf_modes = [0usize; 4];
9189 let mut leaf_skips = [false; 4];
9190 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
9191 for i in 0..4usize {
9192 let (dr, dc) = (i / 2, i % 2);
9193 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
9194 // Neighbour modes at real mi granularity: inside the group the
9195 // sibling leaf, outside it the split-leaf map when the adjacent mi
9196 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
9197 // `sub8_mode_col`'s doc).
9198 let leaf_above = if dr == 0 {
9199 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
9200 } else {
9201 leaf_modes[i - 2]
9202 };
9203 let leaf_left = if dc == 0 {
9204 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
9205 } else {
9206 leaf_modes[i - 1]
9207 };
9208 let has_chroma = i == 3;
9209 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
9210 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
9211 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
9212 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
9213 skip_ctx, allow_intrabc, lmi.0, lmi.1,
9214 )?;
9215 leaf_modes[i] = mode;
9216 leaf_skips[i] = skip;
9217 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
9218 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
9219 if smooth_neighbor {
9220 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
9221 }
9222 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
9223 let reach = Reach::of(4, px, py, y.width, y.height);
9224 if skip {
9225 y.reconstruct(px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor);
9226 neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]);
9227 } else {
9228 let tu_around = neighbours.around_mi(lmi, 4)[0];
9229 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
9230 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
9231 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
9232 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
9233 // off the wrong CDF on the very first leaf and desynced the tile.
9234 let tu_grid = read_plane(
9235 dec,
9236 cdfs,
9237 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
9238 scan4,
9239 0,
9240 tu_around,
9241 mode,
9242 mode,
9243 angle_delta_y,
9244 reach,
9245 y,
9246 px,
9247 py,
9248 4,
9249 4,
9250 base_q_idx,
9251 None,
9252 filter_intra,
9253 None,
9254 smooth_neighbor,
9255 )?;
9256 neighbours.record_mi_luma(lmi, 4, &tu_grid);
9257 }
9258 neighbours.fill_skip_grid(lmi, 1, skip);
9259 neighbours.fill_lf_grid(lmi, 1, 4, 0);
9260 if has_chroma {
9261 last_uv = chroma;
9262 }
9263 }
9264 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
9265 let (cpx, cpy) = (gpx / 2, gpy / 2);
9266 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
9267 let (uv_mode, angle_delta_uv, alpha) =
9268 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
9269 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
9270 neighbours.above_uv_mode[c] = uv_predict_mode;
9271 neighbours.left_uv_mode[r] = uv_predict_mode;
9272 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
9273 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[3] {
9274 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
9275 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
9276 (vec![0i32; 16], vec![0i32; 16])
9277 } else {
9278 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
9279 let chroma_around = neighbours.around_mi(leaf_mi, 8);
9280 let ug = read_plane(
9281 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
9282 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
9283 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
9284 )?;
9285 let vg = read_plane(
9286 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
9287 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
9288 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
9289 )?;
9290 (ug, vg)
9291 };
9292 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
9293 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
9294 // rescaling is wrong for an already-mi-unit position, so this inlines
9295 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
9296 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
9297 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
9298 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
9299 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
9300 // bottom). libaom's `update_ext_partition_context` writes
9301 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
9302 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
9303 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
9304 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
9305 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
9306 // round's bug) makes the very next sibling 8x8's `partition_w8` read
9307 // with the wrong context and desync immediately.
9308 let side_mi = 2;
9309 for cell in 0..side_mi {
9310 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
9311 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
9312 }
9313 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9314 let bound_h = round_up_even(neighbours.mi_rows);
9315 let bound_w = round_up_even(neighbours.mi_cols);
9316 let u_state = neighbour_state(&u_grid);
9317 let v_state = neighbour_state(&v_grid);
9318 for cell in 0..side_mi {
9319 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
9320 neighbours.left[leaf_mi.0 + cell][1] = u_state;
9321 neighbours.left[leaf_mi.0 + cell][2] = v_state;
9322 }
9323 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
9324 neighbours.above[leaf_mi.1 + cell][1] = u_state;
9325 neighbours.above[leaf_mi.1 + cell][2] = v_state;
9326 }
9327 }
9328 Ok((leaf_modes[2], leaf_modes[1]))
9329}
9330
9331/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
9332/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
9333/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
9334/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
9335/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
9336/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
9337/// every sub-block one mi wide or high but the last) -- differing only where
9338/// the shape does:
9339///
9340/// * the transform is a true `TX_4X8`/`TX_8X4`
9341/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
9342/// `av1_inv_txfm_shift_ls` row already cover this size pair);
9343/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
9344/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
9345/// row -- see that variant's doc comment;
9346/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
9347/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
9348/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
9349/// ([`Reach::of_rect`]);
9350/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
9351/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
9352/// `BLOCK_4X4` split writes.
9353///
9354/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
9355/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
9356/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
9357/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
9358/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
9359/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
9360#[allow(clippy::too_many_arguments)]
9361fn decode_leaf_rect8(
9362 dec: &mut SymbolDecoder,
9363 cdfs: &mut Cdfs,
9364 neighbours: &mut Neighbours,
9365 outer_at: (usize, usize),
9366 leaf_mi: (usize, usize),
9367 vert: bool,
9368 scan4: &[u16],
9369 y: &mut PlaneBuf,
9370 u: &mut PlaneBuf,
9371 v: &mut PlaneBuf,
9372 base_q_idx: u8,
9373 enable_filter_intra: bool,
9374 allow_intrabc: bool,
9375 tx_select: bool,
9376 reduced_tx_set: bool,
9377) -> Result<(usize, usize)> {
9378 let (r, c) = outer_at;
9379 // lane-modectx r1: availability-correct fallback pair (see
9380 // `modes_above_left`), not the raw coarse bands.
9381 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
9382 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
9383 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
9384 let (w_mi, h_mi) = (bw / MI, bh / MI);
9385 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
9386 let mut leaf_modes = [0usize; 2];
9387 let mut leaf_skips = [false; 2];
9388 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
9389 for i in 0..2usize {
9390 let lmi = if vert {
9391 (leaf_mi.0, leaf_mi.1 + i)
9392 } else {
9393 (leaf_mi.0 + i, leaf_mi.1)
9394 };
9395 // Inside the pair the sibling is the neighbour on the split axis;
9396 // outside it the mi-granular map, else the coarse 16x16 slot.
9397 let leaf_above = if !vert && i == 1 {
9398 leaf_modes[0]
9399 } else {
9400 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
9401 };
9402 let leaf_left = if vert && i == 1 {
9403 leaf_modes[0]
9404 } else {
9405 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
9406 };
9407 let has_chroma = i == 1;
9408 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
9409 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
9410 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
9411 filter_intra_size_class_rect(bw, bh)
9412 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
9413 skip_ctx, allow_intrabc, lmi.0, lmi.1,
9414 )?;
9415 if filter_intra.is_some() {
9416 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
9417 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
9418 // same `reconstruct_rect`/`reconstruct` calls below -- and under
9419 // a split transform, per 4x4 unit with that unit's own edge,
9420 // which is exactly what the depth-1 loop already does.
9421 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
9422 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.set(c.get() + 1));
9423 }
9424 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
9425 // leaf too, and is read for every intra block, skipped or not. Its
9426 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
9427 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
9428 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
9429 // `tx_size_cat2` the 32x16 strips read -- with the rect context
9430 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
9431 // Missing this read consumed one symbol fewer than the encoder wrote
9432 // and desynced the tile at the very first rect leaf (class
9433 // `symbol-consumption-gap`).
9434 let depth = if tx_select {
9435 let ctx = tx_size_context_rect(neighbours, lmi, bw, bh);
9436 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
9437 } else {
9438 0
9439 };
9440 if depth != 0 {
9441 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
9442 RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
9443 }
9444 leaf_modes[i] = mode;
9445 leaf_skips[i] = skip;
9446 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
9447 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
9448 if smooth_neighbor {
9449 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
9450 }
9451 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
9452 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9453 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
9454 // two 4x4 transform units along its long axis, each predicted from
9455 // the previous unit's reconstruction and reading its own `txb_skip`
9456 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
9457 // four. The per-TU path writes its own neighbour state, so the
9458 // block-level write below is skipped for it.
9459 let split = depth != 0;
9460 if split {
9461 let mut done = 0usize;
9462 for tu in 0..2usize {
9463 let tu_mi = if vert {
9464 (lmi.0 + tu, lmi.1)
9465 } else {
9466 (lmi.0, lmi.1 + tu)
9467 };
9468 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
9469 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
9470 // Same per-TU rule as every other split-transform site
9471 // (lane-palette2 r12): a transform unit inside a block is not
9472 // a block at that position, so its reach comes from the
9473 // block's own row, offset by the unit's position.
9474 let tu_reach = tu_reach(
9475 bw,
9476 bh,
9477 tu_px - px,
9478 tu_py - py,
9479 4,
9480 reach,
9481 px,
9482 py,
9483 y.width,
9484 y.height,
9485 );
9486 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
9487 if skip {
9488 // A skipped leaf still predicts per transform unit: the
9489 // second 4x4 takes its above/left edge from the first
9490 // one's reconstruction, which is NOT what a single 4x8
9491 // prediction of the same mode produces.
9492 let zeros = vec![0i32; 16];
9493 y.reconstruct(
9494 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
9495 filter_intra, smooth_neighbor,
9496 );
9497 neighbours.record_mi_luma(tu_mi, 4, &zeros);
9498 continue;
9499 }
9500 let tu_grid = read_plane(
9501 dec,
9502 cdfs,
9503 if reduced_tx_set {
9504 TxbSet::Luma4
9505 } else {
9506 TxbSet::Luma4Set1
9507 },
9508 scan4,
9509 0,
9510 tu_around,
9511 mode,
9512 mode,
9513 angle_delta_y,
9514 tu_reach,
9515 y,
9516 tu_px,
9517 tu_py,
9518 4,
9519 TX4,
9520 base_q_idx,
9521 None,
9522 filter_intra,
9523 Some(tu_skip_ctx),
9524 smooth_neighbor,
9525 )?;
9526 if tu_grid.iter().any(|&l| l != 0) {
9527 done += 1;
9528 }
9529 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
9530 }
9531 if done > 0 {
9532 if vert {
9533 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
9534 } else {
9535 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
9536 }
9537 }
9538 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
9539 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0);
9540 if has_chroma {
9541 last_uv = chroma;
9542 }
9543 continue;
9544 }
9545 let grid = if skip {
9546 let zeros = vec![0i32; bw * bh];
9547 y.reconstruct_rect(
9548 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
9549 smooth_neighbor,
9550 );
9551 zeros
9552 } else {
9553 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
9554 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
9555 // at 0 -- see `decode_leaf_split4`'s own note.
9556 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
9557 let set = if reduced_tx_set {
9558 TxbSet::LumaRect4x8
9559 } else {
9560 TxbSet::LumaRect4x8Set1
9561 };
9562 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
9563 let (levels, tx_type) = read_coeffs_rect(
9564 dec,
9565 &mut coding,
9566 scan,
9567 bw,
9568 bh,
9569 0,
9570 dc_sign_ctx(around.2),
9571 TxType::DctDct,
9572 )?;
9573 if levels.iter().any(|&l| l != 0) {
9574 if vert {
9575 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
9576 } else {
9577 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
9578 }
9579 }
9580 let residual = dequant_and_inverse_typed_wh(
9581 &levels,
9582 bw,
9583 bh,
9584 crate::decode::bit_depth(),
9585 CURRENT_Q_IDX.with(|q| q.get()),
9586 plane_q_delta(0).0,
9587 plane_q_delta(0).1,
9588 tx_type,
9589 );
9590 y.reconstruct_rect(
9591 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
9592 smooth_neighbor,
9593 );
9594 levels
9595 };
9596 // Plane 0's per-TU coefficient context over this leaf's own mi span
9597 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
9598 // for the whole 8x8 group below).
9599 let state = neighbour_state(&grid);
9600 for cell in 0..h_mi {
9601 if lmi.0 + cell < neighbours.mi_rows {
9602 neighbours.left[lmi.0 + cell][0] = state;
9603 }
9604 }
9605 for cell in 0..w_mi {
9606 if lmi.1 + cell < neighbours.mi_cols {
9607 neighbours.above[lmi.1 + cell][0] = state;
9608 }
9609 }
9610 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
9611 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
9612 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0);
9613 if has_chroma {
9614 last_uv = chroma;
9615 }
9616 }
9617 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
9618 let (cpx, cpy) = (gpx / 2, gpy / 2);
9619 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
9620 let (uv_mode, angle_delta_uv, alpha) =
9621 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
9622 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
9623 neighbours.above_uv_mode[c] = uv_predict_mode;
9624 neighbours.left_uv_mode[r] = uv_predict_mode;
9625 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
9626 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[1] {
9627 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
9628 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
9629 (vec![0i32; 16], vec![0i32; 16])
9630 } else {
9631 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
9632 let chroma_around = neighbours.around_mi(leaf_mi, 8);
9633 let ug = read_plane(
9634 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
9635 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
9636 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
9637 )?;
9638 let vg = read_plane(
9639 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
9640 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
9641 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
9642 )?;
9643 (ug, vg)
9644 };
9645 // `update_partition_context` at the 8x8 level writes
9646 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
9647 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
9648 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
9649 // `partition_ctx_mi` reads back off these side values.
9650 for cell in 0..2 {
9651 neighbours.above_side_mi[leaf_mi.1 + cell] = bw;
9652 neighbours.left_side_mi[leaf_mi.0 + cell] = bh;
9653 }
9654 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9655 let bound_h = round_up_even(neighbours.mi_rows);
9656 let bound_w = round_up_even(neighbours.mi_cols);
9657 let u_state = neighbour_state(&u_grid);
9658 let v_state = neighbour_state(&v_grid);
9659 for cell in 0..2usize {
9660 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
9661 neighbours.left[leaf_mi.0 + cell][1] = u_state;
9662 neighbours.left[leaf_mi.0 + cell][2] = v_state;
9663 }
9664 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
9665 neighbours.above[leaf_mi.1 + cell][1] = u_state;
9666 neighbours.above[leaf_mi.1 + cell][2] = v_state;
9667 }
9668 }
9669 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
9670 // bottom one (the second under HORZ, the left one under VERT), the one a
9671 // neighbour to the right sees is the top-right (the second under VERT).
9672 Ok(if vert {
9673 (leaf_modes[0], leaf_modes[1])
9674 } else {
9675 (leaf_modes[1], leaf_modes[0])
9676 })
9677}
9678
9679/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
9680/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
9681/// (mod 8) reuse the same table.
9682const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
9683 [(-1, 1), (-2, 2)],
9684 [(0, 1), (-1, 2)],
9685 [(0, 1), (0, 2)],
9686 [(0, 1), (1, 2)],
9687 [(1, 1), (2, 2)],
9688 [(1, 0), (2, 1)],
9689 [(1, 0), (2, 0)],
9690 [(1, 0), (2, -1)],
9691];
9692/// A neighbour tap outside the frame's true extent -- `constrain` reads this
9693/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
9694const CDEF_VERY_LARGE: i32 = 0x4000;
9695const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
9696const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
9697
9698fn cdef_msb(x: i32) -> i32 {
9699 31 - x.leading_zeros() as i32
9700}
9701
9702/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
9703/// centre sample a filter tap is allowed to contribute.
9704fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
9705 if threshold == 0 {
9706 return 0;
9707 }
9708 let shift = (damping - cdef_msb(threshold)).max(0);
9709 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
9710}
9711
9712/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
9713/// direction of an 8x8 luma window and the variance gap between it and its
9714/// orthogonal, `sample(row, col)` reading that window's own pixels.
9715fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
9716 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
9717 let mut partial = [[0i64; 15]; 8];
9718 for i in 0..8i64 {
9719 for j in 0..8i64 {
9720 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
9721 // accumulating, same as `constrain`'s threshold shift below.
9722 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
9723 partial[0][(i + j) as usize] += x;
9724 partial[1][(i + j / 2) as usize] += x;
9725 partial[2][i as usize] += x;
9726 partial[3][(3 + i - j / 2) as usize] += x;
9727 partial[4][(7 + i - j) as usize] += x;
9728 partial[5][(3 - i / 2 + j) as usize] += x;
9729 partial[6][j as usize] += x;
9730 partial[7][(i / 2 + j) as usize] += x;
9731 }
9732 }
9733 let mut cost = [0i64; 8];
9734 for i in 0..8usize {
9735 cost[2] += partial[2][i] * partial[2][i];
9736 cost[6] += partial[6][i] * partial[6][i];
9737 }
9738 cost[2] *= DIV_TABLE[8];
9739 cost[6] *= DIV_TABLE[8];
9740 for i in 0..7usize {
9741 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
9742 * DIV_TABLE[i + 1];
9743 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
9744 * DIV_TABLE[i + 1];
9745 }
9746 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
9747 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
9748 for i in (1..8).step_by(2) {
9749 for j in 0..5usize {
9750 cost[i] += partial[i][3 + j] * partial[i][3 + j];
9751 }
9752 cost[i] *= DIV_TABLE[8];
9753 for j in 0..3usize {
9754 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
9755 * DIV_TABLE[2 * j + 2];
9756 }
9757 }
9758 let mut best_cost = 0i64;
9759 let mut best_dir = 0usize;
9760 for (i, &c) in cost.iter().enumerate() {
9761 if c > best_cost {
9762 best_cost = c;
9763 best_dir = i;
9764 }
9765 }
9766 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
9767 (best_dir, var as i32)
9768}
9769
9770/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
9771/// (high variance gap) gets more deringing than a flat or non-directional
9772/// one, only ever applied to the luma primary strength.
9773fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
9774 if var == 0 {
9775 return 0;
9776 }
9777 let i = if var >> 6 != 0 {
9778 cdef_msb(var >> 6).min(12)
9779 } else {
9780 0
9781 };
9782 (strength * (4 + i) + 8) >> 4
9783}
9784
9785/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
9786/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
9787/// previously-filtered neighbour must never feed this block's own sum).
9788#[allow(clippy::too_many_arguments)]
9789fn cdef_filter_block(
9790 sample: impl Fn(i32, i32) -> i32,
9791 dst: &mut PlaneBuf,
9792 ox: usize,
9793 oy: usize,
9794 bw: usize,
9795 bh: usize,
9796 pri_strength: i32,
9797 sec_strength: i32,
9798 dir: usize,
9799 pri_damping: i32,
9800 sec_damping: i32,
9801 enable_primary: bool,
9802 enable_secondary: bool,
9803 coeff_shift: i32,
9804) {
9805 let clipping_required = enable_primary && enable_secondary;
9806 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
9807 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
9808 // derivative) carries the bit-depth shift, so the tap-set parity bit
9809 // must be read back above that shift, not off the raw low bit.
9810 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
9811 for i in 0..bh {
9812 for j in 0..bw {
9813 let x = sample(i as i32, j as i32);
9814 let mut sum = 0i32;
9815 let mut max = x;
9816 let mut min = x;
9817 for k in 0..2usize {
9818 if enable_primary {
9819 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
9820 let p0 = sample(i as i32 + tr, j as i32 + tc);
9821 let p1 = sample(i as i32 - tr, j as i32 - tc);
9822 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
9823 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
9824 if clipping_required {
9825 if p0 != CDEF_VERY_LARGE {
9826 max = max.max(p0);
9827 }
9828 if p1 != CDEF_VERY_LARGE {
9829 max = max.max(p1);
9830 }
9831 min = min.min(p0).min(p1);
9832 }
9833 }
9834 if enable_secondary {
9835 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
9836 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
9837 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
9838 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
9839 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
9840 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
9841 if clipping_required {
9842 for s in [s0, s1, s2, s3] {
9843 if s != CDEF_VERY_LARGE {
9844 max = max.max(s);
9845 }
9846 }
9847 min = min.min(s0).min(s1).min(s2).min(s3);
9848 }
9849 sum += CDEF_SEC_TAPS[k]
9850 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
9851 + cdef_constrain(s1 - x, sec_strength, sec_damping)
9852 + cdef_constrain(s2 - x, sec_strength, sec_damping)
9853 + cdef_constrain(s3 - x, sec_strength, sec_damping));
9854 }
9855 }
9856 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
9857 if clipping_required {
9858 y = y.clamp(min, max);
9859 }
9860 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, sample_max()) as u16;
9861 }
9862 }
9863}
9864
9865/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
9866/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
9867/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
9868/// every block's level comes from [`LoopFilterParams::level`] plus the
9869/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
9870/// `get_filter_level`, precomputed per-block here rather than cached in a
9871/// table the way libaom's `av1_loop_filter_frame_init` does).
9872///
9873/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
9874/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
9875fn apply_deblock(
9876 y: &mut PlaneBuf,
9877 u: &mut PlaneBuf,
9878 v: &mut PlaneBuf,
9879 lf: &LoopFilterParams,
9880 n: &Neighbours,
9881 frame_width: usize,
9882 frame_height: usize,
9883) {
9884 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
9885 // mismatch between the raw reconstruction and post-filter output.
9886 if std::env::var_os("EC_AV1_DEBUG_SKIP_DEBLOCK").is_some() {
9887 return;
9888 }
9889 if lf.level[0] != 0 || lf.level[1] != 0 {
9890 deblock_plane(y, 0, lf, n, frame_width, frame_height);
9891 }
9892 if lf.level[2] != 0 {
9893 deblock_plane(u, 1, lf, n, frame_width, frame_height);
9894 }
9895 if lf.level[3] != 0 {
9896 deblock_plane(v, 2, lf, n, frame_width, frame_height);
9897 }
9898}
9899
9900/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
9901/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
9902/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
9903/// mi unit under this decoder's assumed 4:2:0 subsampling).
9904fn plane_to_mi(chroma: bool, coord: usize) -> usize {
9905 if chroma { coord / 2 } else { coord / 4 }
9906}
9907
9908/// This plane's own transform width in pixels at the covering block, spec
9909/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
9910/// width directly; chroma halves it (this decoder's UV transform is always
9911/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
9912/// under 4:2:0 and a block that never splits its own transform).
9913fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
9914 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
9915 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
9916}
9917
9918/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
9919/// edges step and gate by transform height, which differs from width only
9920/// on rect partition strips.
9921fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
9922 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
9923 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
9924}
9925
9926/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
9927/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
9928/// present only when its neighbour exists inside the true frame -- whether
9929/// the block immediately above (at this block's own leftmost mi column) or
9930/// to the left (at its own topmost mi row) coded a transform at least as wide
9931/// as `own_side`.
9932fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
9933 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
9934 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
9935 usize::from(above) + usize::from(left)
9936}
9937
9938/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
9939/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
9940/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
9941/// inter path maintains), except that an *inter* neighbour contributes its
9942/// own BLOCK size rather than its transform size -- the two differ the moment
9943/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
9944/// approximation coincides with this only while every neighbour codes one
9945/// whole-block transform, which is exactly what `TxMode::Select` ends.
9946fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
9947 let has_above = mi_r > n.tile_row0_mi;
9948 let has_left = mi_c > n.tile_col0_mi;
9949 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
9950 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
9951 if has_above && n.above_inter[mi_c / (SUB / MI)] {
9952 above = n.above_side_mi[mi_c] >= side;
9953 }
9954 if has_left && n.left_inter[mi_r / (SUB / MI)] {
9955 left = n.left_side_mi[mi_r] >= side;
9956 }
9957 match (has_above, has_left) {
9958 (true, true) => usize::from(above) + usize::from(left),
9959 (true, false) => usize::from(above),
9960 (false, true) => usize::from(left),
9961 (false, false) => 0,
9962 }
9963}
9964
9965/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
9966/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
9967/// the transform's own side in pixels (`side >> depth`) -- this decoder's
9968/// four square categories (8/16/32/64) each halve at most twice, matching
9969/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
9970fn read_tx_size(
9971 dec: &mut SymbolDecoder,
9972 cdfs: &mut Cdfs,
9973 n: &Neighbours,
9974 at_mi: (usize, usize),
9975 side: usize,
9976 // lane-txselect: `get_tx_size_context`'s real context, for the callers
9977 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
9978 // key-frame path's own deblock-grid approximation.
9979 ctx_override: Option<usize>,
9980) -> usize {
9981 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, side));
9982 let depth = match side {
9983 8 => {
9984 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
9985 }
9986 16 => {
9987 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
9988 }
9989 32 => {
9990 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
9991 }
9992 64 => {
9993 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
9994 }
9995 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
9996 };
9997 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
9998 let (rng, _) = dec.debug_state();
9999 let (mi_r, mi_c) = at_mi;
10000 eprintln!(
10001 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
10002 );
10003 }
10004 if depth != 0 {
10005 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
10006 }
10007 side >> depth
10008}
10009
10010/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
10011/// `txfm_split` context -- a category from the block's own largest square
10012/// transform and whether this unit already sits below it, times three, plus
10013/// the two neighbour terms (whether the transform last written above/left of
10014/// this unit is narrower/shorter than the unit itself).
10015fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
10016 let above = usize::from(usize::from(above_px) < tx_px);
10017 let left = usize::from(usize::from(left_px) < tx_px);
10018 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
10019 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
10020 // `log2(px) - 2`.
10021 let max_tx = blk_max_px.min(64);
10022 let max_idx = max_tx.trailing_zeros() as usize - 2;
10023 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
10024 category * 3 + above + left
10025}
10026
10027/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
10028/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
10029/// resolved transform's own size.
10030fn txfm_partition_update(
10031 n: &mut Neighbours,
10032 (mi_r, mi_c): (usize, usize),
10033 tx_px: usize,
10034 txb_px: usize,
10035) {
10036 for i in 0..txb_px / MI {
10037 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
10038 *cell = tx_px as u8;
10039 }
10040 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
10041 *cell = tx_px as u8;
10042 }
10043 }
10044}
10045
10046/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
10047/// same contexts -- a skipped *inter* block records its own block size rather
10048/// than its transform size.
10049fn set_txfm_ctxs(
10050 n: &mut Neighbours,
10051 (mi_r, mi_c): (usize, usize),
10052 tx_px: usize,
10053 w_mi: usize,
10054 h_mi: usize,
10055 skip_inter: bool,
10056) {
10057 let bw = if skip_inter { w_mi * MI } else { tx_px };
10058 let bh = if skip_inter { h_mi * MI } else { tx_px };
10059 for i in 0..w_mi {
10060 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
10061 *cell = bw as u8;
10062 }
10063 }
10064 for i in 0..h_mi {
10065 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
10066 *cell = bh as u8;
10067 }
10068 }
10069}
10070
10071/// The value libaom initialises both transform contexts to -- NOT zero:
10072/// `av1_zero_above_context` memsets the txfm row to
10073/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
10074/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
10075/// pixels, so an unwritten neighbour reads as the *widest* possible
10076/// transform, not the narrowest.
10077const TXFM_CTX_INIT: u8 = 64;
10078
10079/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
10080/// twice below its own largest transform.
10081const MAX_VARTX_DEPTH: usize = 2;
10082
10083/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
10084/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
10085/// max-transform-sized unit of an inter block, collecting the resolved leaf
10086/// transform units into `out` as `(row offset, col offset, side)` in mi units
10087/// -- exactly the order `decode_reconstruct_tx` later reads their
10088/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
10089/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
10090/// `max_block_high`).
10091#[allow(clippy::too_many_arguments)]
10092fn read_var_tx_size(
10093 dec: &mut SymbolDecoder,
10094 cdfs: &mut Cdfs,
10095 n: &mut Neighbours,
10096 at_mi: (usize, usize),
10097 blk_max_px: usize,
10098 (max_w_mi, max_h_mi): (usize, usize),
10099 tx_px: usize,
10100 depth: usize,
10101 blk_row: usize,
10102 blk_col: usize,
10103 out: &mut Vec<(usize, usize, usize)>,
10104) {
10105 if blk_row >= max_h_mi || blk_col >= max_w_mi {
10106 return;
10107 }
10108 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
10109 if depth == MAX_VARTX_DEPTH {
10110 out.push((blk_row, blk_col, tx_px));
10111 txfm_partition_update(n, unit, tx_px, tx_px);
10112 return;
10113 }
10114 let ctx = txfm_partition_ctx(n.above_txfm[unit.1], n.left_txfm[unit.0], blk_max_px, tx_px);
10115 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
10116 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
10117 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
10118 let (rng, _) = dec.debug_state();
10119 eprintln!(
10120 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
10121 unit.0,
10122 unit.1,
10123 u8::from(split)
10124 );
10125 }
10126 if !split {
10127 out.push((blk_row, blk_col, tx_px));
10128 txfm_partition_update(n, unit, tx_px, tx_px);
10129 return;
10130 }
10131 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
10132 let sub = tx_px / 2;
10133 if sub == 4 {
10134 // libaom's `sub_txs == TX_4X4` early return: the whole 8x8 unit is
10135 // marked 4x4 (four transform units, raster order) without recursing.
10136 for row in 0..2 {
10137 for col in 0..2 {
10138 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
10139 out.push((blk_row + row, blk_col + col, 4));
10140 }
10141 }
10142 }
10143 txfm_partition_update(n, unit, 4, tx_px);
10144 return;
10145 }
10146 for row in (0..tx_px / MI).step_by(sub / MI) {
10147 for col in (0..tx_px / MI).step_by(sub / MI) {
10148 read_var_tx_size(
10149 dec,
10150 cdfs,
10151 n,
10152 at_mi,
10153 blk_max_px,
10154 (max_w_mi, max_h_mi),
10155 sub,
10156 depth + 1,
10157 blk_row + row,
10158 blk_col + col,
10159 out,
10160 );
10161 }
10162 }
10163}
10164
10165/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
10166/// branch): every block of a `TxMode::Select` inter frame codes its transform
10167/// size right after its own mode info -- an inter non-skip block through the
10168/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
10169/// every other block through the intra `tx_depth` symbol (a skipped inter
10170/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
10171/// block's own resolved transform side and the leaf list, the latter only
10172/// when the tree resolved to more than one transform unit.
10173#[allow(clippy::too_many_arguments)]
10174fn read_block_tx_size(
10175 dec: &mut SymbolDecoder,
10176 cdfs: &mut Cdfs,
10177 n: &mut Neighbours,
10178 at_mi: (usize, usize),
10179 side: usize,
10180 (mi_cols, mi_rows): (usize, usize),
10181 is_inter: bool,
10182 skip: bool,
10183) -> Result<(usize, Option<Vec<(usize, usize, usize)>>)> {
10184 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
10185 return Ok((side, None));
10186 }
10187 let side_mi = side / MI;
10188 if is_inter && !skip {
10189 let max_tx = side.min(64);
10190 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
10191 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
10192 let mut leaves = Vec::new();
10193 let step = max_tx / MI;
10194 for row in (0..side_mi).step_by(step) {
10195 for col in (0..side_mi).step_by(step) {
10196 read_var_tx_size(
10197 dec,
10198 cdfs,
10199 n,
10200 at_mi,
10201 side,
10202 (max_w_mi, max_h_mi),
10203 max_tx,
10204 0,
10205 row,
10206 col,
10207 &mut leaves,
10208 );
10209 }
10210 }
10211 let single = leaves.len() == 1 && leaves[0].2 == side;
10212 if !single && leaves.iter().any(|leaf| leaf.2 > 32) {
10213 // Only a block wider than a superblock's own 64x64 max transform
10214 // reaches here; this crate has no 64-point *inter* coefficient
10215 // table set ([`inter_txbset_for`] stops at 32).
10216 return Err(unsupported(
10217 "an inter var-tx tree with a leaf transform larger than 32x32",
10218 ));
10219 }
10220 let resolved = leaves.last().map_or(side, |l| l.2);
10221 return Ok((resolved, (!single).then_some(leaves)));
10222 }
10223 let tx = if is_inter {
10224 side.min(64)
10225 } else {
10226 read_tx_size(
10227 dec,
10228 cdfs,
10229 n,
10230 at_mi,
10231 side,
10232 Some(tx_size_context_txfm(n, at_mi, side)),
10233 )
10234 };
10235 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
10236 if !is_inter && tx != side {
10237 // lane-intrainter r1: an intra block inside an inter frame whose
10238 // `tx_depth` split its luma transform codes exactly the key-frame
10239 // split path's transform units (`decode_block`'s multi-TU loop),
10240 // raster order over the block. Handed back in the same leaf shape the
10241 // inter var-tx tree uses, so the caller's per-TU luma loop, the
10242 // `record_split_luma` neighbour write-back and the per-TU deblock
10243 // edges are the ones it already runs for a var-tx inter block. A
10244 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
10245 // seeing `Some` here.
10246 let step = tx / MI;
10247 let mut leaves = Vec::new();
10248 for row in (0..side_mi).step_by(step) {
10249 for col in (0..side_mi).step_by(step) {
10250 leaves.push((row, col, tx));
10251 }
10252 }
10253 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
10254 let mut h = c.get();
10255 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
10256 c.set(h);
10257 });
10258 return Ok((tx, Some(leaves)));
10259 }
10260 Ok((tx, None))
10261}
10262
10263/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
10264/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
10265/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
10266/// raster order, each reading its own coefficient context off the units
10267/// already decoded before it. Returns the block's luma grid (all-zero in the
10268/// split case, whose reconstruction has already happened unit by unit) and
10269/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
10270/// which for a split block lands on the top-left unit.
10271#[allow(clippy::too_many_arguments)]
10272fn read_inter_luma8(
10273 dec: &mut SymbolDecoder,
10274 cdfs: &mut Cdfs,
10275 neighbours: &mut Neighbours,
10276 leaf_mi: (usize, usize),
10277 y: &mut PlaneBuf,
10278 px: usize,
10279 py: usize,
10280 pred_y: &[u16],
10281 mode_for_tx: usize,
10282 base_q_idx: u8,
10283 scan8: &[u16],
10284 scan4: &[u16],
10285 reduced_tx_set: bool,
10286 split: bool,
10287) -> Result<(Vec<i32>, TxType)> {
10288 if !split {
10289 return read_inter_plane(
10290 dec,
10291 cdfs,
10292 if reduced_tx_set {
10293 TxbSet::Luma8Inter
10294 } else {
10295 TxbSet::Luma8InterSet1
10296 },
10297 scan8,
10298 0,
10299 neighbours.around_mi(leaf_mi, 8)[0],
10300 mode_for_tx,
10301 y,
10302 px,
10303 py,
10304 8,
10305 base_q_idx,
10306 pred_y,
10307 None,
10308 None,
10309 );
10310 }
10311 let mut first = TxType::DctDct;
10312 for tu_row in 0..2 {
10313 for tu_col in 0..2 {
10314 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
10315 let mut tu_pred = Vec::with_capacity(16);
10316 for rr in 0..4 {
10317 let start = (tu_row * 4 + rr) * 8 + tu_col * 4;
10318 tu_pred.extend_from_slice(&pred_y[start..start + 4]);
10319 }
10320 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
10321 let (tu_grid, tu_tx_type) = read_inter_plane(
10322 dec,
10323 cdfs,
10324 if reduced_tx_set {
10325 TxbSet::Luma4Inter
10326 } else {
10327 TxbSet::Luma4InterSet1
10328 },
10329 scan4,
10330 0,
10331 neighbours.around_mi(tu_mi, 4)[0],
10332 mode_for_tx,
10333 y,
10334 px + tu_col * 4,
10335 py + tu_row * 4,
10336 4,
10337 base_q_idx,
10338 &tu_pred,
10339 None,
10340 Some(tu_skip_ctx),
10341 )?;
10342 if tu_row == 0 && tu_col == 0 {
10343 first = tu_tx_type;
10344 }
10345 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
10346 }
10347 }
10348 Ok((vec![0i32; 64], first))
10349}
10350
10351/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
10352/// coefficient tables from -- the inter counterpart of [`txbset_for`].
10353fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
10354 match tx_px {
10355 32 => TxbSet::Luma32Inter,
10356 16 if reduced_tx_set => TxbSet::Luma16Inter,
10357 16 => TxbSet::Luma16InterSet1,
10358 8 if reduced_tx_set => TxbSet::Luma8Inter,
10359 8 => TxbSet::Luma8InterSet1,
10360 4 if reduced_tx_set => TxbSet::Luma4Inter,
10361 4 => TxbSet::Luma4InterSet1,
10362 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
10363 }
10364}
10365
10366/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
10367/// the only four sizes a `TxMode::Select` block's coded coefficient grid
10368/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
10369fn scan_for<'a>(
10370 tx_px: usize,
10371 scan32: &'a [u16],
10372 scan16: &'a [u16],
10373 scan8: &'a [u16],
10374 scan4: &'a [u16],
10375) -> &'a [u16] {
10376 match tx_px {
10377 32 => scan32,
10378 16 => scan16,
10379 8 => scan8,
10380 4 => scan4,
10381 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
10382 }
10383}
10384
10385/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
10386/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
10387/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
10388/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
10389/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
10390/// regardless of the flag (`av1_get_ext_tx_set_type`'s
10391/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
10392/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
10393/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
10394/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
10395/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
10396/// inter `ext_tx` sets, never the mode-indexed intra ones.
10397fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
10398 match tx_px {
10399 64 => TxbSet::Luma64,
10400 32 => TxbSet::Luma32Inter,
10401 16 if reduced_tx_set => TxbSet::Luma16Inter,
10402 16 => TxbSet::Luma16InterSet1,
10403 8 if reduced_tx_set => TxbSet::Luma8Inter,
10404 8 => TxbSet::Luma8InterSet1,
10405 _ => TxbSet::Luma64,
10406 }
10407}
10408
10409fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
10410 match tx_px {
10411 64 => TxbSet::Luma64,
10412 32 => TxbSet::Luma32,
10413 16 => TxbSet::Luma16,
10414 8 if reduced_tx_set => TxbSet::Luma8,
10415 8 => TxbSet::Luma8Set1,
10416 4 if reduced_tx_set => TxbSet::Luma4,
10417 4 => TxbSet::Luma4Set1,
10418 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
10419 }
10420}
10421
10422/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
10423/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
10424fn unit_log2(px: u32) -> i32 {
10425 if px == 0 {
10426 0
10427 } else {
10428 px.trailing_zeros() as i32 - 2
10429 }
10430}
10431
10432/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
10433/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
10434/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
10435/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
10436/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
10437/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
10438/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
10439/// block anywhere aborted the whole stream's decode before comparison).
10440fn lf_level(
10441 lf: &LoopFilterParams,
10442 plane_idx: usize,
10443 dir: usize,
10444 ref_frame: i8,
10445 delta_lf: i32,
10446 segment_id: u8,
10447) -> i32 {
10448 let base = i32::from(if plane_idx == 0 {
10449 lf.level[dir]
10450 } else if plane_idx == 1 {
10451 lf.level[2]
10452 } else {
10453 lf.level[3]
10454 });
10455 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
10456 // ref/mode delta scaling below, and regardless of `delta_enabled`
10457 // (that flag only gates `ref_deltas`/`mode_deltas`).
10458 let base = (base + delta_lf).clamp(0, 63);
10459 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
10460 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
10461 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
10462 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
10463 // for chroma.
10464 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
10465 let base = match seg_feature(usize::from(segment_id), feature) {
10466 Some(data) => (base + data).clamp(0, 63),
10467 None => base,
10468 };
10469 if !lf.delta_enabled {
10470 return base;
10471 }
10472 let scale = 1i32 << (base >> 5);
10473 let is_inter = ref_frame != 0;
10474 let is_globalmv = ref_frame < 0;
10475 let ref_idx = ref_frame.unsigned_abs() as usize;
10476 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
10477 if is_inter {
10478 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
10479 }
10480 lvl.clamp(0, 63)
10481}
10482
10483/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
10484/// no-segmentation, no-delta-LF path and to this decoder's own invariant
10485/// that a coded block's transform is always its own full size -- so a TU
10486/// edge is always also a PU edge, and the "both sides skipped, not a PU
10487/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
10488/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
10489/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
10490fn edge_params(
10491 lf: &LoopFilterParams,
10492 n: &Neighbours,
10493 plane_idx: usize,
10494 dir: usize,
10495 chroma: bool,
10496 x0: usize,
10497 y0: usize,
10498) -> Option<(u8, i32)> {
10499 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
10500 let cur_tx = if dir == 0 {
10501 tx_px_at(n, chroma, mi_r, mi_c)
10502 } else {
10503 tx_h_px_at(n, chroma, mi_r, mi_c)
10504 };
10505 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
10506 return None;
10507 }
10508 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
10509 let (pv_mi_r, pv_mi_c) = if dir == 0 {
10510 (mi_r, mi_c - 1)
10511 } else {
10512 (mi_r - 1, mi_c)
10513 };
10514 let pv_tx = if dir == 0 {
10515 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
10516 } else {
10517 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
10518 };
10519 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
10520 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
10521 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
10522 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
10523
10524 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
10525 let pv_level = lf_level(
10526 lf,
10527 plane_idx,
10528 dir,
10529 pv_ref,
10530 pv_delta_lf,
10531 segment_id_at(pv_mi_r, pv_mi_c),
10532 );
10533 if cur_level == 0 && pv_level == 0 {
10534 return None;
10535 }
10536 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
10537 let len: u8 = if chroma {
10538 if dim == 0 { 4 } else { 6 }
10539 } else {
10540 [4, 8, 14, 14, 14][dim]
10541 };
10542 let level = if cur_level != 0 { cur_level } else { pv_level };
10543 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
10544 Some((len, level))
10545}
10546
10547/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
10548fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
10549 let sharpness = i32::from(sharpness);
10550 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
10551 let mut lim = level >> shift;
10552 if sharpness > 0 {
10553 lim = lim.min(9 - sharpness);
10554 }
10555 lim = lim.max(1);
10556 (2 * (level + 2) + lim, lim, level >> 4)
10557}
10558
10559fn sclamp(v: i32) -> i32 {
10560 // libaom's `signed_char_clamp_high`: the clamp range scales with
10561 // `128 << (bit_depth - 8)` alongside the centering constant below.
10562 let scale = 1i32 << (bit_depth() - 8);
10563 v.clamp(-128 * scale, 128 * scale - 1)
10564}
10565
10566fn round_pow2(v: i32, n: u32) -> i32 {
10567 (v + (1 << (n - 1))) >> n
10568}
10569
10570/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
10571/// fallback.
10572fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
10573 if !mask {
10574 return [p1, p0, q0, q1];
10575 }
10576 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
10577 let centre = 128i32 << (bit_depth() - 8);
10578 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
10579 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
10580 let filter = sclamp(outer + 3 * (qs0 - ps0));
10581 let filter1 = sclamp(filter + 4) >> 3;
10582 let filter2 = sclamp(filter + 3) >> 3;
10583 let oq0 = sclamp(qs0 - filter1) + centre;
10584 let op0 = sclamp(ps0 + filter2) + centre;
10585 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
10586 let oq1 = sclamp(qs1 - tap) + centre;
10587 let op1 = sclamp(ps1 + tap) + centre;
10588 [op1, op0, oq0, oq1]
10589}
10590
10591/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
10592/// `filter4`'s narrow taps.
10593#[allow(clippy::too_many_arguments)]
10594fn filter6(
10595 mask: bool,
10596 thresh: i32,
10597 flat: bool,
10598 p2: i32,
10599 p1: i32,
10600 p0: i32,
10601 q0: i32,
10602 q1: i32,
10603 q2: i32,
10604) -> [i32; 4] {
10605 if flat && mask {
10606 [
10607 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
10608 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
10609 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
10610 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
10611 ]
10612 } else {
10613 filter4(mask, thresh, p1, p0, q0, q1)
10614 }
10615}
10616
10617/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
10618#[allow(clippy::too_many_arguments)]
10619fn filter8(
10620 mask: bool,
10621 thresh: i32,
10622 flat: bool,
10623 p3: i32,
10624 p2: i32,
10625 p1: i32,
10626 p0: i32,
10627 q0: i32,
10628 q1: i32,
10629 q2: i32,
10630 q3: i32,
10631) -> [i32; 6] {
10632 if flat && mask {
10633 [
10634 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
10635 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
10636 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
10637 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
10638 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
10639 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
10640 ]
10641 } else {
10642 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
10643 [p2, op1, op0, oq0, oq1, q2]
10644 }
10645}
10646
10647/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
10648/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
10649/// way -- they are only ever taps here, never written).
10650#[allow(clippy::too_many_arguments)]
10651fn filter14(
10652 mask: bool,
10653 thresh: i32,
10654 flat: bool,
10655 flat2: bool,
10656 p6: i32,
10657 p5: i32,
10658 p4: i32,
10659 p3: i32,
10660 p2: i32,
10661 p1: i32,
10662 p0: i32,
10663 q0: i32,
10664 q1: i32,
10665 q2: i32,
10666 q3: i32,
10667 q4: i32,
10668 q5: i32,
10669 q6: i32,
10670) -> [i32; 12] {
10671 if flat2 && flat && mask {
10672 [
10673 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
10674 round_pow2(
10675 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
10676 4,
10677 ),
10678 round_pow2(
10679 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
10680 4,
10681 ),
10682 round_pow2(
10683 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
10684 4,
10685 ),
10686 round_pow2(
10687 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
10688 4,
10689 ),
10690 round_pow2(
10691 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
10692 4,
10693 ),
10694 round_pow2(
10695 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
10696 4,
10697 ),
10698 round_pow2(
10699 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
10700 4,
10701 ),
10702 round_pow2(
10703 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
10704 4,
10705 ),
10706 round_pow2(
10707 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
10708 4,
10709 ),
10710 round_pow2(
10711 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
10712 4,
10713 ),
10714 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
10715 ]
10716 } else {
10717 let [op2, op1, op0, oq0, oq1, oq2] =
10718 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
10719 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
10720 }
10721}
10722
10723/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
10724/// the first (`q0`) sample past the edge, `outer_stride` advances to the
10725/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
10726/// the next along the edge's own filtering direction.
10727#[allow(clippy::too_many_arguments)]
10728fn filter_edge(
10729 data: &mut [u16],
10730 base: usize,
10731 outer_stride: isize,
10732 tap_stride: isize,
10733 len: u8,
10734 level: i32,
10735 sharpness: u8,
10736) {
10737 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
10738 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
10739 // every 8-bit threshold (including the flat masks' fixed `1`) is
10740 // compared against a raw pixel difference on the stream's own bit-depth
10741 // scale, so each is shifted left by `bit_depth - 8` before use.
10742 let shift = bit_depth() - 8;
10743 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
10744 let flat_thresh = 1i32 << shift;
10745 for i in 0..4isize {
10746 let center = (base as isize + i * outer_stride) as usize;
10747 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
10748 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
10749 match len {
10750 4 => {
10751 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
10752 let mask = (p1 - p0).abs() <= limit
10753 && (q1 - q0).abs() <= limit
10754 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10755 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
10756 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10757 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10758 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10759 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10760 }
10761 6 => {
10762 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
10763 let mask = (p2 - p1).abs() <= limit
10764 && (p1 - p0).abs() <= limit
10765 && (q1 - q0).abs() <= limit
10766 && (q2 - q1).abs() <= limit
10767 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10768 let flat = (p1 - p0).abs() <= flat_thresh
10769 && (q1 - q0).abs() <= flat_thresh
10770 && (p2 - p0).abs() <= flat_thresh
10771 && (q2 - q0).abs() <= flat_thresh;
10772 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
10773 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10774 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10775 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10776 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10777 }
10778 8 => {
10779 let (p3, p2, p1, p0, q0, q1, q2, q3) =
10780 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
10781 let mask = (p3 - p2).abs() <= limit
10782 && (p2 - p1).abs() <= limit
10783 && (p1 - p0).abs() <= limit
10784 && (q1 - q0).abs() <= limit
10785 && (q2 - q1).abs() <= limit
10786 && (q3 - q2).abs() <= limit
10787 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10788 let flat = (p1 - p0).abs() <= flat_thresh
10789 && (q1 - q0).abs() <= flat_thresh
10790 && (p2 - p0).abs() <= flat_thresh
10791 && (q2 - q0).abs() <= flat_thresh
10792 && (p3 - p0).abs() <= flat_thresh
10793 && (q3 - q0).abs() <= flat_thresh;
10794 let [op2, op1, op0, oq0, oq1, oq2] =
10795 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
10796 data[idx(-3)] = op2.clamp(0, sample_max()) as u16;
10797 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10798 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10799 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10800 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10801 data[idx(2)] = oq2.clamp(0, sample_max()) as u16;
10802 }
10803 _ => {
10804 let (p6, p5, p4, p3, p2, p1, p0) =
10805 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
10806 let (q0, q1, q2, q3, q4, q5, q6) =
10807 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
10808 let mask = (p3 - p2).abs() <= limit
10809 && (p2 - p1).abs() <= limit
10810 && (p1 - p0).abs() <= limit
10811 && (q1 - q0).abs() <= limit
10812 && (q2 - q1).abs() <= limit
10813 && (q3 - q2).abs() <= limit
10814 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10815 let flat = (p1 - p0).abs() <= flat_thresh
10816 && (q1 - q0).abs() <= flat_thresh
10817 && (p2 - p0).abs() <= flat_thresh
10818 && (q2 - q0).abs() <= flat_thresh
10819 && (p3 - p0).abs() <= flat_thresh
10820 && (q3 - q0).abs() <= flat_thresh;
10821 let flat2 = (p4 - p0).abs() <= flat_thresh
10822 && (q4 - q0).abs() <= flat_thresh
10823 && (p5 - p0).abs() <= flat_thresh
10824 && (q5 - q0).abs() <= flat_thresh
10825 && (p6 - p0).abs() <= flat_thresh
10826 && (q6 - q0).abs() <= flat_thresh;
10827 let out = filter14(
10828 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
10829 q6,
10830 );
10831 for (k, v) in (-6..=5isize).zip(out) {
10832 data[idx(k)] = v.clamp(0, sample_max()) as u16;
10833 }
10834 }
10835 }
10836 }
10837}
10838
10839/// One plane's worth of spec 7.14: every vertical edge across the plane,
10840/// then every horizontal edge (the order the spec and libaom both use).
10841fn deblock_plane(
10842 plane: &mut PlaneBuf,
10843 plane_idx: usize,
10844 lf: &LoopFilterParams,
10845 n: &Neighbours,
10846 frame_width: usize,
10847 frame_height: usize,
10848) {
10849 let chroma = plane_idx != 0;
10850 // r7: libaom clips the deblock loop to the CODED frame's own
10851 // width/height, not the mi-aligned `true_width`/`true_height` margin
10852 // (the padding up to the next 8-pixel/superblock boundary that
10853 // reconstruction still fills in but the loop filter never visits).
10854 // Confirmed against the superres gate: with the margin included, the
10855 // last coded mi column's horizontal edges were filtered when libaom's
10856 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
10857 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
10858 let (cw, ch) = if chroma {
10859 (frame_width.div_ceil(2), frame_height.div_ceil(2))
10860 } else {
10861 (frame_width, frame_height)
10862 };
10863 let (tw, th, stride) = (
10864 plane.true_width.min(cw),
10865 plane.true_height.min(ch),
10866 plane.width,
10867 );
10868 let mut y0 = 0usize;
10869 while y0 < th {
10870 let mut x0 = 4usize;
10871 while x0 < tw {
10872 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
10873 filter_edge(
10874 &mut plane.data,
10875 y0 * stride + x0,
10876 stride as isize,
10877 1,
10878 len,
10879 level,
10880 lf.sharpness,
10881 );
10882 }
10883 x0 += 4;
10884 }
10885 y0 += 4;
10886 }
10887 let mut x0 = 0usize;
10888 while x0 < tw {
10889 let mut y0 = 4usize;
10890 while y0 < th {
10891 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
10892 if std::env::var_os("EC_AV1_DEBLOCK_TRACE").is_some()
10893 && plane_idx == 0
10894 && x0 == 44
10895 {
10896 eprintln!(
10897 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
10898 lf.sharpness
10899 );
10900 }
10901 filter_edge(
10902 &mut plane.data,
10903 y0 * stride + x0,
10904 1,
10905 stride as isize,
10906 len,
10907 level,
10908 lf.sharpness,
10909 );
10910 }
10911 y0 += 4;
10912 }
10913 x0 += 4;
10914 }
10915}
10916
10917fn apply_cdef(
10918 y: &mut PlaneBuf,
10919 u: &mut PlaneBuf,
10920 v: &mut PlaneBuf,
10921 cdef: &CdefParams,
10922 skip_grid: &Neighbours,
10923) {
10924 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
10925 if std::env::var_os("EC_AV1_DEBUG_SKIP_CDEF").is_some() {
10926 return;
10927 }
10928 // `cdef.bits == 0` still means "no filtering at all" whenever the single
10929 // (index 0) strength pair is all-zero -- the fast path every existing
10930 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
10931 // at every index, but that is rare enough not to special-case; the
10932 // per-superblock lookup below degrades to the same index-0 read anyway
10933 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
10934 if cdef.bits == 0
10935 && cdef.y_pri_strength[0] == 0
10936 && cdef.y_sec_strength[0] == 0
10937 && cdef.uv_pri_strength[0] == 0
10938 && cdef.uv_sec_strength[0] == 0
10939 {
10940 return;
10941 }
10942 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
10943 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
10944 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
10945 if sb_cols == 0 {
10946 return 0;
10947 }
10948 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
10949 idx_grid
10950 .get(sb_r * sb_cols + sb_c)
10951 .copied()
10952 .unwrap_or(0) as usize
10953 };
10954 let src_y = y.data.clone();
10955 let src_u = u.data.clone();
10956 let src_v = v.data.clone();
10957 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
10958 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
10959 let coeff_shift = i32::from(bit_depth()) - 8;
10960 let damping = i32::from(cdef.damping) + coeff_shift;
10961 let damping_uv = (damping - 1).max(0);
10962 let mut mi_r = 0usize;
10963 while mi_r < skip_grid.mi_rows {
10964 let mut mi_c = 0usize;
10965 while mi_c < skip_grid.mi_cols {
10966 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
10967 let sidx = strength_idx(mi_r, mi_c);
10968 let (ox, oy) = (mi_c * 4, mi_r * 4);
10969 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
10970 let sample_y = |r: i32, c: i32| -> i32 {
10971 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
10972 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
10973 CDEF_VERY_LARGE
10974 } else {
10975 i32::from(src_y[ny as usize * y_stride + nx as usize])
10976 }
10977 };
10978 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| {
10979 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
10980 i32::from(src_y[ny * y_stride + nx])
10981 });
10982
10983 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
10984 // -- each plane zeroes the shared direction when *its own*
10985 // frame-level primary strength is 0, independent of the
10986 // per-block adjusted `t` and of the other plane's strength.
10987 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
10988 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
10989 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
10990 let t = cdef_adjust_strength(y_pri_strength, var);
10991 let enable_primary = t != 0;
10992 let enable_secondary = y_sec_strength != 0;
10993 if enable_primary || enable_secondary {
10994 cdef_filter_block(
10995 sample_y,
10996 y,
10997 ox,
10998 oy,
10999 8,
11000 8,
11001 t,
11002 y_sec_strength,
11003 y_dir,
11004 damping,
11005 damping,
11006 enable_primary,
11007 enable_secondary,
11008 coeff_shift,
11009 );
11010 }
11011
11012 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
11013 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
11014 let uv_dir = if t_uv != 0 { dir } else { 0 };
11015 let enable_primary_uv = t_uv != 0;
11016 let enable_secondary_uv = uv_sec_strength != 0;
11017 if enable_primary_uv || enable_secondary_uv {
11018 let (cox, coy) = (ox / 2, oy / 2);
11019 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
11020 let (tw, th) = (plane.true_width, plane.true_height);
11021 let stride = plane.width;
11022 let sample_uv = |r: i32, c: i32| -> i32 {
11023 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
11024 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
11025 CDEF_VERY_LARGE
11026 } else {
11027 i32::from(src_p[ny as usize * stride + nx as usize])
11028 }
11029 };
11030 cdef_filter_block(
11031 sample_uv,
11032 plane,
11033 cox,
11034 coy,
11035 4,
11036 4,
11037 t_uv,
11038 uv_sec_strength,
11039 uv_dir,
11040 damping_uv,
11041 damping_uv,
11042 enable_primary_uv,
11043 enable_secondary_uv,
11044 coeff_shift,
11045 );
11046 }
11047 }
11048 }
11049 mi_c += 2;
11050 }
11051 mi_r += 2;
11052 }
11053}
11054
11055/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
11056/// ordering note: libaom also runs `superres_post_decode` between the two,
11057/// but this decoder never implements super-resolution, so there is nothing
11058/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
11059/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
11060/// restoration's stripe-boundary rows read from it instead of the
11061/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
11062#[allow(clippy::too_many_arguments)]
11063fn apply_loop_restoration(
11064 y: &mut PlaneBuf,
11065 u: &mut PlaneBuf,
11066 v: &mut PlaneBuf,
11067 deblocked_y: &PlaneBuf,
11068 deblocked_u: &PlaneBuf,
11069 deblocked_v: &PlaneBuf,
11070 lr: &LoopRestorationParams,
11071 grid: &crate::restoration::RestorationGrid,
11072) {
11073 y.data = crate::restoration::apply_loop_restoration_plane(
11074 &y.data,
11075 &deblocked_y.data,
11076 y.width,
11077 y.true_width,
11078 y.true_height,
11079 0,
11080 lr.frame_restoration_type[0],
11081 lr.loop_restoration_size[0],
11082 grid,
11083 0,
11084 );
11085 u.data = crate::restoration::apply_loop_restoration_plane(
11086 &u.data,
11087 &deblocked_u.data,
11088 u.width,
11089 u.true_width,
11090 u.true_height,
11091 1,
11092 lr.frame_restoration_type[1],
11093 lr.loop_restoration_size[1],
11094 grid,
11095 1,
11096 );
11097 v.data = crate::restoration::apply_loop_restoration_plane(
11098 &v.data,
11099 &deblocked_v.data,
11100 v.width,
11101 v.true_width,
11102 v.true_height,
11103 1,
11104 lr.frame_restoration_type[2],
11105 lr.loop_restoration_size[2],
11106 grid,
11107 2,
11108 );
11109}
11110
11111/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
11112/// returning the picture it reconstructs to.
11113///
11114/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
11115/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
11116/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
11117/// `compute_image_size` derives one from the other, but not losslessly: a
11118/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
11119/// what the reconstruction is cropped to on the way out, mirroring
11120/// [`crate::encode::crop_encoded`].
11121///
11122/// # Errors
11123/// Returns an error when a block's partition, mode, skip flag or transform
11124/// type is anything this decoder does not reconstruct (round 2: inter, tx
11125/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
11126/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
11127/// or when the tile payload runs out of the symbols this decode expects (a
11128/// genuinely foreign stream).
11129pub fn decode_key_frame_tile(
11130 data: &[u8],
11131 mi_cols: u32,
11132 mi_rows: u32,
11133 base_q_idx: u8,
11134 frame_width: u32,
11135 frame_height: u32,
11136 enable_filter_intra: bool,
11137 cdef: &CdefParams,
11138 loop_filter: &LoopFilterParams,
11139 tx_select: bool,
11140 reduced_tx_set: bool,
11141 allow_screen_content_tools: bool,
11142 allow_intrabc: bool,
11143) -> Result<Picture> {
11144 let delta = DeltaParams::default();
11145 let single_tile = TileInfo {
11146 mi_col_starts: vec![0, mi_cols],
11147 mi_row_starts: vec![0, mi_rows],
11148 ..TileInfo::default()
11149 };
11150 decode_key_frame_tile_with_cdfs(
11151 &[data],
11152 &single_tile,
11153 mi_cols,
11154 mi_rows,
11155 base_q_idx,
11156 crate::quant::QuantDeltas::default(),
11157 frame_width,
11158 frame_height,
11159 enable_filter_intra,
11160 false,
11161 cdef,
11162 loop_filter,
11163 &LoopRestorationParams::default(),
11164 None,
11165 tx_select,
11166 reduced_tx_set,
11167 allow_screen_content_tools,
11168 allow_intrabc,
11169 delta,
11170 )
11171 .map(|(picture, _)| picture)
11172}
11173
11174thread_local! {
11175 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
11176 /// the mi-aligned `true_width`, set by the most recent
11177 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
11178 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
11179 /// their reconstructed buffer down from the same mi-aligned extent, so
11180 /// they share this one slot. See each function's own comment at its
11181 /// write site. `None` when there was no margin to save.
11182 static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
11183 const { std::cell::RefCell::new(None) };
11184}
11185
11186/// The margin the most recent key- or inter-frame tile decode stashed
11187/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
11188/// reads this immediately after the call, before any other frame
11189/// decode can overwrite it.
11190pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
11191 LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
11192}
11193
11194/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
11195/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
11196/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
11197/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
11198/// since a key frame's own header always forces `primary_ref_frame ==
11199/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
11200/// alongside the picture, for the caller to save into whichever reference
11201/// slots this frame's `refresh_frame_flags` names.
11202/// The order the 64x64 superblock quadrants of a tile are decoded in.
11203///
11204/// At `sb_size == 64` this is plain raster order over the tile's own
11205/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
11206/// each 128x128 superblock in raster order and visits its four 64x64
11207/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
11208/// 64-level bodies must run in that nested order. `row_start` marks the first
11209/// item of each *superblock* row (where the left neighbour context resets),
11210/// `sb_start` the first item of each superblock (where the 128 root's own
11211/// loop-restoration units and partition symbol are read).
11212fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
11213 let mut out = Vec::new();
11214 if !sb128 {
11215 for r in r0..r1 {
11216 for c in c0..c1 {
11217 out.push((r, c, c == c0, true));
11218 }
11219 }
11220 return out;
11221 }
11222 let mut r = r0;
11223 while r < r1 {
11224 let mut first_in_row = true;
11225 let mut c = c0;
11226 while c < c1 {
11227 let mut first_in_sb = true;
11228 for qr in 0..2 {
11229 for qc in 0..2 {
11230 let (rr, cc) = (r + qr, c + qc);
11231 if rr >= r1 || cc >= c1 {
11232 continue;
11233 }
11234 out.push((rr, cc, first_in_row, first_in_sb));
11235 first_in_row = false;
11236 first_in_sb = false;
11237 }
11238 }
11239 c += 2;
11240 }
11241 r += 2;
11242 }
11243 out
11244}
11245
11246/// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
11247/// the inter tile loop. Its loop-restoration units are read once for the whole
11248/// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
11249/// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
11250/// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
11251/// decoder codes, the other seven arms refuse by name.
11252#[allow(clippy::too_many_arguments)]
11253fn read_sb128_root(
11254 dec: &mut SymbolDecoder,
11255 cdfs: &mut Cdfs,
11256 neighbours: &Neighbours,
11257 lr: &LoopRestorationParams,
11258 lr_grid: &mut crate::restoration::RestorationGrid,
11259 lr_reference: &mut [(
11260 crate::restoration::WienerInfo,
11261 crate::restoration::SgrprojInfo,
11262 ); 3],
11263 sb_r: u32,
11264 sb_c: u32,
11265 mi_cols: u32,
11266 mi_rows: u32,
11267) -> Result<()> {
11268 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
11269 crate::restoration::read_lr(
11270 dec,
11271 cdfs,
11272 lr,
11273 lr_grid,
11274 lr_reference,
11275 mi_r128,
11276 mi_c128,
11277 SB_MI * 2,
11278 );
11279 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
11280 let ctx128 = neighbours.partition_ctx(at128, 128);
11281 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
11282 let part128 = if has_cols128 && has_rows128 {
11283 PART128_SYMBOLS.with(|c| c.set(c.get() + 1));
11284 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
11285 if std::env::var_os("EC_AV1_TRACE").is_some() {
11286 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
11287 }
11288 p
11289 } else {
11290 match (has_cols128, has_rows128) {
11291 (true, false) => {
11292 dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128));
11293 }
11294 (false, true) => {
11295 dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128));
11296 }
11297 _ => {}
11298 }
11299 PARTITION_SPLIT
11300 };
11301 if part128 != PARTITION_SPLIT {
11302 return Err(unsupported(
11303 "a 128x128 superblock partition other than SPLIT (NONE/HORZ/VERT and the four AB arms at the 128 root are not decoded)",
11304 ));
11305 }
11306 PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1));
11307 Ok(())
11308}
11309
11310pub(crate) fn decode_key_frame_tile_with_cdfs(
11311 tiles: &[&[u8]],
11312 tile_info: &TileInfo,
11313 mi_cols: u32,
11314 mi_rows: u32,
11315 base_q_idx: u8,
11316 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
11317 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
11318 // tile alongside [`CURRENT_Q_IDX`].
11319 deltas: crate::quant::QuantDeltas,
11320 frame_width: u32,
11321 frame_height: u32,
11322 enable_filter_intra: bool,
11323 enable_edge_filter: bool,
11324 cdef: &CdefParams,
11325 loop_filter: &LoopFilterParams,
11326 lr: &LoopRestorationParams,
11327 initial_cdfs: Option<Cdfs>,
11328 tx_select: bool,
11329 reduced_tx_set: bool,
11330 allow_screen_content_tools: bool,
11331 allow_intrabc: bool,
11332 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
11333 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
11334 // `stream.rs` still refuses a frame with `lf_present` set before this
11335 // function is ever called.
11336 delta: DeltaParams,
11337) -> Result<(Picture, Cdfs)> {
11338 if mi_cols == 0 || mi_rows == 0 {
11339 return Err(unsupported("a frame with no mode-info grid"));
11340 }
11341 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
11342 let sb128 = sb128();
11343 if sb128 && allow_intrabc {
11344 return Err(unsupported(
11345 "intrabc under a 128x128 superblock (libaom's av1_is_dv_valid derives the block-vector delay from sb_size, which this decoder hardcodes to 64)",
11346 ));
11347 }
11348 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
11349 INTRABC_MI_GRID.with(|g| {
11350 *g.borrow_mut() = allow_intrabc.then(|| {
11351 (
11352 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
11353 mi_cols as usize,
11354 mi_rows as usize,
11355 )
11356 });
11357 });
11358 INTRABC_DV.with(|c| c.set(None));
11359 CDEF_BITS.with(|c| c.set(cdef.bits));
11360 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
11361 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
11362 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
11363 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
11364 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
11365 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
11366 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
11367 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
11368 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
11369 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
11370
11371 let mut y = PlaneBuf {
11372 data: vec![0u16; width * height],
11373 width,
11374 height,
11375 true_width,
11376 true_height,
11377 tile_x0: 0,
11378 tile_y0: 0,
11379 tile_x1: width,
11380 tile_y1: height,
11381 };
11382 let mut u = PlaneBuf {
11383 data: vec![0u16; width * height / 4],
11384 width: width / 2,
11385 height: height / 2,
11386 true_width: true_width / 2,
11387 true_height: true_height / 2,
11388 tile_x0: 0,
11389 tile_y0: 0,
11390 tile_x1: width / 2,
11391 tile_y1: height / 2,
11392 };
11393 let mut v = PlaneBuf {
11394 data: vec![0u16; width * height / 4],
11395 width: width / 2,
11396 height: height / 2,
11397 true_width: true_width / 2,
11398 true_height: true_height / 2,
11399 tile_x0: 0,
11400 tile_y0: 0,
11401 tile_x1: width / 2,
11402 tile_y1: height / 2,
11403 };
11404
11405 let scan32 = default_scan(TX32);
11406 let scan16 = default_scan(TX16);
11407 let scan8 = default_scan(TX8);
11408 let scan4 = default_scan(TX4);
11409
11410 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
11411 let mut result_cdfs = base_cdfs.clone();
11412 let mut neighbours = Neighbours::new(
11413 cols32 as usize * 2,
11414 rows32 as usize * 2,
11415 mi_cols as usize,
11416 mi_rows as usize,
11417 );
11418 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
11419 let mut lr_reference = [(
11420 crate::restoration::WienerInfo::default(),
11421 crate::restoration::SgrprojInfo::default(),
11422 ); 3];
11423
11424 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
11425 // own byte range and its own fresh copy of the frame's initial CDFs
11426 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
11427 // `context_update_tile_id` has its end-of-tile adapted table kept as the
11428 // frame's own output (spec `exit_symbol`) -- every other tile's
11429 // adaptation is discarded, matching the refusal this replaces.
11430 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
11431 let tile_num = tile_idx as u32;
11432 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
11433 let mi_row0 = tile_info.mi_row_starts[trow as usize];
11434 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
11435 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
11436 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
11437 // Tile boundaries are always superblock-aligned in mi units (spec
11438 // 5.9.15's uniform/non-uniform derivation both only ever emit
11439 // multiples of the superblock's own mi size), so plain division is
11440 // exact here -- no rounding needed.
11441 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
11442 // tile boundary) are always superblock-aligned by spec 5.9.15; the
11443 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
11444 // last entry) is not, so the upper bound needs `div_ceil` the same
11445 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
11446 // trailing partial superblock row/column in scope.
11447 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
11448 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
11449
11450 let mut cdfs = base_cdfs.clone();
11451 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
11452 // `base_q_idx` at the top of every tile, not once per frame.
11453 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
11454 QUANT_DELTAS.with(|c| c.set(deltas));
11455 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
11456 if std::env::var_os("EC_AV1_TRACE").is_some() {
11457 eprintln!(
11458 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
11459 tile_bytes.len(),
11460 &tile_bytes[..tile_bytes.len().min(8)]
11461 );
11462 }
11463 let mut dec = SymbolDecoder::new(tile_bytes);
11464 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
11465 y.set_tile_origin(
11466 mi_col0 as usize * 4,
11467 mi_row0 as usize * 4,
11468 (mi_col1 as usize * 4).min(y.width),
11469 (mi_row1 as usize * 4).min(y.height),
11470 );
11471 u.set_tile_origin(
11472 mi_col0 as usize * 2,
11473 mi_row0 as usize * 2,
11474 (mi_col1 as usize * 2).min(u.width),
11475 (mi_row1 as usize * 2).min(u.height),
11476 );
11477 v.set_tile_origin(
11478 mi_col0 as usize * 2,
11479 mi_row0 as usize * 2,
11480 (mi_col1 as usize * 2).min(v.width),
11481 (mi_row1 as usize * 2).min(v.height),
11482 );
11483 TILE_HITS.with(|c| c.set(c.get() + 1));
11484
11485 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
11486 if row_start {
11487 neighbours.start_row();
11488 }
11489 {
11490 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
11491 // once for the whole 128x128 (spec 5.11.57 is called with the
11492 // superblock's own size), then one partition symbol off the
11493 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
11494 // recurses into the four 64x64 quadrants this decoder codes.
11495 if sb128 && sb_start {
11496 read_sb128_root(
11497 &mut dec,
11498 &mut cdfs,
11499 &neighbours,
11500 lr,
11501 &mut lr_grid,
11502 &mut lr_reference,
11503 sb_r,
11504 sb_c,
11505 mi_cols,
11506 mi_rows,
11507 )?;
11508 }
11509 if !sb128 {
11510 crate::restoration::read_lr(
11511 &mut dec,
11512 &mut cdfs,
11513 lr,
11514 &mut lr_grid,
11515 &mut lr_reference,
11516 sb_r * SB_MI,
11517 sb_c * SB_MI,
11518 SB_MI,
11519 );
11520 }
11521 CDEF_TRANSMITTED.with(|c| c.set(false));
11522 let at = (sb_r as usize * 4, sb_c as usize * 4);
11523 let ctx = neighbours.partition_ctx(at, SB);
11524 let (has_cols, has_rows) = (
11525 sb_c * SB_MI + SB_MI / 2 < mi_cols,
11526 sb_r * SB_MI + SB_MI / 2 < mi_rows,
11527 );
11528 // Recomputed at this superblock's own half (spec
11529 // `decode_partition`): a full alphabet symbol when both halves are
11530 // inside the true frame, a single gathered bit when just one is
11531 // (the superblock cannot be left whole, so this is forced split),
11532 // and nothing at all (SPLIT inferred, no bits) when neither is —
11533 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
11534 // three-way write exactly.
11535 let part = if has_cols && has_rows {
11536 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
11537 if std::env::var_os("EC_AV1_TRACE").is_some() {
11538 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
11539 }
11540 p
11541 } else {
11542 match (has_cols, has_rows) {
11543 (true, false) => {
11544 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
11545 }
11546 (false, true) => {
11547 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
11548 }
11549 _ => {}
11550 }
11551 PARTITION_SPLIT
11552 };
11553 match part {
11554 PARTITION_NONE => {
11555 decode_block(
11556 &mut dec,
11557 &mut cdfs,
11558 &mut neighbours,
11559 at,
11560 SB,
11561 TxbSet::Luma64,
11562 TxbSet::Chroma32,
11563 TX32,
11564 TX32,
11565 (&scan32, &scan32),
11566 false,
11567 &mut y,
11568 &mut u,
11569 &mut v,
11570 base_q_idx,
11571 enable_filter_intra,
11572 allow_screen_content_tools,
11573 allow_intrabc,
11574 &scan32,
11575 &scan16,
11576 &scan8,
11577 &scan4,
11578 tx_select,
11579 reduced_tx_set,
11580 )?;
11581 }
11582 PARTITION_SPLIT => {
11583 for q in 0..4 {
11584 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
11585 if r32 >= rows32 || c32 >= cols32 {
11586 continue;
11587 }
11588 let at32 = (r32 as usize * 2, c32 as usize * 2);
11589 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
11590 let (has_cols32, has_rows32) = (
11591 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
11592 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
11593 );
11594 let part32 = if has_cols32 && has_rows32 {
11595 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
11596 if std::env::var_os("EC_AV1_TRACE").is_some() {
11597 let (rng, _) = dec.debug_state();
11598 eprintln!(
11599 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
11600 r32 * BLOCK_MI,
11601 c32 * BLOCK_MI
11602 );
11603 }
11604 p
11605 } else {
11606 match (has_cols32, has_rows32) {
11607 (true, false) => {
11608 dec.symbol_fixed(&gather(
11609 &cdfs.partition_w32[ctx32],
11610 VERT_ALIKE,
11611 ));
11612 }
11613 (false, true) => {
11614 dec.symbol_fixed(&gather(
11615 &cdfs.partition_w32[ctx32],
11616 HORZ_ALIKE,
11617 ));
11618 }
11619 _ => {}
11620 }
11621 PARTITION_SPLIT
11622 };
11623 match part32 {
11624 PARTITION_NONE => {
11625 decode_block(
11626 &mut dec,
11627 &mut cdfs,
11628 &mut neighbours,
11629 at32,
11630 BLOCK,
11631 TxbSet::Luma32,
11632 TxbSet::Chroma16,
11633 TX32,
11634 TX16,
11635 (&scan32, &scan16),
11636 true,
11637 &mut y,
11638 &mut u,
11639 &mut v,
11640 base_q_idx,
11641 enable_filter_intra,
11642 allow_screen_content_tools,
11643 allow_intrabc,
11644 &scan32,
11645 &scan16,
11646 &scan8,
11647 &scan4,
11648 tx_select,
11649 reduced_tx_set,
11650 )?;
11651 }
11652 PARTITION_SPLIT => {
11653 for sub in 0..4 {
11654 let (sr, sc) =
11655 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
11656 if (sr as u32) * SUB_MI >= mi_rows
11657 || (sc as u32) * SUB_MI >= mi_cols
11658 {
11659 continue;
11660 }
11661 let (has_cols16, has_rows16) = (
11662 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
11663 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
11664 );
11665 let at16 = (sr, sc);
11666 let ctx16 = neighbours.partition_ctx(at16, SUB);
11667 if has_cols16 && has_rows16 {
11668 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
11669 if std::env::var_os("EC_AV1_TRACE").is_some() {
11670 eprintln!(
11671 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
11672 at16.0, at16.1
11673 );
11674 }
11675 if part16 == PARTITION_NONE {
11676 decode_block(
11677 &mut dec,
11678 &mut cdfs,
11679 &mut neighbours,
11680 at16,
11681 SUB,
11682 TxbSet::Luma16,
11683 TxbSet::Chroma8,
11684 TX16,
11685 TX8,
11686 (&scan16, &scan8),
11687 true,
11688 &mut y,
11689 &mut u,
11690 &mut v,
11691 base_q_idx,
11692 enable_filter_intra,
11693 allow_screen_content_tools,
11694 allow_intrabc,
11695 &scan32,
11696 &scan16,
11697 &scan8,
11698 &scan4,
11699 tx_select,
11700 reduced_tx_set,
11701 )?;
11702 continue;
11703 }
11704 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
11705 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
11706 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
11707 // `decode_partition` visit order (decodeframe.c):
11708 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
11709 // HORZ_B: top 16x8, BL 8x8, BR 8x8
11710 // VERT_A: TL 8x8, BL 8x8, right 8x16
11711 // VERT_B: left 8x16, TR 8x8, BR 8x8
11712 // The squares go through `decode_leaf8`, the strip through
11713 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
11714 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
11715 // used refuses the non-skip case at this size). Both writers keep
11716 // mi-granular mode/skip/palette records, so a later block's
11717 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
11718 // 16x16 cell.
11719 //
11720 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
11721 // top-right neighbour is the partition's own not-yet-decoded
11722 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
11723 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
11724 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
11725 let arm = part16 - PARTITION_HORZ_A;
11726 bump_ab16(arm);
11727 if part16 == PARTITION_VERT_B {
11728 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
11729 }
11730 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
11731 Some(crate::encode::Reach::vert_ab_partition())
11732 } else {
11733 None
11734 };
11735 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
11736 macro_rules! ab_leaf8 {
11737 ($mi:expr, $prev:expr) => {
11738 decode_leaf8(
11739 &mut dec,
11740 &mut cdfs,
11741 &mut neighbours,
11742 at16,
11743 $mi,
11744 (&scan8, &scan4),
11745 $prev,
11746 &mut y,
11747 &mut u,
11748 &mut v,
11749 base_q_idx,
11750 enable_filter_intra,
11751 allow_screen_content_tools,
11752 allow_intrabc,
11753 tx_select,
11754 reduced_tx_set,
11755 )?
11756 };
11757 }
11758 macro_rules! ab_strip {
11759 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
11760 decode_leaf_rect(
11761 &mut dec,
11762 &mut cdfs,
11763 &mut neighbours,
11764 at16,
11765 $mi,
11766 $bw,
11767 $bh,
11768 $prev,
11769 &mut y,
11770 &mut u,
11771 &mut v,
11772 enable_filter_intra,
11773 allow_screen_content_tools,
11774 base_q_idx,
11775 tx_select,
11776 reduced_tx_set,
11777 )?
11778 };
11779 }
11780 let tl = (mi_row0, mi_col0);
11781 let tr = (mi_row0, mi_col0 + 2);
11782 let bl = (mi_row0 + 2, mi_col0);
11783 let br = (mi_row0 + 2, mi_col0 + 2);
11784 let mut done: Vec<((usize, usize), usize)> = Vec::new();
11785 match part16 {
11786 PARTITION_HORZ_A => {
11787 let m_tl = ab_leaf8!(tl, done.last().copied());
11788 done.push((tl, m_tl));
11789 let m_tr = ab_leaf8!(tr, done.last().copied());
11790 done.push((tr, m_tr));
11791 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
11792 done.push((bl, m_bot));
11793 }
11794 PARTITION_HORZ_B => {
11795 let m_top = ab_strip!(tl, 16, 8, None);
11796 done.push((tl, m_top));
11797 let m_bl = ab_leaf8!(bl, done.last().copied());
11798 done.push((bl, m_bl));
11799 let m_br = ab_leaf8!(br, done.last().copied());
11800 done.push((br, m_br));
11801 }
11802 PARTITION_VERT_A => {
11803 let m_tl = ab_leaf8!(tl, done.last().copied());
11804 done.push((tl, m_tl));
11805 let m_bl = ab_leaf8!(bl, done.last().copied());
11806 done.push((bl, m_bl));
11807 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
11808 done.push((tr, m_right));
11809 }
11810 _ => {
11811 let m_left = ab_strip!(tl, 8, 16, None);
11812 done.push((tl, m_left));
11813 let m_tr = ab_leaf8!(tr, done.last().copied());
11814 done.push((tr, m_tr));
11815 let m_br = ab_leaf8!(br, done.last().copied());
11816 done.push((br, m_br));
11817 }
11818 }
11819 // Same coarse-slot write-back the real SPLIT path takes: the
11820 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
11821 // sub-block on the parent's bottom / right edge (the mi-exact map
11822 // above wins wherever it has an entry).
11823 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
11824 continue;
11825 }
11826 if part16 == PARTITION_HORZ {
11827 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
11828 let (mi_row0, mi_col0) = (
11829 sr as u32 * SUB_MI,
11830 sc as u32 * SUB_MI,
11831 );
11832 let top = (mi_row0 as usize, mi_col0 as usize);
11833 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
11834 let mode_top = decode_leaf_rect(
11835 &mut dec,
11836 &mut cdfs,
11837 &mut neighbours,
11838 at16,
11839 top,
11840 16,
11841 8,
11842 None,
11843 &mut y,
11844 &mut u,
11845 &mut v,
11846 enable_filter_intra,
11847 allow_screen_content_tools,
11848 base_q_idx,
11849 tx_select,
11850 reduced_tx_set,
11851 )?;
11852 let mode_bot = decode_leaf_rect(
11853 &mut dec,
11854 &mut cdfs,
11855 &mut neighbours,
11856 at16,
11857 bot,
11858 16,
11859 8,
11860 Some((top, mode_top)),
11861 &mut y,
11862 &mut u,
11863 &mut v,
11864 enable_filter_intra,
11865 allow_screen_content_tools,
11866 base_q_idx,
11867 tx_select,
11868 reduced_tx_set,
11869 )?;
11870 neighbours.above_mode[sc] = mode_bot;
11871 neighbours.left_mode[sr] = mode_bot;
11872 continue;
11873 }
11874 if part16 == PARTITION_VERT {
11875 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
11876 let (mi_row0, mi_col0) = (
11877 sr as u32 * SUB_MI,
11878 sc as u32 * SUB_MI,
11879 );
11880 let left = (mi_row0 as usize, mi_col0 as usize);
11881 let right = (mi_row0 as usize, mi_col0 as usize + 2);
11882 let mode_left = decode_leaf_rect(
11883 &mut dec,
11884 &mut cdfs,
11885 &mut neighbours,
11886 at16,
11887 left,
11888 8,
11889 16,
11890 None,
11891 &mut y,
11892 &mut u,
11893 &mut v,
11894 enable_filter_intra,
11895 allow_screen_content_tools,
11896 base_q_idx,
11897 tx_select,
11898 reduced_tx_set,
11899 )?;
11900 let mode_right = decode_leaf_rect(
11901 &mut dec,
11902 &mut cdfs,
11903 &mut neighbours,
11904 at16,
11905 right,
11906 8,
11907 16,
11908 Some((left, mode_left)),
11909 &mut y,
11910 &mut u,
11911 &mut v,
11912 enable_filter_intra,
11913 allow_screen_content_tools,
11914 base_q_idx,
11915 tx_select,
11916 reduced_tx_set,
11917 )?;
11918 neighbours.above_mode[sc] = mode_right;
11919 neighbours.left_mode[sr] = mode_right;
11920 continue;
11921 }
11922 if part16 != PARTITION_SPLIT {
11923 return Err(unsupported(
11924 "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)",
11925 ));
11926 }
11927 // A real (non-straddle) SPLIT of a
11928 // whole 16x16 into four 8x8 leaves --
11929 // the same recursion the straddle
11930 // path below already runs when the
11931 // true frame edge forces it, just
11932 // over all four positions instead of
11933 // the one or two the edge leaves.
11934 let (mi_row0, mi_col0) =
11935 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
11936 // Each 8x8 leaf's intra-mode context
11937 // must see its own siblings: the
11938 // bottom-left leaf's ABOVE neighbour
11939 // is leaf 0, not the previously
11940 // decoded leaf 1 (and the bottom-right
11941 // leaf's above is leaf 1, while
11942 // `prev_leaf` only ever carried the
11943 // immediately preceding one). The
11944 // coarse `above_mode`/`left_mode`
11945 // arrays hold one slot per 16x16, so
11946 // the sibling modes are swapped in
11947 // around each leaf call and restored
11948 // after; the loop tail writes the last
11949 // leaf's mode as before.
11950 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
11951 for i in 0..4 {
11952 let (mr, mc) =
11953 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
11954 let leaf_mi = (mr as usize, mc as usize);
11955 let li = i as usize;
11956 let saved_modes =
11957 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
11958 if li >= 2 {
11959 if let Some((below, _)) = sib_modes[li - 2] {
11960 neighbours.above_mode[sc] = below;
11961 }
11962 }
11963 if li % 2 == 1 {
11964 if let Some((_, right)) = sib_modes[li - 1] {
11965 neighbours.left_mode[sr] = right;
11966 }
11967 }
11968 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
11969 let part8 =
11970 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
11971 if std::env::var_os("EC_AV1_TRACE").is_some() {
11972 eprintln!(
11973 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
11974 );
11975 }
11976 let leaf_mode = if part8 == PARTITION_NONE {
11977 decode_leaf8(
11978 &mut dec,
11979 &mut cdfs,
11980 &mut neighbours,
11981 at16,
11982 leaf_mi,
11983 (&scan8, &scan4),
11984 None,
11985 &mut y,
11986 &mut u,
11987 &mut v,
11988 base_q_idx,
11989 enable_filter_intra,
11990 allow_screen_content_tools,
11991 allow_intrabc,
11992 tx_select,
11993 reduced_tx_set,
11994 ).map(|m| (m, m))?
11995 } else if part8 == PARTITION_SPLIT {
11996 decode_leaf_split4(
11997 &mut dec,
11998 &mut cdfs,
11999 &mut neighbours,
12000 at16,
12001 leaf_mi,
12002 &scan4,
12003 None,
12004 &mut y,
12005 &mut u,
12006 &mut v,
12007 base_q_idx,
12008 enable_filter_intra,
12009 allow_intrabc,
12010 reduced_tx_set,
12011 )?
12012 } else if part8 == PARTITION_HORZ
12013 || part8 == PARTITION_VERT
12014 {
12015 decode_leaf_rect8(
12016 &mut dec,
12017 &mut cdfs,
12018 &mut neighbours,
12019 at16,
12020 leaf_mi,
12021 part8 == PARTITION_VERT,
12022 &scan4,
12023 &mut y,
12024 &mut u,
12025 &mut v,
12026 base_q_idx,
12027 enable_filter_intra,
12028 allow_intrabc,
12029 tx_select,
12030 reduced_tx_set,
12031 )?
12032 } else {
12033 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
12034 };
12035 neighbours.above_mode[sc] = saved_modes.0;
12036 neighbours.left_mode[sr] = saved_modes.1;
12037 sib_modes[li] = Some(leaf_mode);
12038 }
12039 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
12040 neighbours.above_mode[sc] = below;
12041 }
12042 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
12043 neighbours.left_mode[sr] = right;
12044 }
12045 continue;
12046 }
12047 // The true edge falls inside this 16x16
12048 // leaf itself (mod-32==8 target sizes,
12049 // lane-av1-rect): one axis only -- an 8x8
12050 // leaf never itself straddles, so the
12051 // block splits cleanly along whichever
12052 // axis is short.
12053 if !has_cols16 && !has_rows16 {
12054 return Err(unsupported(
12055 "a 16x16 block whose true edge cuts through both \
12056 axes needs a rectangular transform this decoder \
12057 does not code yet",
12058 ));
12059 }
12060 if has_cols16 {
12061 dec.symbol_fixed(&gather(
12062 &cdfs.partition_w16[ctx16],
12063 VERT_ALIKE,
12064 ));
12065 } else {
12066 dec.symbol_fixed(&gather(
12067 &cdfs.partition_w16[ctx16],
12068 HORZ_ALIKE,
12069 ));
12070 }
12071 let (mi_row0, mi_col0) =
12072 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
12073 let leaf_positions: Vec<(u32, u32)> = (0..4)
12074 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
12075 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
12076 .collect();
12077 // See the sibling-mode note in the clean
12078 // SPLIT path above.
12079 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
12080 for (mr, mc) in leaf_positions {
12081 let leaf_mi = (mr as usize, mc as usize);
12082 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
12083 as usize;
12084 let saved_modes =
12085 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
12086 if li >= 2 {
12087 if let Some((below, _)) = sib_modes[li - 2] {
12088 neighbours.above_mode[sc] = below;
12089 }
12090 }
12091 if li % 2 == 1 {
12092 if let Some((_, right)) = sib_modes[li - 1] {
12093 neighbours.left_mode[sr] = right;
12094 }
12095 }
12096 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
12097 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
12098 if std::env::var_os("EC_AV1_TRACE").is_some() {
12099 eprintln!(
12100 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
12101 );
12102 }
12103 let leaf_mode = if part8 == PARTITION_NONE {
12104 decode_leaf8(
12105 &mut dec,
12106 &mut cdfs,
12107 &mut neighbours,
12108 at16,
12109 leaf_mi,
12110 (&scan8, &scan4),
12111 None,
12112 &mut y,
12113 &mut u,
12114 &mut v,
12115 base_q_idx,
12116 enable_filter_intra,
12117 allow_screen_content_tools,
12118 allow_intrabc,
12119 tx_select,
12120 reduced_tx_set,
12121 ).map(|m| (m, m))?
12122 } else if part8 == PARTITION_SPLIT {
12123 decode_leaf_split4(
12124 &mut dec,
12125 &mut cdfs,
12126 &mut neighbours,
12127 at16,
12128 leaf_mi,
12129 &scan4,
12130 None,
12131 &mut y,
12132 &mut u,
12133 &mut v,
12134 base_q_idx,
12135 enable_filter_intra,
12136 allow_intrabc,
12137 reduced_tx_set,
12138 )?
12139 } else if part8 == PARTITION_HORZ
12140 || part8 == PARTITION_VERT
12141 {
12142 decode_leaf_rect8(
12143 &mut dec,
12144 &mut cdfs,
12145 &mut neighbours,
12146 at16,
12147 leaf_mi,
12148 part8 == PARTITION_VERT,
12149 &scan4,
12150 &mut y,
12151 &mut u,
12152 &mut v,
12153 base_q_idx,
12154 enable_filter_intra,
12155 allow_intrabc,
12156 tx_select,
12157 reduced_tx_set,
12158 )?
12159 } else {
12160 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
12161 };
12162 neighbours.above_mode[sc] = saved_modes.0;
12163 neighbours.left_mode[sr] = saved_modes.1;
12164 sib_modes[li] = Some(leaf_mode);
12165 }
12166 // `record()`'s `above_mode`/`left_mode`
12167 // write is a no-op at an 8x8 leaf's own
12168 // side, so force the write once the whole
12169 // 16x16 slot's leaves are done, from the
12170 // last leaf (mirrors the writer's r15
12171 // fix).
12172 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
12173 neighbours.above_mode[sc] = below;
12174 }
12175 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
12176 neighbours.left_mode[sr] = right;
12177 }
12178 }
12179 }
12180 PARTITION_HORZ => {
12181 // lane-intradisp r1: two true 32x16 strips.
12182 decode_block_rect(
12183 &mut dec,
12184 &mut cdfs,
12185 &mut neighbours,
12186 at32,
12187 32,
12188 16,
12189 &mut y,
12190 &mut u,
12191 &mut v,
12192 enable_filter_intra,
12193 allow_screen_content_tools,
12194 base_q_idx,
12195 tx_select,
12196 reduced_tx_set,
12197 )?;
12198 decode_block_rect(
12199 &mut dec,
12200 &mut cdfs,
12201 &mut neighbours,
12202 (at32.0 + 1, at32.1),
12203 32,
12204 16,
12205 &mut y,
12206 &mut u,
12207 &mut v,
12208 enable_filter_intra,
12209 allow_screen_content_tools,
12210 base_q_idx,
12211 tx_select,
12212 reduced_tx_set,
12213 )?;
12214 }
12215 PARTITION_VERT => {
12216 // lane-intradisp r1: mirror of PARTITION_HORZ
12217 // above with width/height swapped.
12218 decode_block_rect(
12219 &mut dec,
12220 &mut cdfs,
12221 &mut neighbours,
12222 at32,
12223 16,
12224 32,
12225 &mut y,
12226 &mut u,
12227 &mut v,
12228 enable_filter_intra,
12229 allow_screen_content_tools,
12230 base_q_idx,
12231 tx_select,
12232 reduced_tx_set,
12233 )?;
12234 decode_block_rect(
12235 &mut dec,
12236 &mut cdfs,
12237 &mut neighbours,
12238 (at32.0, at32.1 + 1),
12239 16,
12240 32,
12241 &mut y,
12242 &mut u,
12243 &mut v,
12244 enable_filter_intra,
12245 allow_screen_content_tools,
12246 base_q_idx,
12247 tx_select,
12248 reduced_tx_set,
12249 )?;
12250 }
12251 PARTITION_HORZ_A => {
12252 // lane-part32 r1: two 16x16 squares on top +
12253 // a true 32x16 strip below (mirrors
12254 // decode_inter_block's cd6cb6d HORZ_A: TL,
12255 // TR, bottom strip).
12256 INTRA_HORZ_A_HITS.with(|c| c.set(c.get() + 1));
12257 decode_block(
12258 &mut dec,
12259 &mut cdfs,
12260 &mut neighbours,
12261 at32,
12262 SUB,
12263 TxbSet::Luma16,
12264 TxbSet::Chroma8,
12265 TX16,
12266 TX8,
12267 (&scan16, &scan8),
12268 true,
12269 &mut y,
12270 &mut u,
12271 &mut v,
12272 base_q_idx,
12273 enable_filter_intra,
12274 allow_screen_content_tools,
12275 allow_intrabc,
12276 &scan32,
12277 &scan16,
12278 &scan8,
12279 &scan4,
12280 tx_select,
12281 reduced_tx_set,
12282 )?;
12283 decode_block(
12284 &mut dec,
12285 &mut cdfs,
12286 &mut neighbours,
12287 (at32.0, at32.1 + 1),
12288 SUB,
12289 TxbSet::Luma16,
12290 TxbSet::Chroma8,
12291 TX16,
12292 TX8,
12293 (&scan16, &scan8),
12294 true,
12295 &mut y,
12296 &mut u,
12297 &mut v,
12298 base_q_idx,
12299 enable_filter_intra,
12300 allow_screen_content_tools,
12301 allow_intrabc,
12302 &scan32,
12303 &scan16,
12304 &scan8,
12305 &scan4,
12306 tx_select,
12307 reduced_tx_set,
12308 )?;
12309 decode_block_rect(
12310 &mut dec,
12311 &mut cdfs,
12312 &mut neighbours,
12313 (at32.0 + 1, at32.1),
12314 32,
12315 16,
12316 &mut y,
12317 &mut u,
12318 &mut v,
12319 enable_filter_intra,
12320 allow_screen_content_tools,
12321 base_q_idx,
12322 tx_select,
12323 reduced_tx_set,
12324 )?;
12325 }
12326 PARTITION_HORZ_B => {
12327 // lane-part32 r1: a true 32x16 strip on top +
12328 // two 16x16 squares below (mirrors HORZ_A
12329 // with the strip/squares order flipped, same
12330 // shape as libaom decode_partition's HORZ_B).
12331 INTRA_HORZ_B_HITS.with(|c| c.set(c.get() + 1));
12332 decode_block_rect(
12333 &mut dec,
12334 &mut cdfs,
12335 &mut neighbours,
12336 at32,
12337 32,
12338 16,
12339 &mut y,
12340 &mut u,
12341 &mut v,
12342 enable_filter_intra,
12343 allow_screen_content_tools,
12344 base_q_idx,
12345 tx_select,
12346 reduced_tx_set,
12347 )?;
12348 decode_block(
12349 &mut dec,
12350 &mut cdfs,
12351 &mut neighbours,
12352 (at32.0 + 1, at32.1),
12353 SUB,
12354 TxbSet::Luma16,
12355 TxbSet::Chroma8,
12356 TX16,
12357 TX8,
12358 (&scan16, &scan8),
12359 true,
12360 &mut y,
12361 &mut u,
12362 &mut v,
12363 base_q_idx,
12364 enable_filter_intra,
12365 allow_screen_content_tools,
12366 allow_intrabc,
12367 &scan32,
12368 &scan16,
12369 &scan8,
12370 &scan4,
12371 tx_select,
12372 reduced_tx_set,
12373 )?;
12374 decode_block(
12375 &mut dec,
12376 &mut cdfs,
12377 &mut neighbours,
12378 (at32.0 + 1, at32.1 + 1),
12379 SUB,
12380 TxbSet::Luma16,
12381 TxbSet::Chroma8,
12382 TX16,
12383 TX8,
12384 (&scan16, &scan8),
12385 true,
12386 &mut y,
12387 &mut u,
12388 &mut v,
12389 base_q_idx,
12390 enable_filter_intra,
12391 allow_screen_content_tools,
12392 allow_intrabc,
12393 &scan32,
12394 &scan16,
12395 &scan8,
12396 &scan4,
12397 tx_select,
12398 reduced_tx_set,
12399 )?;
12400 }
12401 PARTITION_VERT_A => {
12402 // lane-part32 r1: mirror of HORZ_A with
12403 // width/height swapped (TL, BL, right 16x32
12404 // strip).
12405 INTRA_VERT_A_HITS.with(|c| c.set(c.get() + 1));
12406 let _vert_ab = crate::encode::Reach::vert_ab_partition();
12407 decode_block(
12408 &mut dec,
12409 &mut cdfs,
12410 &mut neighbours,
12411 at32,
12412 SUB,
12413 TxbSet::Luma16,
12414 TxbSet::Chroma8,
12415 TX16,
12416 TX8,
12417 (&scan16, &scan8),
12418 true,
12419 &mut y,
12420 &mut u,
12421 &mut v,
12422 base_q_idx,
12423 enable_filter_intra,
12424 allow_screen_content_tools,
12425 allow_intrabc,
12426 &scan32,
12427 &scan16,
12428 &scan8,
12429 &scan4,
12430 tx_select,
12431 reduced_tx_set,
12432 )?;
12433 decode_block(
12434 &mut dec,
12435 &mut cdfs,
12436 &mut neighbours,
12437 (at32.0 + 1, at32.1),
12438 SUB,
12439 TxbSet::Luma16,
12440 TxbSet::Chroma8,
12441 TX16,
12442 TX8,
12443 (&scan16, &scan8),
12444 true,
12445 &mut y,
12446 &mut u,
12447 &mut v,
12448 base_q_idx,
12449 enable_filter_intra,
12450 allow_screen_content_tools,
12451 allow_intrabc,
12452 &scan32,
12453 &scan16,
12454 &scan8,
12455 &scan4,
12456 tx_select,
12457 reduced_tx_set,
12458 )?;
12459 decode_block_rect(
12460 &mut dec,
12461 &mut cdfs,
12462 &mut neighbours,
12463 (at32.0, at32.1 + 1),
12464 16,
12465 32,
12466 &mut y,
12467 &mut u,
12468 &mut v,
12469 enable_filter_intra,
12470 allow_screen_content_tools,
12471 base_q_idx,
12472 tx_select,
12473 reduced_tx_set,
12474 )?;
12475 }
12476 PARTITION_VERT_B => {
12477 // lane-part32 r1: a true 16x32 strip on the
12478 // left + two 16x16 squares on the right
12479 // (libaom decode_partition VERT_B: left
12480 // strip, TR, BR).
12481 INTRA_VERT_B_HITS.with(|c| c.set(c.get() + 1));
12482 let _vert_ab = crate::encode::Reach::vert_ab_partition();
12483 decode_block_rect(
12484 &mut dec,
12485 &mut cdfs,
12486 &mut neighbours,
12487 at32,
12488 16,
12489 32,
12490 &mut y,
12491 &mut u,
12492 &mut v,
12493 enable_filter_intra,
12494 allow_screen_content_tools,
12495 base_q_idx,
12496 tx_select,
12497 reduced_tx_set,
12498 )?;
12499 decode_block(
12500 &mut dec,
12501 &mut cdfs,
12502 &mut neighbours,
12503 (at32.0, at32.1 + 1),
12504 SUB,
12505 TxbSet::Luma16,
12506 TxbSet::Chroma8,
12507 TX16,
12508 TX8,
12509 (&scan16, &scan8),
12510 true,
12511 &mut y,
12512 &mut u,
12513 &mut v,
12514 base_q_idx,
12515 enable_filter_intra,
12516 allow_screen_content_tools,
12517 allow_intrabc,
12518 &scan32,
12519 &scan16,
12520 &scan8,
12521 &scan4,
12522 tx_select,
12523 reduced_tx_set,
12524 )?;
12525 decode_block(
12526 &mut dec,
12527 &mut cdfs,
12528 &mut neighbours,
12529 (at32.0 + 1, at32.1 + 1),
12530 SUB,
12531 TxbSet::Luma16,
12532 TxbSet::Chroma8,
12533 TX16,
12534 TX8,
12535 (&scan16, &scan8),
12536 true,
12537 &mut y,
12538 &mut u,
12539 &mut v,
12540 base_q_idx,
12541 enable_filter_intra,
12542 allow_screen_content_tools,
12543 allow_intrabc,
12544 &scan32,
12545 &scan16,
12546 &scan8,
12547 &scan4,
12548 tx_select,
12549 reduced_tx_set,
12550 )?;
12551 }
12552 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
12553 // lane-tx64x16 r3: the 1:4 pair at the 32x32
12554 // level -- four 32x8 (or 8x32) strips in
12555 // raster order, `quarter_step` = 2 mi, with
12556 // libaom `decode_partition`'s own `i > 0`
12557 // frame-edge break.
12558 let horz = part32 == PARTITION_HORZ_4;
12559 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
12560 let mut prev: Option<((usize, usize), usize)> = None;
12561 for i in 0..4 {
12562 let strip_mi = if horz {
12563 (base_mi.0 + i * 2, base_mi.1)
12564 } else {
12565 (base_mi.0, base_mi.1 + i * 2)
12566 };
12567 if i > 0
12568 && (strip_mi.0 >= mi_rows as usize
12569 || strip_mi.1 >= mi_cols as usize)
12570 {
12571 break;
12572 }
12573 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
12574 let (mode, _uv) = decode_block_rect4(
12575 &mut dec,
12576 &mut cdfs,
12577 &mut neighbours,
12578 strip_mi,
12579 bw,
12580 bh,
12581 prev,
12582 &mut y,
12583 &mut u,
12584 &mut v,
12585 enable_filter_intra,
12586 allow_screen_content_tools,
12587 base_q_idx,
12588 tx_select,
12589 )?;
12590 prev = Some((strip_mi, mode));
12591 }
12592 }
12593 _ => {
12594 return Err(unsupported(format!(
12595 "a 32x32 partition type this decoder does not code (value={part32})"
12596 )));
12597 }
12598 }
12599 }
12600 }
12601 PARTITION_HORZ => {
12602 // lane-sbpart r2: two true 64x32 strips.
12603 decode_block_rect64(
12604 &mut dec,
12605 &mut cdfs,
12606 &mut neighbours,
12607 at,
12608 64,
12609 32,
12610 &mut y,
12611 &mut u,
12612 &mut v,
12613 enable_filter_intra,
12614 allow_screen_content_tools,
12615 base_q_idx,
12616 tx_select,
12617 reduced_tx_set,
12618 )?;
12619 decode_block_rect64(
12620 &mut dec,
12621 &mut cdfs,
12622 &mut neighbours,
12623 (at.0 + 2, at.1),
12624 64,
12625 32,
12626 &mut y,
12627 &mut u,
12628 &mut v,
12629 enable_filter_intra,
12630 allow_screen_content_tools,
12631 base_q_idx,
12632 tx_select,
12633 reduced_tx_set,
12634 )?;
12635 }
12636 PARTITION_VERT => {
12637 // lane-sbpart r2: mirror of PARTITION_HORZ above with
12638 // width/height swapped.
12639 decode_block_rect64(
12640 &mut dec,
12641 &mut cdfs,
12642 &mut neighbours,
12643 at,
12644 32,
12645 64,
12646 &mut y,
12647 &mut u,
12648 &mut v,
12649 enable_filter_intra,
12650 allow_screen_content_tools,
12651 base_q_idx,
12652 tx_select,
12653 reduced_tx_set,
12654 )?;
12655 decode_block_rect64(
12656 &mut dec,
12657 &mut cdfs,
12658 &mut neighbours,
12659 (at.0, at.1 + 2),
12660 32,
12661 64,
12662 &mut y,
12663 &mut u,
12664 &mut v,
12665 enable_filter_intra,
12666 allow_screen_content_tools,
12667 base_q_idx,
12668 tx_select,
12669 reduced_tx_set,
12670 )?;
12671 }
12672 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
12673 // lane-part32 r4: the four superblock-level AB arms, each
12674 // two 32x32 squares plus one 64x32/32x64 strip, in
12675 // libaom's own `decode_partition` order (decodeframe.c:
12676 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
12677 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
12678 // TR, BR). The pieces are exactly the ones already proven
12679 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
12680 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
12681 SB_AB_HITS.with(|c| {
12682 let mut h = c.get();
12683 h[part - PARTITION_HORZ_A] += 1;
12684 c.set(h);
12685 });
12686 // lane-part32 r5: only the two VERTICAL arms reorder the
12687 // square sub-blocks (TL, BL, TR, BR), so only they switch
12688 // libaom's `has_tr`/`has_bl` tables.
12689 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
12690 .then(crate::encode::Reach::vert_ab_partition);
12691 macro_rules! square32 {
12692 ($at:expr) => {
12693 decode_block(
12694 &mut dec,
12695 &mut cdfs,
12696 &mut neighbours,
12697 $at,
12698 BLOCK,
12699 TxbSet::Luma32,
12700 TxbSet::Chroma16,
12701 TX32,
12702 TX16,
12703 (&scan32, &scan16),
12704 true,
12705 &mut y,
12706 &mut u,
12707 &mut v,
12708 base_q_idx,
12709 enable_filter_intra,
12710 allow_screen_content_tools,
12711 allow_intrabc,
12712 &scan32,
12713 &scan16,
12714 &scan8,
12715 &scan4,
12716 tx_select,
12717 reduced_tx_set,
12718 )?
12719 };
12720 }
12721 macro_rules! strip64 {
12722 ($at:expr, $bw:expr, $bh:expr) => {
12723 decode_block_rect64(
12724 &mut dec,
12725 &mut cdfs,
12726 &mut neighbours,
12727 $at,
12728 $bw,
12729 $bh,
12730 &mut y,
12731 &mut u,
12732 &mut v,
12733 enable_filter_intra,
12734 allow_screen_content_tools,
12735 base_q_idx,
12736 tx_select,
12737 reduced_tx_set,
12738 )?
12739 };
12740 }
12741 let (br, bc) = (at.0 + 2, at.1 + 2);
12742 match part {
12743 PARTITION_HORZ_A => {
12744 square32!(at);
12745 square32!((at.0, bc));
12746 strip64!((br, at.1), 64, 32);
12747 }
12748 PARTITION_HORZ_B => {
12749 strip64!(at, 64, 32);
12750 square32!((br, at.1));
12751 square32!((br, bc));
12752 }
12753 PARTITION_VERT_A => {
12754 square32!(at);
12755 square32!((br, at.1));
12756 strip64!((at.0, bc), 32, 64);
12757 }
12758 _ => {
12759 strip64!(at, 32, 64);
12760 square32!((at.0, bc));
12761 square32!((br, bc));
12762 }
12763 }
12764 }
12765 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
12766 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
12767 // 16x64) strips in raster order. `decode_partition`
12768 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
12769 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
12770 // frame edge for `i > 0`, so a partial superblock codes
12771 // only the strips whose origin is inside the frame.
12772 let horz = part == PARTITION_HORZ_4;
12773 for i in 0..4 {
12774 let step_mi = i * (SB_MI as usize / 4);
12775 let (this_r_mi, this_c_mi) = if horz {
12776 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
12777 } else {
12778 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
12779 };
12780 if i > 0
12781 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
12782 {
12783 break;
12784 }
12785 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
12786 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
12787 decode_block_rect64(
12788 &mut dec,
12789 &mut cdfs,
12790 &mut neighbours,
12791 strip_at,
12792 bw,
12793 bh,
12794 &mut y,
12795 &mut u,
12796 &mut v,
12797 enable_filter_intra,
12798 allow_screen_content_tools,
12799 base_q_idx,
12800 tx_select,
12801 reduced_tx_set,
12802 )?;
12803 }
12804 }
12805 _ => {
12806 return Err(unsupported(
12807 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
12808 ));
12809 }
12810 }
12811 }
12812 }
12813
12814 if tile_num == tile_info.context_update_tile_id {
12815 result_cdfs = cdfs;
12816 }
12817 }
12818
12819 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
12820 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
12821 // that isolate whether a decode-order frame's mismatch already exists
12822 // in reconstruction (this dump) vs is introduced by the loop filter
12823 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
12824 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
12825 use std::io::Write;
12826 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12827 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12828 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
12829 let _ = f.write_all(&narrow(&y));
12830 let _ = f.write_all(&narrow(&u));
12831 let _ = f.write_all(&narrow(&v));
12832 }
12833 } else {
12834 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12835 }
12836 if let Ok(path) = std::env::var("EC_AV1_PREFILT_WIDE_DUMP") {
12837 use std::io::Write;
12838 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12839 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12840 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
12841 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
12842 for row in 0..plane.true_height {
12843 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
12844 }
12845 out
12846 };
12847 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12848 let _ = f.write_all(&crop_wide(&y));
12849 let _ = f.write_all(&crop_wide(&u));
12850 let _ = f.write_all(&crop_wide(&v));
12851 }
12852 }
12853 apply_deblock(
12854 &mut y,
12855 &mut u,
12856 &mut v,
12857 loop_filter,
12858 &neighbours,
12859 frame_width as usize,
12860 frame_height as usize,
12861 );
12862 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
12863 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
12864 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
12865 // dump above these bisect WHICH filter stage introduced a mismatch.
12866 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
12867 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
12868 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
12869 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
12870
12871 let (fw, fh) = (frame_width as usize, frame_height as usize);
12872 if fw == width && fh == height {
12873 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
12874 return Ok((
12875 Picture {
12876 width,
12877 height,
12878 y: y.data,
12879 u: u.data,
12880 v: v.data,
12881 },
12882 result_cdfs,
12883 ));
12884 }
12885 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
12886 let mut out = Vec::with_capacity(w * h);
12887 for row in 0..h {
12888 out.extend(plane.data[row * plane.width..][..w].iter().copied());
12889 }
12890 out
12891 };
12892 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
12893 // is the real reconstructed extent -- columns `[fw, true_width)` hold
12894 // genuine decoded samples (the last coding block straddles the frame
12895 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
12896 // libaom's superres upscale runs on that buffer's own border-extended
12897 // margin, so it reads those real columns, not a synthetic replicate of
12898 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
12899 // aomenc 43->64 stream pinned column-by-column against libaom's own
12900 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
12901 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
12902 // decoder used before was off by 1 at the columns the tap window
12903 // reaches into that real margin; `None` when there is no margin (this
12904 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
12905 // non-superres frame whose width just isn't 32-block aligned).
12906 LAST_FRAME_WIDE_MARGIN.with(|m| {
12907 *m.borrow_mut() = if true_width > fw || true_height > fh {
12908 let yc = crop(&y, true_width, true_height);
12909 if let Ok(path) = std::env::var("EC_AV1_MARGIN_DUMP") {
12910 use std::io::Write;
12911 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12912 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12913 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12914 // corner-cut: this diagnostic dump stays 8-bit-narrowed
12915 // regardless of the stream's real bit depth (debug-only,
12916 // never read by a gate); widen if a >8-bit margin dump
12917 // is ever needed.
12918 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
12919 }
12920 }
12921 Some(Picture {
12922 width: true_width,
12923 height: true_height,
12924 y: yc,
12925 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
12926 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
12927 })
12928 } else {
12929 None
12930 }
12931 });
12932 Ok((
12933 Picture {
12934 width: fw,
12935 height: fh,
12936 y: crop(&y, fw, fh),
12937 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
12938 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
12939 },
12940 result_cdfs,
12941 ))
12942}
12943
12944/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
12945/// -- `above`/`left` are the neighbour's own resolved index for this
12946/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
12947/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
12948/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
12949/// block itself has a second reference) -- lane-av1idx: a stale "this
12950/// decoder never codes a compound reference" assumption baked this to
12951/// always-0, which desynced the CDF context bucket (not the decoded value
12952/// outright, hence small pixel deltas rather than a hard desync) the moment
12953/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
12954/// filter frame.
12955fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
12956 let base = dir * 8 + if is_compound { 4 } else { 0 };
12957 let term = if left == above {
12958 left
12959 } else if left == 3 {
12960 above
12961 } else if above == 3 {
12962 left
12963 } else {
12964 3
12965 };
12966 base + term as usize
12967}
12968
12969/// Resolves the interpolation filter kernel(s) an inter block's motion
12970/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
12971/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
12972/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
12973/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
12974/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
12975/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
12976/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
12977/// which forces `EIGHTTAP` without reading anything.
12978#[allow(clippy::too_many_arguments)]
12979fn resolve_interp_filter(
12980 dec: &mut SymbolDecoder,
12981 cdfs: &mut Cdfs,
12982 interp_fixed: Option<mc::InterpFilterKind>,
12983 enable_dual_filter: bool,
12984 force_regular: bool,
12985 above: [u8; 2],
12986 left: [u8; 2],
12987 is_compound: bool,
12988) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
12989 if let Some(kind) = interp_fixed {
12990 return (kind, kind, [3, 3]);
12991 }
12992 if force_regular {
12993 return (
12994 mc::InterpFilterKind::Regular,
12995 mc::InterpFilterKind::Regular,
12996 [0, 0],
12997 );
12998 }
12999 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
13000 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
13001 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
13002 // "horizontal then vertical" despite `predict_with_filters`' own
13003 // `h_kind`/`v_kind` argument order, which is why this function returns
13004 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
13005 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
13006 if std::env::var_os("EC_AV1_IFDBG").is_some() {
13007 eprintln!(
13008 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
13009 &cdfs.switchable_interp[ctx0][..3]
13010 );
13011 }
13012 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
13013 let sym1 = if enable_dual_filter {
13014 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
13015 if std::env::var_os("EC_AV1_IFDBG").is_some() {
13016 eprintln!(
13017 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
13018 &cdfs.switchable_interp[ctx1][..3]
13019 );
13020 }
13021 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
13022 } else {
13023 sym0
13024 };
13025 (
13026 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
13027 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
13028 [sym0, sym1],
13029 )
13030}
13031
13032/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
13033/// duplicating [`crate::tile`]'s private copy of the same rule.
13034pub(crate) fn intra_inter_ctx(
13035 has_above: bool,
13036 has_left: bool,
13037 above_inter: bool,
13038 left_inter: bool,
13039) -> usize {
13040 match (has_above, has_left) {
13041 (true, true) => {
13042 let (above_intra, left_intra) = (!above_inter, !left_inter);
13043 if above_intra && left_intra {
13044 3
13045 } else {
13046 usize::from(above_intra || left_intra)
13047 }
13048 }
13049 (true, false) => 2 * usize::from(!above_inter),
13050 (false, true) => 2 * usize::from(!left_inter),
13051 (false, false) => 0,
13052 }
13053}
13054
13055/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
13056/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
13057/// bits start counting from.
13058fn mv_class_base(class: usize) -> i32 {
13059 if class == 0 { 0 } else { 2i32 << (class + 2) }
13060}
13061
13062/// One motion vector component's non-zero diff (spec 5.11.32
13063/// `read_mv_component`), the inverse of [`crate::tile`]'s private
13064/// `write_mv_component`.
13065fn read_mv_component(
13066 dec: &mut SymbolDecoder,
13067 c: &mut MvComponentCdfs,
13068 allow_high_precision_mv: bool,
13069 force_integer_mv: bool,
13070) -> i32 {
13071 let sign = dec.symbol(&mut c.sign);
13072 let class = dec.symbol(&mut c.class);
13073 let local = if class == 0 {
13074 let bit = dec.symbol(&mut c.class0_bit);
13075 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
13076 // forces integer motion vectors -- implicitly `3` (the top
13077 // fractional value) rather than read, else every symbol after it
13078 // in the tile desyncs by one read.
13079 let fr = if force_integer_mv {
13080 3
13081 } else {
13082 dec.symbol(&mut c.class0_fr[bit])
13083 };
13084 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
13085 // high-precision motion vectors, else implicitly 1 (the low bit
13086 // stays at half-pel precision) -- this crate's own writer always
13087 // leaves the flag off, but a foreign stream can set it per frame.
13088 let hp = if allow_high_precision_mv {
13089 dec.symbol(&mut c.class0_hp)
13090 } else {
13091 1
13092 };
13093 (bit << 3) | (fr << 1) | hp
13094 } else {
13095 let mut d = 0;
13096 for i in 0..class {
13097 d |= dec.symbol(&mut c.bit[i]) << i;
13098 }
13099 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
13100 // `mv_class0_fr` above.
13101 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
13102 let hp = if allow_high_precision_mv {
13103 dec.symbol(&mut c.hp)
13104 } else {
13105 1
13106 };
13107 (d << 3) | (fr << 1) | hp
13108 };
13109 let mag = mv_class_base(class) + local as i32 + 1;
13110 if sign == 1 { -mag } else { mag }
13111}
13112
13113/// A motion vector coded as a residual against `pred` (spec 5.11.32
13114/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
13115fn read_mv(
13116 dec: &mut SymbolDecoder,
13117 mv_comp: &mut [MvComponentCdfs; 2],
13118 mv_joint: &mut [u16; 5],
13119 pred: (i32, i32),
13120 allow_high_precision_mv: bool,
13121 force_integer_mv: bool,
13122) -> (i32, i32) {
13123 let joint = dec.symbol(mv_joint);
13124 let mut diff = (0, 0);
13125 if joint == 2 || joint == 3 {
13126 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
13127 }
13128 if joint == 1 || joint == 3 {
13129 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
13130 }
13131 (pred.0 + diff.0, pred.1 + diff.1)
13132}
13133
13134/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
13135/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
13136///
13137/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
13138/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
13139/// when that is zero, or -- when both are -- the fixed fallback DV one
13140/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
13141/// left when this is the tile's first superblock row. The predictor is then
13142/// rounded to full pel, and the difference reads off the *dv* nmv context
13143/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
13144/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
13145/// symbol is coded for a DV, so none of this can move the bitstream
13146/// position -- only the reconstructed vector.
13147fn read_intrabc_dv(
13148 dec: &mut SymbolDecoder,
13149 cdfs: &mut Cdfs,
13150 mi_r: usize,
13151 mi_c: usize,
13152 side: usize,
13153) -> (i32, i32) {
13154 const INTRABC_DELAY_PIXELS: i32 = 256;
13155 let n4 = side / MI;
13156 let stack_pred = INTRABC_MI_GRID.with(|g| {
13157 let g = g.borrow();
13158 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
13159 let stack = crate::mvstack::find_mv_stack(
13160 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
13161 *mi_cols, *mi_rows,
13162 );
13163 if stack.nearest_mv == (0, 0) {
13164 stack.near_mv
13165 } else {
13166 stack.nearest_mv
13167 }
13168 })
13169 });
13170 let mut pred = stack_pred.unwrap_or((0, 0));
13171 if pred == (0, 0) {
13172 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
13173 // single-tile-row case every intrabc gate stream is).
13174 let sb_px = SB_MI as i32 * MI as i32;
13175 pred = if mi_r < SB_MI as usize {
13176 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
13177 } else {
13178 (-sb_px * 8, 0)
13179 };
13180 }
13181 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
13182 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
13183 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
13184}
13185
13186/// A 1/8-pel motion vector component converted to the 1/16-pel offset
13187/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
13188/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
13189fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
13190 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
13191}
13192
13193impl PlaneBuf {
13194 /// Adds `residual` onto an already-computed `prediction` (motion
13195 /// compensation's output, rather than [`predict`]'s intra one), writing
13196 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
13197 /// counterpart of [`PlaneBuf::reconstruct`].
13198 fn reconstruct_mc(
13199 &mut self,
13200 x: usize,
13201 y: usize,
13202 side: usize,
13203 prediction: &[u16],
13204 residual: &[i32],
13205 ) {
13206 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
13207 }
13208
13209 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
13210 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
13211 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
13212 /// VERT strip is predicted at its enclosing square `side` (matching
13213 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
13214 /// but only its own true `w`x`h` footprint is committed to the plane, so
13215 /// two strips sharing a square's coordinate origin never clobber each
13216 /// other's real pixels.
13217 fn reconstruct_mc_rect(
13218 &mut self,
13219 x: usize,
13220 y: usize,
13221 side: usize,
13222 w: usize,
13223 h: usize,
13224 prediction: &[u16],
13225 residual: &[i32],
13226 ) {
13227 for row in 0..h {
13228 for col in 0..w {
13229 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
13230 .clamp(0, crate::decode::sample_max()) as u16;
13231 self.data[(y + row) * self.width + x + col] = sample;
13232 }
13233 }
13234 }
13235}
13236
13237/// Reads one inter-coded plane's transform block and reconstructs it by
13238/// adding its residual onto a motion-compensated `prediction` -- the inter
13239/// counterpart of [`read_plane`] (every inter transform this decoder reads is
13240/// `side`-square with no oversized-64 case, so there is no padded-grid
13241/// branch to mirror).
13242#[allow(clippy::too_many_arguments)]
13243fn read_inter_plane(
13244 dec: &mut SymbolDecoder,
13245 cdfs: &mut Cdfs,
13246 set: TxbSet,
13247 scan: &[u16],
13248 plane_idx: usize,
13249 around: (bool, bool, i32),
13250 tx_mode: usize,
13251 plane: &mut PlaneBuf,
13252 x: usize,
13253 y: usize,
13254 side: usize,
13255 base_q_idx: u8,
13256 prediction: &[u16],
13257 // lane-chromau: this block's own luma transform's *actual coded*
13258 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
13259 // chroma plane never codes its own `tx_type` symbol, but (unlike an
13260 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
13261 // the colocated luma transform's coded type verbatim, clamped back to
13262 // `DCT_DCT` at the chroma tx sizes the spec forces DCT-only
13263 // (`av1_get_ext_tx_set_type`: `tx_size_sqr_up >= TX_32X32`, i.e. this
13264 // function's own `side >= 32`). `None` for the luma call itself
13265 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
13266 // `DCT_DCT` default at 32-point+) already resolves it without help.
13267 inherited_luma_tx_type: Option<TxType>,
13268 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
13269 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
13270 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
13271 // transform every non-var-tx caller reads, whose plane-0 context is the
13272 // lone-transform-unit 0.
13273 luma_skip_ctx: Option<usize>,
13274) -> Result<(Vec<i32>, TxType)> {
13275 let skip_ctx = if plane_idx == 0 {
13276 luma_skip_ctx.unwrap_or(0)
13277 } else {
13278 usize::from(around.0) + usize::from(around.1)
13279 };
13280 let mut coding = cdfs.txb(set, tx_mode);
13281 let default_tx_type = match inherited_luma_tx_type {
13282 Some(t) if side < 32 => t,
13283 _ => TxType::DctDct,
13284 };
13285 let (grid, tx_type) = read_coeffs(
13286 dec,
13287 &mut coding,
13288 scan,
13289 skip_ctx,
13290 dc_sign_ctx(around.2),
13291 default_tx_type,
13292 None,
13293 )?;
13294 note_chroma_class1(plane_idx, tx_type);
13295 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
13296 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
13297 // caller hands the 32-point `scan` there, and the coded corner goes into
13298 // the top-left of the true `side`-sized grid before dequantization
13299 // (dqDenom is keyed by the true size, not the corner's), mirroring
13300 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
13301 // this decoder codes has `tx_side == side`, so this is inert below 64.
13302 let tx_side = side.min(32);
13303 let grid = if tx_side == side {
13304 grid
13305 } else {
13306 let mut full = vec![0i32; side * side];
13307 for row in 0..tx_side {
13308 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
13309 }
13310 full
13311 };
13312 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
13313 let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
13314 plane.reconstruct_mc(x, y, side, prediction, &residual);
13315 Ok((grid, tx_type))
13316}
13317
13318/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
13319/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
13320/// `reference_select` set before this is ever called, so that read is never
13321/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
13322/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
13323fn read_single_ref(
13324 dec: &mut SymbolDecoder,
13325 cdfs: &mut Cdfs,
13326 above_ref: i8,
13327 above_ref1: Option<i8>,
13328 left_ref: i8,
13329 left_ref1: Option<i8>,
13330) -> i8 {
13331 let above = (above_ref > 0).then_some(above_ref);
13332 let left = (left_ref > 0).then_some(left_ref);
13333 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
13334 let ref_frame = if p1 == 1 {
13335 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
13336 if p2 == 1 {
13337 ALTREF_FRAME
13338 } else {
13339 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
13340 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
13341 }
13342 } else {
13343 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
13344 if p3 == 1 {
13345 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
13346 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
13347 } else {
13348 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
13349 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
13350 }
13351 };
13352 if ref_frame != LAST_FRAME {
13353 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
13354 let c = match ref_frame {
13355 LAST2_FRAME => &LAST2_HITS,
13356 LAST3_FRAME => &LAST3_HITS,
13357 GOLDEN_FRAME => &GOLDEN_HITS,
13358 BWDREF_FRAME => &BWDREF_HITS,
13359 ALTREF2_FRAME => &ALTREF2_HITS,
13360 ALTREF_FRAME => &ALTREF_HITS,
13361 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
13362 };
13363 c.with(|v| v.set(v.get() + 1));
13364 }
13365 ref_frame
13366}
13367
13368/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
13369/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
13370/// `reference_select` header bit lets a block choose per-block instead of
13371/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
13372/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
13373/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
13374/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
13375/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
13376/// Resolves a compound reference's own planes -- the same `ref_frame ==
13377/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
13378/// [`decode_inter_block`]'s single-ref path already does, factored out so
13379/// the compound path can call it twice (lane-av1comp).
13380fn ref_planes<'a>(
13381 ref_frame: i8,
13382 ref_y: &'a PlaneBuf,
13383 ref_u: &'a PlaneBuf,
13384 ref_v: &'a PlaneBuf,
13385 other_refs: &'a RefSlots,
13386) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
13387 if ref_frame == LAST_FRAME {
13388 Ok((ref_y, ref_u, ref_v))
13389 } else {
13390 match other_refs[ref_frame as usize] {
13391 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
13392 None => Err(unsupported(
13393 "a reference frame selected with no picture at this frame's own \
13394 ref_frame_idx slot for it",
13395 )),
13396 }
13397 }
13398}
13399
13400/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
13401/// directly above this block's own column span, one bordering block at a
13402/// time (stepping by that neighbour's own `MiInfo::size`, which is always
13403/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
13404/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
13405/// unit at a time, and does not itself count as a step). `max_neighbors`
13406/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
13407/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
13408/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
13409/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
13410/// not ported -- no block this decoder codes is narrower than 8px, so it
13411/// never fires here regardless of what a neighbour's own decoder was.
13412fn overlappable_above(
13413 grid: &MiGrid,
13414 mi_row: usize,
13415 mi_col: usize,
13416 bw4: usize,
13417 mi_cols: usize,
13418 max_neighbors: usize,
13419) -> Vec<(usize, usize, MiInfo)> {
13420 let mut out = Vec::new();
13421 if mi_row == 0 {
13422 return out;
13423 }
13424 let end_col = (mi_col + bw4).min(mi_cols);
13425 let mut col = mi_col;
13426 while col < end_col && out.len() < max_neighbors {
13427 let cell = grid.get(mi_row - 1, col);
13428 let step = cell.map_or(1, |c| c.size).max(1);
13429 if let Some(info) = cell {
13430 if info.is_inter {
13431 out.push((col - mi_col, step.min(end_col - col), *info));
13432 }
13433 }
13434 col += step;
13435 }
13436 out
13437}
13438
13439/// `foreach_overlappable_nb_left`'s left-column mirror of
13440/// [`overlappable_above`] -- see its doc for the shared corner-cut.
13441fn overlappable_left(
13442 grid: &MiGrid,
13443 mi_row: usize,
13444 mi_col: usize,
13445 bh4: usize,
13446 mi_rows: usize,
13447 max_neighbors: usize,
13448) -> Vec<(usize, usize, MiInfo)> {
13449 let mut out = Vec::new();
13450 if mi_col == 0 {
13451 return out;
13452 }
13453 let end_row = (mi_row + bh4).min(mi_rows);
13454 let mut row = mi_row;
13455 while row < end_row && out.len() < max_neighbors {
13456 let cell = grid.get(row, mi_col - 1);
13457 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
13458 // width (8) would swallow the strip below it.
13459 let step = cell.map_or(1, |c| c.size_h).max(1);
13460 if let Some(info) = cell {
13461 if info.is_inter {
13462 out.push((row - mi_row, step.min(end_row - row), *info));
13463 }
13464 }
13465 row += step;
13466 }
13467 out
13468}
13469
13470/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples`
13471/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2:
13472/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128`
13473/// libaom's mask loop runs one level further and strips the top-right sample
13474/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame
13475/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates
13476/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is
13477/// the block's own side in 4x4 (`mi`) units (square inter leaves only here).
13478fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
13479 crate::mvstack::has_top_right(mi_row, mi_col, bs, bs)
13480}
13481
13482/// `av1_findSamples` (`mvref_common.c`), full port: the up to
13483/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
13484/// samples (`record_samples`) that share this block's own single reference
13485/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
13486/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
13487/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
13488/// libaom are also mi units of that same square side here). Each sample's
13489/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
13490/// come from the *neighbour* cell's own coded size, not this block's.
13491#[allow(clippy::too_many_arguments)]
13492fn find_samples(
13493 grid: &MiGrid,
13494 mi_row: usize,
13495 mi_col: usize,
13496 bw4: usize,
13497 bh4: usize,
13498 mi_cols: usize,
13499 mi_rows: usize,
13500 ref_frame: i8,
13501) -> Vec<crate::warp::Sample> {
13502 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
13503 let up_available = mi_row > 0;
13504 let left_available = mi_col > 0;
13505 let mut samples = Vec::with_capacity(MAX);
13506 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
13507 let mut do_tl = true;
13508 let mut do_tr = true;
13509 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
13510 let nb_bw = (info.size * 4) as i32;
13511 // lane-rect r2: the neighbour's own true height -- a rect strip
13512 // neighbour donates its sample at ITS center (aom pts y=-72 for a
13513 // 32x16 above strip; the square assumption put it at -136).
13514 let nb_bh = (info.size_h * 4) as i32;
13515 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
13516 };
13517
13518 'outer: {
13519 if up_available {
13520 let above = grid.get(mi_row - 1, mi_col);
13521 let superblock_width = above.map_or(1, |c| c.size).max(1);
13522 if bw4 <= superblock_width {
13523 let col_offset = -((mi_col % superblock_width) as isize);
13524 if col_offset < 0 {
13525 do_tl = false;
13526 }
13527 if col_offset + superblock_width as isize > bw4 as isize {
13528 do_tr = false;
13529 }
13530 if let Some(info) = above {
13531 if single_ref_match(info) {
13532 samples.push(rec(info, 0, -1, col_offset as i32, 1));
13533 if samples.len() >= MAX {
13534 break 'outer;
13535 }
13536 }
13537 }
13538 } else {
13539 let mut i = 0usize;
13540 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
13541 while i < limit {
13542 let cell = grid.get(mi_row - 1, mi_col + i);
13543 let sw = cell.map_or(1, |c| c.size).max(1);
13544 if let Some(info) = cell {
13545 if single_ref_match(info) {
13546 samples.push(rec(info, 0, -1, i as i32, 1));
13547 if samples.len() >= MAX {
13548 break 'outer;
13549 }
13550 }
13551 }
13552 i += sw;
13553 }
13554 }
13555 }
13556
13557 if left_available {
13558 let left = grid.get(mi_row, mi_col - 1);
13559 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
13560 if bh4 <= superblock_height {
13561 let row_offset = -((mi_row % superblock_height) as isize);
13562 if row_offset < 0 {
13563 do_tl = false;
13564 }
13565 if let Some(info) = left {
13566 if single_ref_match(info) {
13567 samples.push(rec(info, row_offset as i32, 1, 0, -1));
13568 if samples.len() >= MAX {
13569 break 'outer;
13570 }
13571 }
13572 }
13573 } else {
13574 let mut i = 0usize;
13575 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
13576 while i < limit {
13577 let cell = grid.get(mi_row + i, mi_col - 1);
13578 let sh = cell.map_or(1, |c| c.size_h).max(1);
13579 if let Some(info) = cell {
13580 if single_ref_match(info) {
13581 samples.push(rec(info, i as i32, 1, 0, -1));
13582 if samples.len() >= MAX {
13583 break 'outer;
13584 }
13585 }
13586 }
13587 i += sh;
13588 }
13589 }
13590 }
13591
13592 if do_tl && left_available && up_available {
13593 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
13594 if single_ref_match(info) {
13595 samples.push(rec(info, 0, -1, 0, -1));
13596 if samples.len() >= MAX {
13597 break 'outer;
13598 }
13599 }
13600 }
13601 }
13602
13603 if do_tr && has_top_right(mi_row, mi_col, bw4) {
13604 let tr_col = mi_col + bw4;
13605 if mi_row > 0 && tr_col < mi_cols {
13606 if let Some(info) = grid.get(mi_row - 1, tr_col) {
13607 if single_ref_match(info) {
13608 samples.push(rec(info, 0, -1, bw4 as i32, 1));
13609 }
13610 }
13611 }
13612 }
13613 }
13614 samples
13615}
13616
13617/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
13618/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
13619/// the 2-symbol `obmc_cdf` (spec 5.11.24).
13620#[allow(clippy::too_many_arguments)]
13621fn num_proj_ref(
13622 grid: &MiGrid,
13623 mi_row: usize,
13624 mi_col: usize,
13625 bw4: usize,
13626 bh4: usize,
13627 mi_cols: usize,
13628 mi_rows: usize,
13629 ref_frame: i8,
13630) -> u8 {
13631 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
13632}
13633
13634/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
13635/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
13636/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
13637/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
13638/// to 64 (no neighbour contribution) away from it. Only the lengths this
13639/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
13640/// are transcribed.
13641fn obmc_mask(len: usize) -> &'static [u8] {
13642 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
13643 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
13644 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
13645 // round wired interior 16x16 splits down to real 8x8 leaves, where the
13646 // old `unreachable!()` below fired as a hard panic.
13647 const M1: [u8; 1] = [64];
13648 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
13649 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
13650 // chroma), which only became live once 8x8 inter leaves stopped being
13651 // refused.
13652 const M2: [u8; 2] = [45, 64];
13653 const M4: [u8; 4] = [39, 50, 59, 64];
13654 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
13655 const M16: [u8; 16] = [
13656 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
13657 ];
13658 const M32: [u8; 32] = [
13659 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
13660 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
13661 ];
13662 match len {
13663 1 => &M1,
13664 2 => &M2,
13665 4 => &M4,
13666 8 => &M8,
13667 16 => &M16,
13668 32 => &M32,
13669 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
13670 }
13671}
13672
13673/// A bordering block's own resolved interp filter kernel, `(h, v)` --
13674/// mirrors [`resolve_interp_filter`]'s own return order from its stored
13675/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
13676/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]`
13677/// sentinel: that value is only ever stored for an intra neighbour (already
13678/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter`
13679/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here
13680/// first.
13681fn neighbour_filter(
13682 interp_fixed: Option<mc::InterpFilterKind>,
13683 sym: [u8; 2],
13684) -> (mc::InterpFilterKind, mc::InterpFilterKind) {
13685 if let Some(kind) = interp_fixed {
13686 return (kind, kind);
13687 }
13688 (
13689 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
13690 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
13691 )
13692}
13693
13694/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
13695/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
13696/// under `av1_setup_build_prediction_by_{above,left}_pred`).
13697#[allow(clippy::too_many_arguments)]
13698fn obmc_neighbour_pred(
13699 refplane: &PlaneBuf,
13700 x: usize,
13701 y: usize,
13702 mv: (i32, i32),
13703 w: usize,
13704 h: usize,
13705 luma: bool,
13706 h_kind: mc::InterpFilterKind,
13707 v_kind: mc::InterpFilterKind,
13708 // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own
13709 // reference (derived from luma widths, applied unchanged to chroma whose
13710 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
13711 // the ordinary stride-1 path bit-exact.
13712 x_scale_fp: i64,
13713) -> Vec<u16> {
13714 let mut out = vec![0u16; w * h];
13715 if x_scale_fp == mc::REF_NO_SCALE {
13716 mc::predict_with_filters(
13717 &refplane.data,
13718 refplane.width,
13719 refplane.true_width,
13720 refplane.true_height,
13721 mv_to_q4(x, mv.1, luma),
13722 mv_to_q4(y, mv.0, luma),
13723 w,
13724 h,
13725 h_kind,
13726 v_kind,
13727 &mut out,
13728 );
13729 } else {
13730 mc::predict_scaled(
13731 &refplane.data,
13732 refplane.width,
13733 refplane.true_width,
13734 refplane.true_height,
13735 mv_to_q4(x, mv.1, luma),
13736 mv_to_q4(y, mv.0, luma),
13737 x_scale_fp,
13738 w,
13739 h,
13740 h_kind,
13741 v_kind,
13742 &mut out,
13743 );
13744 }
13745 out
13746}
13747
13748/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
13749/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
13750/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
13751const II_WEIGHTS_1D: [u8; 128] = [
13752 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
13753 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
13754 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
13755 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
13756 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
13757 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
13758 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
13759];
13760
13761/// lane-interintra r1: non-wedge interintra prediction for one plane
13762/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
13763/// `build_smooth_interintra_mask`). Builds the intra predictor for the
13764/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
13765/// own decoded edges at `(x, y)`, then blends it over the inter prediction
13766/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
13767/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
13768/// reduces to `128 / side` for the square plane sizes this decoder reaches.
13769/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
13770/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
13771fn interintra_blend(
13772 plane: &PlaneBuf,
13773 x: usize,
13774 y: usize,
13775 side: usize,
13776 ii_mode: u8,
13777 wedge: Option<(&'static [u8], usize)>,
13778 pred: &mut [u16],
13779) {
13780 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
13781 let intra_mode = match ii_mode {
13782 0 => crate::intra::DC_PRED,
13783 1 => crate::intra::V_PRED,
13784 2 => crate::intra::H_PRED,
13785 _ => crate::intra::SMOOTH_PRED,
13786 };
13787 let (above, left, corner) = plane.edges(
13788 x,
13789 y,
13790 side,
13791 crate::encode::Reach {
13792 above_right: false,
13793 below_left: false,
13794 },
13795 );
13796 let mut intra = vec![0u16; side * side];
13797 // Edge filtering never applies here: V/H at delta 0 are plain edge
13798 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
13799 // angle at all.
13800 predict(
13801 intra_mode,
13802 0,
13803 above.as_deref(),
13804 left.as_deref(),
13805 corner,
13806 side,
13807 side,
13808 false,
13809 false,
13810 &mut intra,
13811 );
13812 let scale = 128 / side;
13813 for i in 0..side {
13814 for j in 0..side {
13815 let m = u32::from(match wedge {
13816 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
13817 // over the wedge codebook, intra as src0, fixed sign 0).
13818 // Luma plane: mask rows are luma-resolution, ms == side.
13819 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
13820 // subw == subh == 1).
13821 Some((mask, ms)) if ms == side => mask[i * side + j],
13822 Some((mask, ms)) => {
13823 let t = 2 * i * ms + 2 * j;
13824 ((u32::from(mask[t])
13825 + u32::from(mask[t + 1])
13826 + u32::from(mask[t + ms])
13827 + u32::from(mask[t + ms + 1])
13828 + 2)
13829 >> 2) as u8
13830 }
13831 None => match ii_mode {
13832 0 => 32,
13833 1 => II_WEIGHTS_1D[i * scale],
13834 2 => II_WEIGHTS_1D[j * scale],
13835 _ => II_WEIGHTS_1D[i.min(j) * scale],
13836 },
13837 });
13838 let idx = i * side + j;
13839 pred[idx] =
13840 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u16;
13841 }
13842 }
13843}
13844
13845fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
13846 let mask = obmc_mask(h);
13847 for row in 0..h {
13848 let m = u32::from(mask[row]);
13849 for col in 0..w {
13850 let d = &mut dst[(oy + row) * stride + ox + col];
13851 let t = u32::from(tmp[row * w + col]);
13852 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
13853 }
13854 }
13855}
13856
13857/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
13858/// left-neighbour pass, `aom_blend_a64_hmask`).
13859fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
13860 let mask = obmc_mask(w);
13861 for row in 0..h {
13862 for col in 0..w {
13863 let m = u32::from(mask[col]);
13864 let d = &mut dst[(oy + row) * stride + ox + col];
13865 let t = u32::from(tmp[row * w + col]);
13866 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
13867 }
13868 }
13869}
13870
13871/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
13872/// the overlap strip against each bordering above/left inter neighbour's own
13873/// mv/ref/filter and blends it into this block's just-built single-reference
13874/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
13875/// left, each reading only the *original* prediction this function was
13876/// handed (never the other pass's own output), matching libaom's own
13877/// independence between the two. `max_neighbor_obmc`'s own cap table
13878/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
13879/// decoder's own square blocks always index the same value both ways) bounds
13880/// how many bordering blocks actually get blended, separate from the
13881/// eligibility scan's own unbounded ("any at all") walk.
13882#[allow(clippy::too_many_arguments)]
13883fn obmc_blend(
13884 grid: &MiGrid,
13885 neighbours: &Neighbours,
13886 mi_row: usize,
13887 mi_col: usize,
13888 bw4: usize,
13889 bh4: usize,
13890 mi_rows: usize,
13891 mi_cols: usize,
13892 side: usize,
13893 write_w: usize,
13894 write_h: usize,
13895 chroma_side: usize,
13896 px: usize,
13897 py: usize,
13898 cpx: usize,
13899 cpy: usize,
13900 ref_y: &PlaneBuf,
13901 ref_u: &PlaneBuf,
13902 ref_v: &PlaneBuf,
13903 other_refs: &RefSlots,
13904 interp_fixed: Option<mc::InterpFilterKind>,
13905 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
13906 // neighbour is re-predicted against ITS OWN reference, which may be
13907 // scaled differently from this block's (spec 7.11.3.3 / libaom
13908 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
13909 // `scale_factors`).
13910 frame_width: usize,
13911 pred_y: &mut [u16],
13912 pred_u: &mut [u16],
13913 pred_v: &mut [u16],
13914) -> Result<()> {
13915 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
13916 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
13917 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
13918 // right only for square blocks.
13919 let max_nb = |n4: usize| match n4 {
13920 1..=4 => 2,
13921 5..=8 => 3,
13922 _ => 4,
13923 };
13924 let overlap_above = write_h / 2;
13925 let overlap_left = write_w / 2;
13926 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
13927 // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided
13928 // obmc") returns `dir == 0` when the chroma plane's own block is
13929 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
13930 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
13931 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
13932
13933 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
13934 {
13935 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
13936 // (this decoder's own outer block-loop granularity), one step
13937 // coarser than the mi(4px) units `overlappable_above` walks in --
13938 // divide back down to that column.
13939 // lane-gmaffine r2: the neighbour's OWN mi-granular filter
13940 // (libaom `av1_setup_build_prediction_by_above_pred` reads
13941 // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot
13942 // stays as the fallback for paths that do not record one yet
13943 // (compound), which is what every earlier round used.
13944 let (h_kind, v_kind) = neighbour_filter(
13945 interp_fixed,
13946 neighbours.above_filter[mi_col + off4],
13947 );
13948 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
13949 let nb_scale = mc::scale_factor(ny.width, frame_width);
13950 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
13951 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
13952 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
13953 if !skip_chroma_above {
13954 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
13955 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13956 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
13957 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13958 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
13959 }
13960 }
13961
13962 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
13963 let (h_kind, v_kind) = neighbour_filter(
13964 interp_fixed,
13965 neighbours.left_filter[mi_row + off4],
13966 );
13967 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
13968 let nb_scale = mc::scale_factor(ny.width, frame_width);
13969 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
13970 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
13971 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
13972 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
13973 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13974 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
13975 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13976 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
13977 }
13978 Ok(())
13979}
13980
13981/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
13982/// the square block sizes this decoder ever decodes (32/16/8, all
13983/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
13984/// always `is_interinter_compound_used`, so the function is always `true`
13985/// for `side` -- kept as a named call (rather than inlined `true`) so a
13986/// future sub-8 block size does not silently misdecode a real stream.
13987fn is_any_masked_compound_used_here(side: usize) -> bool {
13988 side.min(side) >= 8
13989}
13990
13991/// Whether a compound reference pair is unidirectional (both references on
13992/// the same temporal side of the current frame) -- `has_uni_comp_refs`
13993/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
13994/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
13995/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
13996/// is_backward(ref1)`). Used to build a real
13997/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
13998/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
13999fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
14000 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
14001 backward(ref0) == backward(ref1)
14002}
14003
14004/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
14005/// above/left neighbour contributions [`Neighbours::record_inter`]/
14006/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
14007/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
14008/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
14009/// leaves read the same neighbour cell (class context-read-from-one-cell).
14010fn get_comp_group_idx_context(
14011 neighbours: &Neighbours,
14012 at_mi: (usize, usize),
14013 side: usize,
14014) -> usize {
14015 let _ = side;
14016 let (rmi, cmi) = at_mi;
14017 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
14018 .min(5)
14019}
14020
14021/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
14022/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
14023/// block's own two references' distances from the current frame (spec
14024/// 7.11.3.15's `get_relative_dist`, same convention
14025/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
14026#[allow(clippy::too_many_arguments)]
14027fn get_comp_index_context(
14028 neighbours: &Neighbours,
14029 at_mi: (usize, usize),
14030 side: usize,
14031 order_hint_bits: u32,
14032 cur_order_hint: u32,
14033 ref0_order_hint: u32,
14034 ref1_order_hint: u32,
14035) -> usize {
14036 let _ = side;
14037 let (rmi, cmi) = at_mi;
14038 let fwd =
14039 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
14040 .abs();
14041 let bck =
14042 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
14043 .abs();
14044 let offset = usize::from(fwd == bck);
14045 neighbours.above_compound_idx[cmi] as usize
14046 + neighbours.left_compound_idx[rmi] as usize
14047 + 3 * offset
14048}
14049
14050fn read_comp_mode(
14051 dec: &mut SymbolDecoder,
14052 cdfs: &mut Cdfs,
14053 above: Option<NeighbourRef>,
14054 left: Option<NeighbourRef>,
14055) -> bool {
14056 let ctx = reference_mode_ctx(above, left);
14057 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
14058 if compound {
14059 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
14060 }
14061 compound
14062}
14063
14064/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
14065/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
14066/// arm), reached once [`read_comp_mode`] has already returned
14067/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
14068/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
14069/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
14070/// convention [`read_single_ref`] already uses, for every downstream binary
14071/// decision. libaom `pred_common.c`'s own compound context functions
14072/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
14073/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
14074/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
14075/// (same vote-the-neighbours-above-left shape, same forward/backward and
14076/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
14077/// against the C source rather than porting six near-duplicate functions.
14078/// Its caller today only needs the symbols consumed, correctly, to keep the
14079/// arithmetic decoder's own state in sync before refusing the block by name
14080/// -- the returned pair is not yet threaded into any motion-compensation
14081/// path.
14082fn read_compound_ref_frames(
14083 dec: &mut SymbolDecoder,
14084 cdfs: &mut Cdfs,
14085 above: Option<NeighbourRef>,
14086 left: Option<NeighbourRef>,
14087 above_ref: i8,
14088 left_ref: i8,
14089) -> (i8, i8) {
14090 let a = (above_ref > 0).then_some(above_ref);
14091 let l = (left_ref > 0).then_some(left_ref);
14092 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
14093 // neighbour's references, not just its first -- `a1`/`l1` carry that
14094 // second reference through to every vote below (lane-av1blend r6: a
14095 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
14096 // row for a block sitting under a skip_mode-forced compound neighbour).
14097 let a1 = above.and_then(|n| n.ref1);
14098 let l1 = left.and_then(|n| n.ref1);
14099 let type_ctx = comp_reference_type_ctx(above, left);
14100 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
14101 if unidir {
14102 UNI_COMP_HITS.with(|c| c.set(c.get() + 1));
14103 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
14104 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
14105 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
14106 if bit == 1 {
14107 (BWDREF_FRAME, ALTREF_FRAME)
14108 } else {
14109 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
14110 if p1 == 1 {
14111 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
14112 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
14113 if p2 == 1 {
14114 (LAST_FRAME, GOLDEN_FRAME)
14115 } else {
14116 (LAST_FRAME, LAST3_FRAME)
14117 }
14118 } else {
14119 (LAST_FRAME, LAST2_FRAME)
14120 }
14121 }
14122 } else {
14123 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
14124 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
14125 let ref0 = if bit0 == 0 {
14126 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
14127 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
14128 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
14129 } else {
14130 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
14131 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
14132 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
14133 };
14134 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
14135 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
14136 let ref1 = if bit1 == 0 {
14137 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
14138 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
14139 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
14140 } else {
14141 ALTREF_FRAME
14142 };
14143 (ref0, ref1)
14144 }
14145}
14146
14147/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
14148/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
14149/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
14150/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
14151/// libaom's `av1_mode_context_analyzer`'s compound branch --
14152/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
14153/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
14154/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
14155/// is not yet turned into an assigned MV pair or motion-compensated --
14156/// lane-av1comp.
14157fn read_inter_compound_mode(
14158 dec: &mut SymbolDecoder,
14159 cdfs: &mut Cdfs,
14160 new_mv_ctx: usize,
14161 ref_mv_ctx: usize,
14162) -> u8 {
14163 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
14164 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
14165 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
14166}
14167
14168/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
14169/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
14170/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
14171/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
14172/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
14173/// non-`IDENTITY` global motion model before a tile is ever decoded.
14174///
14175/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
14176/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
14177/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
14178/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
14179/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
14180fn assign_compound_mv(
14181 dec: &mut SymbolDecoder,
14182 cdfs: &mut Cdfs,
14183 comp_stack: &crate::mvstack::CompoundMvStack,
14184 mode: u8,
14185 allow_high_precision_mv: bool,
14186 force_integer_mv: bool,
14187 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
14188 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
14189 global_mv: ((i32, i32), (i32, i32)),
14190) -> ((i32, i32), (i32, i32)) {
14191 const NEAREST_NEARESTMV: u8 = 0;
14192 const NEAR_NEARMV: u8 = 1;
14193 const NEAREST_NEWMV: u8 = 2;
14194 const NEW_NEARESTMV: u8 = 3;
14195 const NEAR_NEWMV: u8 = 4;
14196 const NEW_NEARMV: u8 = 5;
14197 const GLOBAL_GLOBALMV: u8 = 6;
14198 const NEW_NEWMV: u8 = 7;
14199
14200 let mut ref_mv_idx = 0usize;
14201 if mode == NEW_NEWMV {
14202 let mut idx = 0usize;
14203 while idx < 2 && comp_stack.entries.len() > idx + 1 {
14204 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
14205 break;
14206 }
14207 idx += 1;
14208 }
14209 ref_mv_idx = idx;
14210 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
14211 let mut idx = 1usize;
14212 while idx < 3 && comp_stack.entries.len() > idx + 1 {
14213 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
14214 break;
14215 }
14216 idx += 1;
14217 }
14218 ref_mv_idx = idx - 1;
14219 }
14220
14221 let near = comp_stack
14222 .entries
14223 .get(ref_mv_idx + 1)
14224 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
14225 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
14226 ref_mv_idx + 1
14227 } else {
14228 ref_mv_idx
14229 };
14230 let new_pred = comp_stack
14231 .entries
14232 .get(new_idx)
14233 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
14234
14235 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
14236 read_mv(
14237 dec,
14238 &mut cdfs.mv_comp,
14239 &mut cdfs.mv_joint,
14240 base,
14241 allow_high_precision_mv,
14242 force_integer_mv,
14243 )
14244 };
14245
14246 match mode {
14247 NEAREST_NEARESTMV => comp_stack.nearest_mv,
14248 NEAR_NEARMV => near,
14249 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
14250 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
14251 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
14252 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
14253 GLOBAL_GLOBALMV => global_mv,
14254 _ => (
14255 read_new(dec, cdfs, new_pred.0),
14256 read_new(dec, cdfs, new_pred.1),
14257 ),
14258 }
14259}
14260
14261/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
14262/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
14263/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
14264/// table is always computed at the *querying* block's position, never a
14265/// donating neighbour's).
14266fn build_gm_mv_table(
14267 global_motion: &[ec_av1_syntax::WarpParams; 7],
14268 mi_row: usize,
14269 mi_col: usize,
14270 bw4: usize,
14271 bh4: usize,
14272 allow_high_precision_mv: bool,
14273 force_integer_mv: bool,
14274) -> crate::mvstack::GmMvTable {
14275 std::array::from_fn(|i| {
14276 let gm = &global_motion[i];
14277 crate::warp::gm_get_motion_vector(
14278 gm.model,
14279 &gm.params,
14280 mi_row,
14281 mi_col,
14282 bw4,
14283 bh4,
14284 allow_high_precision_mv,
14285 force_integer_mv,
14286 )
14287 })
14288}
14289
14290/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
14291/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
14292/// and motion-compensated reconstruction, or the inter frame's own intra
14293/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
14294/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
14295/// private `write_inter_frame_leaf` -- both share this one function here,
14296/// parameterised by `side`/the transform sets/scan tables/size group they
14297/// each use.
14298///
14299/// # Errors
14300/// Returns an error when a symbol names anything this decoder does not
14301/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
14302/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
14303/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
14304/// refuse.
14305#[allow(clippy::too_many_arguments)]
14306fn decode_inter_block(
14307 dec: &mut SymbolDecoder,
14308 cdfs: &mut Cdfs,
14309 neighbours: &mut Neighbours,
14310 grid: &mut MiGrid,
14311 at: (usize, usize),
14312 side: usize,
14313 mi_cols: u32,
14314 mi_rows: u32,
14315 y: &mut PlaneBuf,
14316 u: &mut PlaneBuf,
14317 v: &mut PlaneBuf,
14318 ref_y: &PlaneBuf,
14319 ref_u: &PlaneBuf,
14320 ref_v: &PlaneBuf,
14321 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
14322 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
14323 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
14324 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
14325 // slot's still empty (an error-resilient stream, or too early in the
14326 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
14327 other_refs: &RefSlots,
14328 sign_bias_table: &SignBiasTable,
14329 // lane-gm r2: this frame header's own `global_motion` table (spec
14330 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
14331 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
14332 // assignment and the mv-stack's neighbour substitution.
14333 global_motion: &[ec_av1_syntax::WarpParams; 7],
14334 base_q_idx: u8,
14335 luma_set_intra: TxbSet,
14336 luma_set_inter: TxbSet,
14337 chroma_set: TxbSet,
14338 luma_tx: usize,
14339 chroma_tx: usize,
14340 scan_luma: &[u16],
14341 scan_chroma: &[u16],
14342 size_group: usize,
14343 allow_high_precision_mv: bool,
14344 force_integer_mv: bool,
14345 interp_fixed: Option<mc::InterpFilterKind>,
14346 enable_dual_filter: bool,
14347 tpl_frame: Option<&TplFrameArgs>,
14348 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
14349 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
14350 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
14351 // refuses (rather than silently misdecoding) the ones that pick
14352 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
14353 // wired yet.
14354 reference_select: bool,
14355 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
14356 // compound enable bits, gating `comp_group_idx`/`compound_idx`
14357 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
14358 // compound blend weights need this frame's own order hint regardless
14359 // of `use_ref_frame_mvs`.
14360 enable_masked_compound: bool,
14361 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
14362 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
14363 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
14364 // and before `read_motion_mode` on the single-ref path below, gated by
14365 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
14366 // every mode this single-ref branch can produce is already in
14367 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
14368 // (inter+intra blended prediction unimplemented) rather than a
14369 // mis-decode.
14370 enable_interintra_compound: bool,
14371 enable_jnt_comp: bool,
14372 order_hint_bits: u32,
14373 order_hint: u32,
14374 ref_order_hints: [u32; 7],
14375 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
14376 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
14377 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
14378 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
14379 // when this is `true` (every block this decoder reaches is >= 8x8, so
14380 // `is_comp_ref_allowed` never gates it further); a `true` result forces
14381 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
14382 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
14383 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
14384 skip_mode_present: bool,
14385 skip_mode_frame: [u8; 2],
14386 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
14387 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
14388 switchable_motion_mode: bool,
14389 allow_warped_motion: bool,
14390 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
14391 // as a square 32x32 block, which over-reads a residual unless coded
14392 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
14393 reject_residual: bool,
14394 // lane-partitions r1: the strip's own true width/height in pixels --
14395 // `side` keeps governing every syntax/CDF/prediction-buffer decision
14396 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
14397 // the final pixel write and this block's own neighbour-context stamp
14398 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
14399 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
14400 // for every existing (square) caller.
14401 write_w: usize,
14402 write_h: usize,
14403 // lane-screen r2: this frame header's own `allow_screen_content_tools`
14404 // bit, threaded to the intra-sub-block branch below -- libaom's
14405 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
14406 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
14407 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
14408 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
14409 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
14410 // under the same `av1_allow_palette` gate as the key-frame path.
14411 allow_screen_content_tools: bool,
14412 // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) --
14413 // compared against each reference's stored picture width to decide
14414 // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary
14415 // stride-1 one (`mc::predict_with_filters`) applies per reference, and to
14416 // refuse (rather than mis-decode) the warp/OBMC/interintra/compound
14417 // combinations that don't implement scaled MC yet.
14418 frame_width: usize,
14419) -> Result<()> {
14420 let (r, c) = at;
14421 // lane-inter8 r2: the inter side bands are mi-granular; this block's own
14422 // above/left neighbour is the mi cell at its top-left corner (libaom
14423 // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads
14424 // exactly what it read before.
14425 let (rmi, cmi) = (r * (SUB / MI), c * (SUB / MI));
14426 let (px, py) = (c * SUB, r * SUB);
14427 let (cpx, cpy) = (px / 2, py / 2);
14428 let chroma_side = side / 2;
14429 let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2);
14430
14431 if std::env::var_os("EC_AV1_TELL").is_some() {
14432 eprintln!(
14433 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
14434 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
14435 );
14436 }
14437 let skip_mode_ctx =
14438 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
14439 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
14440 // MSAC tell so it can be diffed against an equivalent hook in libaom's
14441 // own `read_skip_mode`/`av1_get_skip_mode_context`.
14442 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
14443 eprintln!(
14444 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
14445 dec.debug_bitpos()
14446 );
14447 }
14448 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
14449 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
14450 let (seg_mi_r, seg_mi_c) = (r * SUB_MI as usize, c * SUB_MI as usize);
14451 let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
14452 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
14453 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
14454 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
14455 eprintln!(
14456 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
14457 dec.debug_bitpos()
14458 );
14459 }
14460 if skip_mode {
14461 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
14462 }
14463
14464 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
14465 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
14466 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
14467 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
14468 maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
14469 maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
14470 // lane-warp r5: see `reject_residual` -- a square-block decode of a
14471 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
14472 // motion_mode/warp symbol), so gate here before any further read.
14473 if reject_residual && !skip {
14474 return Err(unsupported(
14475 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
14476 ));
14477 }
14478
14479 let (has_above, has_left) = (
14480 r > neighbours.tile_row0_mi / (SUB / MI),
14481 c > neighbours.tile_col0_mi / (SUB / MI),
14482 );
14483 let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]);
14484 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
14485 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
14486 if std::env::var_os("EC_TRACE_MODE").is_some() {
14487 eprintln!(
14488 "EC_MODE mi_row={} mi_col={} rng={}",
14489 r * SUB_MI as usize,
14490 c * SUB_MI as usize,
14491 dec.debug_state().0
14492 );
14493 }
14494 if std::env::var_os("EC_AV1_TELL").is_some() {
14495 eprintln!(
14496 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
14497 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
14498 );
14499 }
14500
14501 let mode_for_tx;
14502 let uv_predict_mode;
14503 let (luma_grid, u_grid, v_grid);
14504 let block_filter;
14505 let ref_frame_for_lf;
14506 let globalmv_for_lf;
14507 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
14508 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
14509 // common `record_inter` call below (which would otherwise stamp the
14510 // single-ref ALTREF-special-case default over it).
14511 let mut compound_ctx: Option<(i8, u8, u8)> = None;
14512 // lane-txselect: `read_block_tx_size`'s leaf transform units (spec
14513 // 5.11.17), `Some` only when this block's var-tx tree resolved to more
14514 // than one luma transform -- read back by the residual loop, the
14515 // coefficient-context write-back and the loop-filter grid fill below.
14516 let mut vartx_leaves: Option<Vec<(usize, usize, usize)>> = None;
14517 let at_mi = (r * (SUB / MI), c * (SUB / MI));
14518 if is_inter {
14519 let above_nbr = has_above.then(|| NeighbourRef {
14520 is_inter: above_inter,
14521 ref0: if above_inter {
14522 neighbours.above_ref[cmi]
14523 } else {
14524 0
14525 },
14526 ref1: neighbours.above_ref1[cmi],
14527 uni: neighbours.above_ref1[cmi]
14528 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[cmi], r1)),
14529 });
14530 let left_nbr = has_left.then(|| NeighbourRef {
14531 is_inter: left_inter,
14532 ref0: if left_inter {
14533 neighbours.left_ref[rmi]
14534 } else {
14535 0
14536 },
14537 ref1: neighbours.left_ref1[rmi],
14538 uni: neighbours.left_ref1[rmi]
14539 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
14540 });
14541 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
14542 eprintln!(
14543 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
14544 dec.debug_bitpos()
14545 );
14546 }
14547 let is_compound =
14548 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
14549 if is_compound {
14550 let (ref0, ref1) = if skip_mode {
14551 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
14552 } else {
14553 read_compound_ref_frames(
14554 dec,
14555 cdfs,
14556 above_nbr,
14557 left_nbr,
14558 neighbours.above_ref[cmi],
14559 neighbours.left_ref[rmi],
14560 )
14561 };
14562 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
14563 // lane-rect r2: true footprint, mirroring the single-ref path below.
14564 let bw4 = write_w / 4;
14565 let bh4 = write_h / 4;
14566 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
14567 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
14568 // below, just one `get_relative_dist` per reference.
14569 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
14570 field: t.field,
14571 cur_offset_0: crate::motion_field::get_relative_dist(
14572 t.order_hint_bits,
14573 t.order_hint,
14574 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
14575 ),
14576 cur_offset_1: crate::motion_field::get_relative_dist(
14577 t.order_hint_bits,
14578 t.order_hint,
14579 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
14580 ),
14581 allow_high_precision_mv,
14582 });
14583 let gm_table = build_gm_mv_table(
14584 global_motion,
14585 mi_row,
14586 mi_col,
14587 bw4,
14588 bh4,
14589 allow_high_precision_mv,
14590 force_integer_mv,
14591 );
14592 let comp_stack = crate::mvstack::find_mv_stack_compound(
14593 grid,
14594 mi_row,
14595 mi_col,
14596 bw4,
14597 bh4,
14598 (ref0, ref1),
14599 mi_cols as usize,
14600 mi_rows as usize,
14601 sign_bias_table,
14602 &gm_table,
14603 comp_tpl,
14604 );
14605 let compound_mode = if skip_mode {
14606 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
14607 } else {
14608 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
14609 };
14610 let (mv0, mv1) = assign_compound_mv(
14611 dec,
14612 cdfs,
14613 &comp_stack,
14614 compound_mode,
14615 allow_high_precision_mv,
14616 force_integer_mv,
14617 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
14618 );
14619 if std::env::var_os("EC_TRACE_MODE").is_some() {
14620 eprintln!(
14621 "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={} ref0={ref0} ref1={ref1} mv0=({},{}) stack={} rng={}",
14622 compound_mode + 17,
14623 mv0.0,
14624 mv0.1,
14625 comp_stack.entries.len(),
14626 dec.debug_state().0
14627 );
14628 for (i, e) in comp_stack.entries.iter().enumerate() {
14629 eprintln!(
14630 "EC_STACK mi_row={mi_row} mi_col={mi_col} i={i} this=({},{}) comp=({},{}) w={}",
14631 e.mv0.0, e.mv0.1, e.mv1.0, e.mv1.1, e.weight
14632 );
14633 }
14634 }
14635 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
14636 // spec `is_nontrans_global_motion`: ALL active refs' models must
14637 // be non-TRANSLATION (IDENTITY counts) for the compound block's
14638 // interp-filter read to be suppressed.
14639 let gm_nontrans = is_globalmv
14640 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
14641 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
14642 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
14643 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
14644 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
14645 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
14646 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
14647 // the write extent below, so recompute the size bound from
14648 // `side` here (the block's own size, what libaom's `bsize`
14649 // is).
14650 let is_global_mv0 = is_globalmv
14651 && side >= 8
14652 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1;
14653 let is_global_mv1 = is_globalmv
14654 && side >= 8
14655 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1;
14656 // libaom `av1_init_warp_params` + `allow_warp`'s
14657 // `global_warp_allowed` branch, run once per reference for a
14658 // compound block exactly as for a single-ref one (reconinter.c
14659 // `build_inter_predictors_8x8_and_bigger` loops over `ref` and
14660 // calls `av1_init_warp_params` inside the loop) -- WARPED_CAUSAL
14661 // never reaches here (spec 5.11.27 / libaom `read_motion_mode`:
14662 // `has_second_ref` returns SIMPLE_TRANSLATION), so the local-warp
14663 // arm of `allow_warp` is dead on this path and only the global
14664 // one applies. `force_integer_mv` short-circuits
14665 // `av1_init_warp_params` before `allow_warp`.
14666 let compound_warp = |ref_frame: i8, eligible: bool| {
14667 if eligible
14668 && !force_integer_mv
14669 && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid
14670 {
14671 crate::warp::global_warp_params(
14672 global_motion[(ref_frame - LAST_FRAME) as usize].params,
14673 )
14674 } else {
14675 None
14676 }
14677 };
14678 let warp0 = compound_warp(ref0, is_global_mv0);
14679 let warp1 = compound_warp(ref1, is_global_mv1);
14680 if warp0.is_some() || warp1.is_some() {
14681 COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1));
14682 }
14683 // spec `get_ref_filter_type`: matches when EITHER of the
14684 // neighbour's two references equals this block's own ref0 --
14685 // `above_ref1`/`left_ref1` is the neighbour's real second
14686 // reference (`record_compound_ctx`) when it was itself a
14687 // compound block; checking `above_ref`/`left_ref` alone drops a
14688 // real filter match down to the "no neighbour" sentinel
14689 // whenever the shared reference sits in the neighbour's SECOND
14690 // slot (lane-av1idx r2).
14691 let above_filter_ctx = if neighbours.above_ref[cmi] == ref0
14692 || neighbours.above_ref1[cmi] == Some(ref0)
14693 {
14694 neighbours.above_filter[cmi]
14695 } else {
14696 [3, 3]
14697 };
14698 let left_filter_ctx = if neighbours.left_ref[rmi] == ref0
14699 || neighbours.left_ref1[rmi] == Some(ref0)
14700 {
14701 neighbours.left_filter[rmi]
14702 } else {
14703 [3, 3]
14704 };
14705 globalmv_for_lf = is_globalmv;
14706 ref_frame_for_lf = ref0;
14707 mode_for_tx = 0;
14708 uv_predict_mode = DC_PRED;
14709 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
14710 // `neighbours`) must be stamped with the block's true footprint
14711 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
14712 // NEXT strip's own rows/cols before it decodes, corrupting
14713 // every later mvstack scan that reads this cell back.
14714 for dr in 0..bh4 {
14715 for dc in 0..bw4 {
14716 grid.set(
14717 mi_row + dr,
14718 mi_col + dc,
14719 MiInfo {
14720 is_inter: true,
14721 ref_frame: ref0,
14722 ref_frame1: Some(ref1),
14723 mv1: Some(mv1),
14724 mv: mv0,
14725 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
14726 size: bw4,
14727 size_h: bh4,
14728 // libaom `is_global_mv_block`: per-ref-slot, mode
14729 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
14730 // own gm model > TRANSLATION (IDENTITY excluded
14731 // too -- the two-predicate trap, distinct from
14732 // `gm_nontrans` above which allows IDENTITY).
14733 is_global_mv0,
14734 is_global_mv1,
14735 },
14736 );
14737 }
14738 }
14739 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
14740 // masked compound / distance-weighted compound are actually
14741 // enabled for this stream -- `is_any_masked_compound_used_here`
14742 // is `true` for every block size this decoder ever reaches
14743 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
14744 // there), so the gate reduces to the sequence header bit; kept
14745 // as an explicit call so a future smaller block size is not
14746 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
14747 let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side);
14748 let comp_group_idx = if !skip_mode
14749 && enable_masked_compound
14750 && is_any_masked_compound_used_here(side)
14751 {
14752 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
14753 } else {
14754 0
14755 };
14756 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
14757 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
14758 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
14759 // when `comp_group_idx == 1`.
14760 let mut diffwtd_mask_type: Option<u8> = None;
14761 let mut wedge_mask: Option<&'static [u8]> = None;
14762 if comp_group_idx == 1 {
14763 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
14764 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
14765 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
14766 // `av1_wedge_params_lookup`) is true for every square bsize
14767 // this leaf reaches (8x8/16x16/32x32 all have
14768 // `wedge_types > 0`), so `compound_type` always reads a real
14769 // symbol here -- no alphabet collapse to worry about at this
14770 // block-size family.
14771 // lane-mcomp64 r1: `av1_is_wedge_used` is false at 64x64
14772 // (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`),
14773 // so libaom's `read_compound_type` (decodemv.c 1634-1656)
14774 // writes NO `compound_type` symbol there and INFERS
14775 // `COMPOUND_DIFFWTD` -- only the 1-bit `mask_type` literal
14776 // follows. `None` here is exactly that inferred arm.
14777 let wedge_bsize = match side {
14778 8 => Some(3),
14779 16 => Some(6),
14780 32 => Some(9),
14781 _ => None,
14782 };
14783 let compound_type = match wedge_bsize {
14784 Some(b) => dec.symbol(&mut cdfs.compound_type[b]),
14785 None => 1,
14786 };
14787 if let Some(wedge_bsize) = wedge_bsize.filter(|_| compound_type == 0) {
14788 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
14789 // verified vs independent C dump (wedge.rs).
14790 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
14791 let wedge_sign = dec.literal(1);
14792 WEDGE_HITS.with(|c| c.set(c.get() + 1));
14793 wedge_mask = Some(
14794 crate::wedge::wedge_masks()
14795 .codebook(side)
14796 .mask(wedge_sign as usize, wedge_index as usize),
14797 );
14798 } else {
14799 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
14800 let mask_type = dec.literal(1);
14801 diffwtd_mask_type = Some(mask_type as u8);
14802 if wedge_bsize.is_none() {
14803 DIFFWTD_INFERRED_HITS.with(|c| c.set(c.get() + 1));
14804 }
14805 }
14806 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
14807 }
14808 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
14809 // called this a `predict_compound_intermediate`/`combine_compound`
14810 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
14811 // unmasking and running the real gates
14812 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
14813 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
14814 // shows the plain-average blend is bit-exact *most of the time*
14815 // -- `combine_compound`'s two-shift-in-one round2 was proven
14816 // algebraically identical to libaom's separate
14817 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
14818 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
14819 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
14820 // the common case a lag-in-frames GOP's hidden altref frames
14821 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
14822 // for several consecutive frames.
14823 //
14824 // The real defect a live gate run isolated (seed 49,
14825 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
14826 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
14827 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
14828 // byte; decode-order frame 2 -- same shape, same zero MV, only
14829 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
14830 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
14831 // Every later frame up through decode-order 9 also mismatches,
14832 // *including* frame 8, whose four blocks are back to
14833 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
14834 // math is wrong" (that block's own math is proven exact) in
14835 // favour of "the picture sitting in some DPB slot is already
14836 // wrong by the time frame 2 reads it, and the corruption
14837 // propagates through refresh_frame_flags into every later
14838 // reference regardless of which named ref a later block picks".
14839 // Frames 10 through 18 (once the GOP's lineage stops tracing
14840 // back through the bad slot) are bit-exact again. This points at
14841 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
14842 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
14843 // indexing feeding `dist_wtd_comp_weight_assign`) around
14844 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
14845 // mc.rs. Not isolated further within lane-av1blend's budget --
14846 // refuse by name rather than ship a blend that is right only
14847 // sometimes. Ceiling: r13/r14's MC plumbing above this line
14848 // stays -- only the plain-average reconstruct is masked off
14849 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
14850 // per decode-order frame (which slot each `Frame` OBU refreshes,
14851 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
14852 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
14853 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
14854 // frame 2.
14855 //
14856 // r2 (fresh fixture, seed 45, same recipe -- the original r1
14857 // fixture is gitignored and could not be regenerated byte-exact):
14858 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
14859 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
14860 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
14861 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
14862 // is forced 0 on every non-key `show_existing_frame`) turned up
14863 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
14864 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
14865 // isolated a *different, smaller* shape than r1's: decode-order
14866 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
14867 // compound block) is the first to diverge from ffmpeg (worst
14868 // delta 1, luma only, clustered at 32-pixel block edges) even
14869 // though BOTH its compound inputs -- the key frame and
14870 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
14871 // itself proven bit-exact: it is later re-shown via
14872 // `show_existing_frame` and matches ffmpeg exactly) -- are
14873 // independently pixel-exact, and the blend arithmetic is the
14874 // same proven-exact formula. That rules out "wrong slot"/"stale
14875 // picture" for this fixture: the inputs are right, so the defect
14876 // is in decode-order frame 3's *own* per-block decode (entropy
14877 // desync from compound-CDF adaptation carried across a slot, or
14878 // the compound mode/MV read itself) -- not in `ref_slots`/
14879 // `refresh_frame_flags`. Not isolated further within budget.
14880 // Upgrade: bisect decode-order frame 3's tile decode against a
14881 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
14882 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
14883 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
14884 // -- the pre-deblock dump frame-index alignment between this
14885 // crate and that aomdec build is NOT 1:1 on this fixture (23
14886 // dumps here vs 24 there), so calibrate that first.
14887 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
14888 // against an instrumented aomdec build (frame-index alignment
14889 // recalibrated via content-hash matching rather than the raw
14890 // dump count -- the keyframe never calls a pre-deblock dump at
14891 // all, since only `decode_inter_frame_tile` does, which is the
14892 // whole "23 vs 24" gap, not a real bug).
14893 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
14894 // seed 45) is still the first divergence: PRE-deblock differs
14895 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
14896 // luma pixels, clustered where its two compound inputs' pixel
14897 // values disagree by more than a couple of levels -- both
14898 // inputs (the keyframe and decode-order frame 2's own picture)
14899 // are independently proven bit-exact (pre- and post-deblock)
14900 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
14901 // matches this decoder's block loop exactly for every block in
14902 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
14903 // every mismatching pixel against `key`/`bwd` (both known-exact)
14904 // picks out `w0=9, w1=7` for the majority (525/846) with zero
14905 // matches for the plain average this decoder actually emits or
14906 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
14907 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
14908 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
14909 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
14910 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
14911 // decoder's own `dist_wtd_comp_weight_assign` was independently
14912 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
14913 // by hand for these distances and gives the same `(9, 7)`).
14914 // `get_comp_index_context` was checked line-for-line against
14915 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
14916 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
14917 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
14918 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
14919 // `default_compound_idx_cdfs` value-for-value; the read is
14920 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
14921 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
14922 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
14923 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
14924 // either -- some blocks in this frame plausibly decode a
14925 // genuinely different (correct, context-dependent) compound_idx
14926 // than block (0,0)'s own -- so this is not simply "always wrong
14927 // the same way": table/context/gate are all individually
14928 // verified correct, yet the decoded VALUE at this specific
14929 // symbol is wrong at least once in this frame. Not isolated
14930 // further within budget. Upgrade: instrument `dec.symbol`'s own
14931 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
14932 // trace fields) immediately before and after the `compound_idx`
14933 // read specifically, not just the surrounding mode/mv/skip
14934 // trace which does match -- the desync (if any) is local to
14935 // this one read, not a wider stream desync.
14936 //
14937 // r5 (this round): the `resolve_interp_filter` call used to sit
14938 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
14939 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
14940 // `read_compound_type`, not before, so that was a genuine
14941 // ordering bug for a Switchable-filter frame (moved below, past
14942 // the `compound_ctx = Some(...)` line). It does NOT explain this
14943 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
14944 // header carries a *fixed* interpolation filter
14945 // (`interp_fixed = Some(Regular)`, confirmed live via a
14946 // one-off dump), so `resolve_interp_filter` never read a symbol
14947 // in either position -- zero bits moved, decoded values
14948 // unchanged before and after the reorder. Kept anyway: it is a
14949 // real spec-order fix for the next Switchable-filter compound
14950 // stream, independently correct regardless of this fixture.
14951 //
14952 // Also ruled out this round: comparing this crate's own
14953 // `SymbolDecoder::debug_bitpos()` against aomdec's
14954 // `aom_reader_tell()` at the block boundary is NOT a valid
14955 // desync probe -- they are different quantities (raw consumed
14956 // input bits vs. an entropy-cost estimate that advances without
14957 // a literal byte fetch), so equal/unequal bitpos proves nothing
14958 // either way. Do not repeat that comparison; instead trace
14959 // `range`/`value` (this crate) against libaom's own internal
14960 // `dif`/`rng` (needs new instrumentation in both) immediately
14961 // after each read *upstream* of this one in the same block:
14962 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
14963 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
14964 // and the DRL loop. All of those independently decoded the SAME
14965 // values this crate and aomdec both show (ref0=1, ref1=5, mode
14966 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
14967 // miscomputation can still decode the identical symbol value off
14968 // a slightly different CDF, narrowing `range` by a different
14969 // amount than aomdec without changing the decoded value itself,
14970 // and only surface as a wrong decode a few reads later exactly
14971 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
14972 // table were independently re-verified again this round and are
14973 // still correct; the four candidates above were not re-audited
14974 // this round. Refusing here (rather than shipping a value-exact-
14975 // most-of-the-time blend) until one of them is found wrong.
14976 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
14977 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
14978 // comp_bwdref* context reads -- kept, real fix). Unmasking on
14979 // that fix alone and running the wide gate sweep (many seeds,
14980 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
14981 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
14982 // cq-level=45) still mismatches roughly half the time, at
14983 // different frames each run for the SAME seed -- aomenc's own
14984 // cpu-used=0 RD search is run-to-run nondeterministic (noted
14985 // above), so this is a second, still-unfound compound_idx defect,
14986 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
14987 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
14988 // either) already flagged more than one bug here. Re-masking:
14989 // do not ship a blend that is right only sometimes.
14990 // lane-av1idx r1: fixed one real bug this round
14991 // (`switchable_interp_ctx` never folded in libaom's
14992 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
14993 // interp_filter context -- kept). Pinned
14994 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
14995 // gate) still mismatches after that fix (decode-order frame 8
14996 // first, small deltas, worst 1-2, propagating through later
14997 // frames via DPB reference) -- a second, still-unfound bug.
14998 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
14999 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
15000 // for the next round's starting point.
15001 // lane-maskcomp r2: `compound_idx` is only read when
15002 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
15003 // (wedge/diffwtd) block never also carries a distance-weighted
15004 // split. This gate was missing before r2 (dead code: the masked
15005 // path always refused earlier, so it never executed with
15006 // `comp_group_idx == 1` in practice).
15007 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
15008 && !skip_mode
15009 && enable_jnt_comp
15010 {
15011 let idx_ctx = get_comp_index_context(
15012 neighbours,
15013 (rmi, cmi),
15014 side,
15015 order_hint_bits,
15016 order_hint,
15017 ref_order_hints[(ref0 - LAST_FRAME) as usize],
15018 ref_order_hints[(ref1 - LAST_FRAME) as usize],
15019 );
15020 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
15021 if idx == 1 {
15022 (8, 8, 1u8)
15023 } else {
15024 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
15025 order_hint_bits,
15026 order_hint,
15027 ref_order_hints[(ref0 - LAST_FRAME) as usize],
15028 ref_order_hints[(ref1 - LAST_FRAME) as usize],
15029 );
15030 (fwd, bck, 0u8)
15031 }
15032 } else {
15033 (8, 8, 1u8)
15034 };
15035 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
15036 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
15037 eprintln!(
15038 "EC_COMPIDX mi_row={mi_row} mi_col={mi_col} bsize={side} mode={compound_mode} mv0=({},{}) mv1=({},{}) ref0={ref0} ref1={ref1} comp_group_idx={comp_group_idx} compound_idx={compound_idx} tell={}",
15039 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
15040 );
15041 }
15042
15043 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
15044 // comes AFTER `read_compound_type` (the `comp_group_idx`/
15045 // `compound_idx` reads just above), not before -- moved here
15046 // (lane-av1blend r5) from its old position ahead of those reads,
15047 // which stole their bits for a Switchable-filter compound block
15048 // and desynced every symbol read after it in the tile.
15049 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
15050 // filter is derived (Regular), never read -- same
15051 // conditional-read contract as the WARPED_CAUSAL suppression on
15052 // the single-ref path below.
15053 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
15054 dec,
15055 cdfs,
15056 interp_fixed,
15057 enable_dual_filter,
15058 gm_nontrans || skip_mode,
15059 above_filter_ctx,
15060 left_filter_ctx,
15061 true,
15062 );
15063 block_filter = resolved_filter;
15064
15065 // lane-scaledref r1: each compound tap scales INDEPENDENTLY off
15066 // its own stored reference's luma width (spec 7.11.3.3 derives
15067 // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds
15068 // one `scale_factors` per `ref_frame`), so the two taps can carry
15069 // different ratios in the same block. `REF_NO_SCALE` reduces
15070 // `predict_compound_intermediate`'s walk to the ordinary
15071 // stride-1 one, so the unscaled case is unchanged.
15072 let scale0 = mc::scale_factor(py0.width, frame_width);
15073 let scale1 = mc::scale_factor(py1.width, frame_width);
15074 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
15075 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
15076 }
15077 // lane-scaledref r2: the MIXED case -- one tap scaled, the other
15078 // not -- is the one an all-frames-scaled recipe never produces,
15079 // and the one a single shared scale factor would get wrong.
15080 if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) {
15081 MIXED_SCALE_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
15082 }
15083
15084 let mut inter0_y = vec![0i32; side * side];
15085 mc::predict_compound_intermediate(
15086 &py0.data,
15087 py0.width,
15088 py0.true_width,
15089 py0.true_height,
15090 mv_to_q4(px, mv0.1, true),
15091 mv_to_q4(py, mv0.0, true),
15092 scale0,
15093 side,
15094 side,
15095 h_filter,
15096 v_filter,
15097 &mut inter0_y,
15098 );
15099 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
15100 // translational tap (libaom `av1_warp_plane` with
15101 // `conv_params->is_compound`); the blend below is unchanged.
15102 if let Some(wp) = &warp0 {
15103 crate::warp::warp_affine_compound(
15104 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
15105 py0.width as i32, &mut inter0_y, px as i32, py as i32, side as i32,
15106 side as i32, side as i32, 0, 0,
15107 );
15108 }
15109 let mut inter1_y = vec![0i32; side * side];
15110 mc::predict_compound_intermediate(
15111 &py1.data,
15112 py1.width,
15113 py1.true_width,
15114 py1.true_height,
15115 mv_to_q4(px, mv1.1, true),
15116 mv_to_q4(py, mv1.0, true),
15117 scale1,
15118 side,
15119 side,
15120 h_filter,
15121 v_filter,
15122 &mut inter1_y,
15123 );
15124 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
15125 // translational tap (libaom `av1_warp_plane` with
15126 // `conv_params->is_compound`); the blend below is unchanged.
15127 if let Some(wp) = &warp1 {
15128 crate::warp::warp_affine_compound(
15129 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
15130 py1.width as i32, &mut inter1_y, px as i32, py as i32, side as i32,
15131 side as i32, side as i32, 0, 0,
15132 );
15133 }
15134 let mut pred_y = vec![0u16; side * side];
15135 let mut diffwtd_mask_y = Vec::new();
15136 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
15137 // the wedge codebook lookup (comp_group_idx==1's two mutually
15138 // exclusive branches) -- same [`mc::blend_masked_compound`] call
15139 // either way, only the mask source differs.
15140 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
15141 diffwtd_mask_y = vec![0u8; side * side];
15142 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
15143 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
15144 Some(diffwtd_mask_y.as_slice())
15145 } else {
15146 wedge_mask
15147 };
15148 if let Some(mask_y) = mask_y {
15149 mc::blend_masked_compound(
15150 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
15151 );
15152 } else {
15153 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
15154 }
15155
15156 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
15157 mc::predict_compound_intermediate(
15158 &pu0.data,
15159 pu0.width,
15160 pu0.true_width,
15161 pu0.true_height,
15162 mv_to_q4(cpx, mv0.1, false),
15163 mv_to_q4(cpy, mv0.0, false),
15164 scale0,
15165 chroma_side,
15166 chroma_side,
15167 h_filter,
15168 v_filter,
15169 &mut inter0_u,
15170 );
15171 // `av1_init_warp_params` bails when the PLANE's block is
15172 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
15173 // block of an 8x8 luma block stays translational.
15174 if let Some(wp) = &warp0 {
15175 if chroma_side >= 8 {
15176 crate::warp::warp_affine_compound(
15177 wp, &pu0.data, pu0.true_width as i32, pu0.true_height as i32,
15178 pu0.width as i32, &mut inter0_u, cpx as i32, cpy as i32,
15179 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
15180 );
15181 }
15182 }
15183 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
15184 mc::predict_compound_intermediate(
15185 &pu1.data,
15186 pu1.width,
15187 pu1.true_width,
15188 pu1.true_height,
15189 mv_to_q4(cpx, mv1.1, false),
15190 mv_to_q4(cpy, mv1.0, false),
15191 scale1,
15192 chroma_side,
15193 chroma_side,
15194 h_filter,
15195 v_filter,
15196 &mut inter1_u,
15197 );
15198 // `av1_init_warp_params` bails when the PLANE's block is
15199 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
15200 // block of an 8x8 luma block stays translational.
15201 if let Some(wp) = &warp1 {
15202 if chroma_side >= 8 {
15203 crate::warp::warp_affine_compound(
15204 wp, &pu1.data, pu1.true_width as i32, pu1.true_height as i32,
15205 pu1.width as i32, &mut inter1_u, cpx as i32, cpy as i32,
15206 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
15207 );
15208 }
15209 }
15210 let mut pred_u = vec![0u16; chroma_side * chroma_side];
15211 if let Some(mask_y) = mask_y {
15212 mc::blend_masked_compound(
15213 &inter0_u,
15214 &inter1_u,
15215 mask_y,
15216 side,
15217 chroma_side,
15218 chroma_side,
15219 true,
15220 &mut pred_u,
15221 );
15222 } else {
15223 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
15224 }
15225
15226 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
15227 mc::predict_compound_intermediate(
15228 &pv0.data,
15229 pv0.width,
15230 pv0.true_width,
15231 pv0.true_height,
15232 mv_to_q4(cpx, mv0.1, false),
15233 mv_to_q4(cpy, mv0.0, false),
15234 scale0,
15235 chroma_side,
15236 chroma_side,
15237 h_filter,
15238 v_filter,
15239 &mut inter0_v,
15240 );
15241 // `av1_init_warp_params` bails when the PLANE's block is
15242 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
15243 // block of an 8x8 luma block stays translational.
15244 if let Some(wp) = &warp0 {
15245 if chroma_side >= 8 {
15246 crate::warp::warp_affine_compound(
15247 wp, &pv0.data, pv0.true_width as i32, pv0.true_height as i32,
15248 pv0.width as i32, &mut inter0_v, cpx as i32, cpy as i32,
15249 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
15250 );
15251 }
15252 }
15253 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
15254 mc::predict_compound_intermediate(
15255 &pv1.data,
15256 pv1.width,
15257 pv1.true_width,
15258 pv1.true_height,
15259 mv_to_q4(cpx, mv1.1, false),
15260 mv_to_q4(cpy, mv1.0, false),
15261 scale1,
15262 chroma_side,
15263 chroma_side,
15264 h_filter,
15265 v_filter,
15266 &mut inter1_v,
15267 );
15268 // `av1_init_warp_params` bails when the PLANE's block is
15269 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
15270 // block of an 8x8 luma block stays translational.
15271 if let Some(wp) = &warp1 {
15272 if chroma_side >= 8 {
15273 crate::warp::warp_affine_compound(
15274 wp, &pv1.data, pv1.true_width as i32, pv1.true_height as i32,
15275 pv1.width as i32, &mut inter1_v, cpx as i32, cpy as i32,
15276 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
15277 );
15278 }
15279 }
15280 let mut pred_v = vec![0u16; chroma_side * chroma_side];
15281 if let Some(mask_y) = mask_y {
15282 mc::blend_masked_compound(
15283 &inter0_v,
15284 &inter1_v,
15285 mask_y,
15286 side,
15287 chroma_side,
15288 chroma_side,
15289 true,
15290 &mut pred_v,
15291 );
15292 } else {
15293 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
15294 }
15295
15296 vartx_leaves = read_block_tx_size(
15297 dec,
15298 cdfs,
15299 neighbours,
15300 at_mi,
15301 side,
15302 (mi_cols as usize, mi_rows as usize),
15303 true,
15304 skip,
15305 )?
15306 .1;
15307 if skip {
15308 y.reconstruct_mc_rect(
15309 px,
15310 py,
15311 side,
15312 write_w,
15313 write_h,
15314 &pred_y,
15315 &vec![0i32; side * side],
15316 );
15317 u.reconstruct_mc_rect(
15318 cpx,
15319 cpy,
15320 chroma_side,
15321 write_chroma_w,
15322 write_chroma_h,
15323 &pred_u,
15324 &vec![0i32; chroma_side * chroma_side],
15325 );
15326 v.reconstruct_mc_rect(
15327 cpx,
15328 cpy,
15329 chroma_side,
15330 write_chroma_w,
15331 write_chroma_h,
15332 &pred_v,
15333 &vec![0i32; chroma_side * chroma_side],
15334 );
15335 luma_grid = vec![0i32; side * side];
15336 u_grid = vec![0i32; chroma_side * chroma_side];
15337 v_grid = vec![0i32; chroma_side * chroma_side];
15338 } else {
15339 let around = neighbours.around(at, side);
15340 let luma_tx_type;
15341 if let Some(leaves) = vartx_leaves.clone() {
15342 // spec 5.11.17's transform tree, leaf by leaf in the order
15343 // `read_var_tx_size` coded it: each unit reads its own
15344 // coefficients against the neighbour magnitudes the
15345 // earlier units already wrote, and reconstructs over its
15346 // own slice of the block's motion-compensated predictor.
15347 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
15348 let mut first_tx_type = TxType::DctDct;
15349 for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() {
15350 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
15351 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
15352 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
15353 for rr in 0..tx_px {
15354 let start = (row * MI + rr) * side + col * MI;
15355 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
15356 }
15357 let scan = default_scan(tx_px);
15358 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
15359 let (tu_grid, tu_tx_type) = read_inter_plane(
15360 dec,
15361 cdfs,
15362 inter_txbset_for(tx_px, reduced),
15363 &scan,
15364 0,
15365 neighbours.around_mi(tu_mi, tx_px)[0],
15366 mode_for_tx,
15367 y,
15368 tu_px,
15369 tu_py,
15370 tx_px,
15371 base_q_idx,
15372 &tu_pred,
15373 None,
15374 Some(tu_skip_ctx),
15375 )?;
15376 if idx == 0 {
15377 first_tx_type = tu_tx_type;
15378 }
15379 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
15380 }
15381 // `av1_get_tx_type`'s chroma lookup scales the chroma
15382 // position back to luma, so an inter block's chroma
15383 // inherits the *first* (top-left) luma unit's coded type.
15384 luma_tx_type = first_tx_type;
15385 luma_grid = vec![0i32; side * side];
15386 } else {
15387 (luma_grid, luma_tx_type) = read_inter_plane(
15388 dec,
15389 cdfs,
15390 luma_set_inter,
15391 scan_luma,
15392 0,
15393 around[0],
15394 mode_for_tx,
15395 y,
15396 px,
15397 py,
15398 side,
15399 base_q_idx,
15400 &pred_y,
15401 None,
15402 None,
15403 )?;
15404 }
15405 u_grid = read_inter_plane(
15406 dec,
15407 cdfs,
15408 chroma_set,
15409 scan_chroma,
15410 1,
15411 around[1],
15412 mode_for_tx,
15413 u,
15414 cpx,
15415 cpy,
15416 chroma_side,
15417 base_q_idx,
15418 &pred_u,
15419 Some(luma_tx_type),
15420 None,
15421 )?
15422 .0;
15423 v_grid = read_inter_plane(
15424 dec,
15425 cdfs,
15426 chroma_set,
15427 scan_chroma,
15428 2,
15429 around[2],
15430 mode_for_tx,
15431 v,
15432 cpx,
15433 cpy,
15434 chroma_side,
15435 base_q_idx,
15436 &pred_v,
15437 Some(luma_tx_type),
15438 None,
15439 )?
15440 .0;
15441 }
15442 } else {
15443 let ref_frame =
15444 read_single_ref(
15445 dec,
15446 cdfs,
15447 neighbours.above_ref[cmi],
15448 neighbours.above_ref1[cmi],
15449 neighbours.left_ref[rmi],
15450 neighbours.left_ref1[rmi],
15451 );
15452 ref_frame_for_lf = ref_frame;
15453 if std::env::var_os("EC_AV1_TELL").is_some() {
15454 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
15455 eprintln!(
15456 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
15457 dec.debug_bitpos(), dec.debug_state().0
15458 );
15459 }
15460 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
15461 // stacked defects (lf_level ref/mode-delta forwarding, the
15462 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
15463 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
15464 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
15465 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
15466 // widens this from GOLDEN alone to every reference `read_single_ref`
15467 // can name.
15468 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
15469 (ref_y, ref_u, ref_v)
15470 } else {
15471 match other_refs[ref_frame as usize] {
15472 Some((ry, ru, rv)) => (ry, ru, rv),
15473 None => {
15474 return Err(unsupported(
15475 "a reference frame selected with no picture at this frame's own \
15476 ref_frame_idx slot for it",
15477 ));
15478 }
15479 }
15480 };
15481
15482 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
15483 // lane-rect r2: the mv stack must be queried with the block's
15484 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
15485 // xd->width/xd->height, not a square guess) -- `write_w`/
15486 // `write_h` already name the true HORZ/VERT/HORZ_B strip
15487 // footprint (r1's plumbing), so derive bw4/bh4 from those
15488 // instead of the old `side`-square (HORZ_B-only) heuristic.
15489 let bw4 = write_w / 4;
15490 let bh4 = write_h / 4;
15491 // spec 7.10.2.8: only reached when the frame header set
15492 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
15493 // otherwise) -- `cur_offset_0` is this query block's own resolved
15494 // `ref_frame`'s distance from the current frame (spec 7.9.3),
15495 // recomputed per block since different blocks pick different refs.
15496 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
15497 field: t.field,
15498 cur_offset_0: crate::motion_field::get_relative_dist(
15499 t.order_hint_bits,
15500 t.order_hint,
15501 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
15502 ),
15503 allow_high_precision_mv,
15504 });
15505 let gm_table = build_gm_mv_table(
15506 global_motion,
15507 mi_row,
15508 mi_col,
15509 bw4,
15510 bh4,
15511 allow_high_precision_mv,
15512 force_integer_mv,
15513 );
15514 let stack = find_mv_stack_with_sign_bias(
15515 grid,
15516 mi_row,
15517 mi_col,
15518 bw4,
15519 bh4,
15520 ref_frame,
15521 mi_cols as usize,
15522 mi_rows as usize,
15523 sign_bias_table,
15524 &gm_table,
15525 tpl,
15526 );
15527 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
15528 let mut is_globalmv = false;
15529 let (mv, is_new_mv) = if !not_new {
15530 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
15531 // read at most two `drl_mode` bits, one per stack entry past the
15532 // first, stopping at the first `0`. The chosen index selects
15533 // which stack entry `read_mv`'s base predictor comes from
15534 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
15535 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
15536 let mut idx = 0usize;
15537 while idx < 2 && stack.entries.len() > idx + 1 {
15538 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
15539 break;
15540 }
15541 idx += 1;
15542 }
15543 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
15544 (
15545 read_mv(
15546 dec,
15547 &mut cdfs.mv_comp,
15548 &mut cdfs.mv_joint,
15549 base_mv,
15550 allow_high_precision_mv,
15551 force_integer_mv,
15552 ),
15553 true,
15554 )
15555 } else {
15556 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
15557 is_globalmv = !not_zero;
15558 let mv = if !not_zero {
15559 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
15560 // computed at this block's own position in `gm_table`.
15561 gm_table[(ref_frame - LAST_FRAME) as usize]
15562 } else {
15563 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
15564 if nearest {
15565 stack.nearest_mv
15566 } else {
15567 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
15568 // at 1): read at most two more `drl_mode` bits, one per stack
15569 // entry past the second, stopping at the first `0`.
15570 // `drl_ctx[idx]` is the context between `entries[idx]` and
15571 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
15572 // exactly the pair this index is choosing between.
15573 let mut idx = 1usize;
15574 while idx < 3 && stack.entries.len() > idx + 1 {
15575 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
15576 break;
15577 }
15578 idx += 1;
15579 }
15580 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
15581 }
15582 };
15583 (mv, false)
15584 };
15585 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
15586 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
15587 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
15588 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
15589 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
15590 // TRANSLATION -- IDENTITY counts here -- gating the interp
15591 // filter suppress below). Do NOT unify these.
15592 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
15593 let min_bw_bh4 = bw4.min(bh4);
15594 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
15595 let gm_nontrans =
15596 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
15597 if std::env::var_os("EC_AV1_TELL").is_some() {
15598 eprintln!(
15599 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
15600 dec.debug_bitpos(), dec.debug_state().0
15601 );
15602 }
15603 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
15604 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
15605 // right after `assign_mv` and before `read_motion_mode` below --
15606 // libaom's own sequential order. `is_interintra_allowed_bsize`
15607 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
15608 // single-ref path: `is_interintra_allowed_ref` always holds here
15609 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
15610 // `is_interintra_allowed_mode` always holds (every mode this
15611 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
15612 // `SINGLE_INTER_MODE_START..END` by construction).
15613 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
15614 let mut interintra_mode: Option<u8> = None;
15615 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
15616 if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) {
15617 let bsize_group = if side == 16 { 2 } else { 3 };
15618 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
15619 if interintra {
15620 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
15621 // then -- gated on block size ALONE, never the
15622 // `enable_interintra_wedge` seq bit -- the wedge flag
15623 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
15624 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
15625 let wedge_bsize = if side == 16 { 6 } else { 9 };
15626 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
15627 if wedge {
15628 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
15629 // ADAPTING CDF symbol over the same `wedge_bsize` row;
15630 // NO sign symbol follows -- libaom fixes
15631 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
15632 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
15633 WII_HITS.with(|c| c.set(c.get() + 1));
15634 wedge_mask = Some((
15635 crate::wedge::wedge_masks()
15636 .codebook(side)
15637 .mask(0, wedge_index as usize),
15638 side,
15639 ));
15640 } else {
15641 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
15642 }
15643 interintra_mode = Some(ii);
15644 }
15645 }
15646 if std::env::var_os("EC_AV1_TELL").is_some() {
15647 eprintln!(
15648 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
15649 dec.debug_bitpos(), dec.debug_state().0
15650 );
15651 }
15652 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
15653 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
15654 // placed right after MV assignment and before the switchable
15655 // interp filter read below (`read_mb_interp_filter`, decodemv.c
15656 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
15657 // (`reconinter.h`) reduces, for every block this single-ref path
15658 // reaches, to "does an inter neighbour border the above row or
15659 // left column": `is_motion_variation_allowed_bsize` always holds
15660 // (`side` is never below 16px on this path), `ref_frame[1] !=
15661 // INTRA_FRAME` always holds (no interintra reader here),
15662 // `is_motion_variation_allowed_compound` always holds (this is
15663 // the single-ref branch), and `is_global_mv_block` never
15664 // triggers (this decoder's global motion is always `IDENTITY`,
15665 // so its warp `type` is never `> TRANSLATION`). A stream with
15666 // `allow_warped_motion=1` is refused right at an eligible block
15667 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
15668 // not ported, so this decoder cannot tell a real
15669 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
15670 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
15671 // the header allows warp -- reading the wrong alphabet desyncs
15672 // the tile.
15673 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
15674 // fails libaom's `is_motion_variation_allowed_compound`: the
15675 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
15676 let motion_mode_eligible = switchable_motion_mode
15677 && !skip_mode
15678 && interintra_mode.is_none()
15679 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
15680 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
15681 .is_empty())
15682 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
15683 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
15684 // mv reads no motion_mode/obmc symbol at all -- implicit
15685 // SIMPLE_TRANSLATION.
15686 && !(is_global_mv_block && !force_integer_mv);
15687 let mut obmc_selected = false;
15688 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
15689 // *and* the local warp estimate is valid (`!wm_params.invalid`,
15690 // `av1_find_projection`) -- an invalid estimate falls back to
15691 // this block's own translational mv, same as any other block
15692 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
15693 // fallback here since this decoder's global motion is always
15694 // IDENTITY).
15695 let mut warp_params: Option<crate::warp::WarpParams> = None;
15696 // Tracks the SYMBOL value, not projection validity: libaom's
15697 // `av1_is_interp_needed` suppresses the interp-filter read for
15698 // `motion_mode == WARPED_CAUSAL` even when the projection later
15699 // falls back to translation. Its third suppressor,
15700 // `is_nontrans_global_motion`, matches our unconditional
15701 // `is_globalmv` only because this decoder codes global motion as
15702 // IDENTITY (non-TRANSLATION) and never reads switchable filters
15703 // below 8x8 -- porting TRANSLATION global motion must add the
15704 // wmtype check here.
15705 let mut warped_selected = false;
15706 if motion_mode_eligible {
15707 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
15708 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
15709 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
15710 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
15711 // strip motion_mode read diverged on the square row.
15712 let bsize_idx = if write_w == write_h {
15713 (write_w.trailing_zeros() - 3) as usize
15714 } else if write_w == 16 {
15715 4
15716 } else {
15717 5
15718 };
15719 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
15720 // instead of the 2-symbol `obmc_cdf` exactly when
15721 // `num_proj_ref >= 1` under `allow_warped_motion`.
15722 // lane-scaledref r2 + lane-fimv r1: libaom
15723 // `motion_mode_allowed` (`blockd.h:1484`) requires BOTH
15724 // `!av1_is_scaled(block_ref_scale_factors[0])` and
15725 // `!xd->cur_frame_force_integer_mv` for WARPED_CAUSAL --
15726 // under a scaled reference (superres) OR on a frame whose
15727 // header set `force_integer_mv` (screen content) the block
15728 // reads the 2-symbol `obmc_cdf`, never the 3-symbol
15729 // `motion_mode_cdf`. Reading the wrong alphabet here narrows
15730 // the arithmetic coder by the wrong amount and predicts the
15731 // rest of the tile off a diverged state: silently wrong
15732 // pixels, not a desync error. `force_integer_mv` is the
15733 // per-frame value (spec 5.9.2: coded per frame only when
15734 // `seq_force_integer_mv == SELECT_INTEGER_MV`, threaded from
15735 // `FrameHeader::force_integer_mv`).
15736 // libaom `av1_is_scaled` is `x_scale_fp != REF_NO_SCALE ||
15737 // y_scale_fp != REF_NO_SCALE`; the y half is unreachable here
15738 // because a reference whose height differs from this frame's
15739 // true size is refused before any tile decodes ("a reference
15740 // picture whose height does not match this frame's own true
15741 // size", ~14681). Whoever lifts that refusal adds the y term.
15742 let ref_is_scaled =
15743 mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE;
15744 let proj_ok = num_proj_ref(
15745 grid,
15746 mi_row,
15747 mi_col,
15748 bw4,
15749 bh4,
15750 mi_cols as usize,
15751 mi_rows as usize,
15752 ref_frame,
15753 ) >= 1;
15754 let warp_eligible =
15755 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
15756 if allow_warped_motion && proj_ok && ref_is_scaled {
15757 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1));
15758 }
15759 if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv {
15760 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
15761 }
15762 if warp_eligible {
15763 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
15764 match mode {
15765 0 => {}
15766 1 => {
15767 obmc_selected = true;
15768 OBMC_HITS.with(|c| c.set(c.get() + 1));
15769 }
15770 _ => {
15771 warped_selected = true;
15772 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
15773 let mut samples = find_samples(
15774 grid,
15775 mi_row,
15776 mi_col,
15777 bw4,
15778 bh4,
15779 mi_cols as usize,
15780 mi_rows as usize,
15781 ref_frame,
15782 );
15783 if std::env::var_os("EC_WARP_DEBUG").is_some() {
15784 eprintln!(
15785 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
15786 samples.len()
15787 );
15788 for (i, s) in samples.iter().enumerate() {
15789 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
15790 }
15791 }
15792 if samples.len() > 1 {
15793 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
15794 }
15795 warp_params = crate::warp::find_projection(
15796 &samples,
15797 // lane-rect r2: the block's TRUE dims -- a
15798 // 32x16 strip's model center is not a
15799 // 32x32's (aom av1_find_projection bw/bh).
15800 write_w as i32,
15801 write_h as i32,
15802 mv.1,
15803 mv.0,
15804 mi_row as i32,
15805 mi_col as i32,
15806 );
15807 if std::env::var_os("EC_WARP_DEBUG").is_some() {
15808 eprintln!(
15809 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
15810 samples.len(), mv.0, mv.1, warp_params
15811 );
15812 for (i, s) in samples.iter().enumerate() {
15813 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
15814 }
15815 }
15816 }
15817 }
15818 } else {
15819 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
15820 if obmc_selected {
15821 OBMC_HITS.with(|c| c.set(c.get() + 1));
15822 }
15823 }
15824 }
15825 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
15826 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
15827 // libaom's `av1_init_warp_params` runs for every inter
15828 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
15829 // reachable when `warp_params` is still `None` here: a block
15830 // that read (and got) local `WARPED_CAUSAL` above already has
15831 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
15832 // checks FIRST and short-circuits on -- the global branch is an
15833 // `else if`, never layered on top. `is_global_mv_block` already
15834 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
15835 // >=8px both dims, matching `av1_init_warp_params`'s
15836 // `block_height < 8 || block_width < 8` early return) and, via
15837 // `motion_mode_eligible`'s own suppression above, the
15838 // `force_integer_mv` case never reads a motion_mode symbol at
15839 // all -- checked again here directly since this branch fires
15840 // independent of `motion_mode_eligible`.
15841 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
15842 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
15843 warp_params = crate::warp::global_warp_params(gm_ref.params);
15844 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
15845 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
15846 }
15847 }
15848 if std::env::var_os("EC_AV1_TELL").is_some() {
15849 eprintln!(
15850 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
15851 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
15852 );
15853 }
15854 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
15855 // this block's switchable_interp context when that neighbour coded
15856 // the SAME reference frame this block is about to read -- a
15857 // different-ref neighbour reads as "no neighbour" ([3, 3], the
15858 // sentinel `Neighbours::new` already seeds unset slots with),
15859 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
15860 // block next to a LAST_FRAME one inherits that neighbour's filter
15861 // choice into its own context, corrupting the symbol it reads.
15862 // lane-av1idx r2: also match on the neighbour's SECOND reference
15863 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
15864 // see the 16x16 leaf's own comment above for the spec citation.
15865 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
15866 || neighbours.above_ref1[cmi] == Some(ref_frame)
15867 {
15868 neighbours.above_filter[cmi]
15869 } else {
15870 [3, 3]
15871 };
15872 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
15873 || neighbours.left_ref1[rmi] == Some(ref_frame)
15874 {
15875 neighbours.left_filter[rmi]
15876 } else {
15877 [3, 3]
15878 };
15879 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
15880 dec,
15881 cdfs,
15882 interp_fixed,
15883 enable_dual_filter,
15884 gm_nontrans || warped_selected,
15885 above_filter_ctx,
15886 left_filter_ctx,
15887 false,
15888 );
15889 block_filter = resolved_filter;
15890 globalmv_for_lf = is_globalmv;
15891 if std::env::var_os("EC_AV1_TELL").is_some() {
15892 eprintln!(
15893 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
15894 dec.debug_bitpos(), dec.debug_state().0
15895 );
15896 }
15897 if std::env::var_os("EC_AV1_TRACE").is_some() {
15898 eprintln!(
15899 "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={:?} motion_mode_eligible={} obmc_selected={} warped={} tell={}",
15900 skip as u8, mv.0, mv.1, block_filter, motion_mode_eligible as u8, obmc_selected as u8, warp_params.is_some() as u8, dec.debug_bitpos()
15901 );
15902 }
15903 // lane-rect r2: see the compound path's matching comment above --
15904 // `grid` must be stamped with the block's true bh4/bw4 span, not
15905 // a square `bw4`x`bw4` guess.
15906 for dr in 0..bh4 {
15907 for dc in 0..bw4 {
15908 grid.set(
15909 mi_row + dr,
15910 mi_col + dc,
15911 MiInfo {
15912 is_inter: true,
15913 ref_frame,
15914 // An interintra block records ref_frame[1] ==
15915 // INTRA_FRAME (0): warp-sample gathering
15916 // (libaom av1_findSamples, mvref_common.c:1155)
15917 // requires ref_frame[1] == NONE_FRAME, so such a
15918 // neighbour must not donate samples or count in
15919 // num_proj_ref.
15920 ref_frame1: interintra_mode.map(|_| 0),
15921 mv1: None,
15922 mv,
15923 is_new_mv,
15924 size: bw4,
15925 size_h: bh4,
15926 is_global_mv0: is_global_mv_block,
15927 is_global_mv1: false,
15928 },
15929 );
15930 }
15931 }
15932 mode_for_tx = 0;
15933 uv_predict_mode = DC_PRED;
15934
15935 // lane-superres r9: spec 7.11.3.3's x_scale_fp comes from LUMA
15936 // widths only (r8's derivation) and applies unchanged to the
15937 // chroma calls below (their x_q4 is already in the chroma
15938 // plane's own pixel units). `mc::predict_scaled` has no warp/OBMC
15939 // /interintra counterpart -- those three combinations are refused
15940 // by name instead of silently sampling a scaled reference wrong
15941 // (warp_params/obmc_selected/interintra_mode are all resolved by
15942 // this point, every symbol for this block already read).
15943 let luma_scale = mc::scale_factor(py_ref.width, frame_width);
15944 if luma_scale != mc::REF_NO_SCALE {
15945 // lane-scaledref r1: libaom `allow_warp`
15946 // (av1/common/reconinter.c:41) suppresses BOTH local and
15947 // global warp under a scaled reference and predicts
15948 // translationally instead -- that fallback is implemented
15949 // below, but the one real aomenc stream this round found
15950 // that reaches it (`--enable-warped-motion=1`,
15951 // `--superres-denominator=16`, seed 47) still mismatches
15952 // ffmpeg at frame 2 luma, so the case stays refused by name
15953 // until it has a green gate rather than shipping wrong
15954 // pixels behind a lifted refusal.
15955 if warp_params.is_some() {
15956 SCALED_WARP_FALLBACK_HITS.with(|c| c.set(c.get() + 1));
15957 return Err(unsupported(
15958 "warp prediction with a scaled reference (superres, unimplemented)",
15959 ));
15960 }
15961 if obmc_selected {
15962 SCALED_OBMC_HITS.with(|c| c.set(c.get() + 1));
15963 }
15964 if interintra_mode.is_some() {
15965 SCALED_INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
15966 }
15967 }
15968
15969 let mut pred_y = vec![0u16; side * side];
15970 let mut pred_u = vec![0u16; chroma_side * chroma_side];
15971 let mut pred_v = vec![0u16; chroma_side * chroma_side];
15972 if luma_scale == mc::REF_NO_SCALE {
15973 mc::predict_with_filters(
15974 &py_ref.data,
15975 py_ref.width,
15976 py_ref.true_width,
15977 py_ref.true_height,
15978 mv_to_q4(px, mv.1, true),
15979 mv_to_q4(py, mv.0, true),
15980 side,
15981 side,
15982 h_filter,
15983 v_filter,
15984 &mut pred_y,
15985 );
15986 mc::predict_with_filters(
15987 &pu_ref.data,
15988 pu_ref.width,
15989 pu_ref.true_width,
15990 pu_ref.true_height,
15991 mv_to_q4(cpx, mv.1, false),
15992 mv_to_q4(cpy, mv.0, false),
15993 chroma_side,
15994 chroma_side,
15995 h_filter,
15996 v_filter,
15997 &mut pred_u,
15998 );
15999 mc::predict_with_filters(
16000 &pv_ref.data,
16001 pv_ref.width,
16002 pv_ref.true_width,
16003 pv_ref.true_height,
16004 mv_to_q4(cpx, mv.1, false),
16005 mv_to_q4(cpy, mv.0, false),
16006 chroma_side,
16007 chroma_side,
16008 h_filter,
16009 v_filter,
16010 &mut pred_v,
16011 );
16012 } else {
16013 mc::predict_scaled(
16014 &py_ref.data,
16015 py_ref.width,
16016 py_ref.true_width,
16017 py_ref.true_height,
16018 mv_to_q4(px, mv.1, true),
16019 mv_to_q4(py, mv.0, true),
16020 luma_scale,
16021 side,
16022 side,
16023 h_filter,
16024 v_filter,
16025 &mut pred_y,
16026 );
16027 mc::predict_scaled(
16028 &pu_ref.data,
16029 pu_ref.width,
16030 pu_ref.true_width,
16031 pu_ref.true_height,
16032 mv_to_q4(cpx, mv.1, false),
16033 mv_to_q4(cpy, mv.0, false),
16034 luma_scale,
16035 chroma_side,
16036 chroma_side,
16037 h_filter,
16038 v_filter,
16039 &mut pred_u,
16040 );
16041 mc::predict_scaled(
16042 &pv_ref.data,
16043 pv_ref.width,
16044 pv_ref.true_width,
16045 pv_ref.true_height,
16046 mv_to_q4(cpx, mv.1, false),
16047 mv_to_q4(cpy, mv.0, false),
16048 luma_scale,
16049 chroma_side,
16050 chroma_side,
16051 h_filter,
16052 v_filter,
16053 &mut pred_v,
16054 );
16055 }
16056
16057 // lane-scaledref r1: libaom `allow_warp` (av1/common/reconinter.c:41)
16058 // opens with `if (av1_is_scaled(sf)) return 0;` -- BOTH local
16059 // (`wm_params`) and global warp fall back to the translational
16060 // prediction above when the reference is scaled, even though the
16061 // motion_mode symbol was still read and warp_params still
16062 // resolved. Suppress the warp, keep every symbol read.
16063 if let Some(params) = warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE) {
16064 crate::warp::warp_affine(
16065 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
16066 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
16067 side as i32, side as i32, 0, 0,
16068 );
16069 // libaom `av1_init_warp_params` (reconinter.c): warp is
16070 // per PLANE and bails out at `block_width < 8 ||
16071 // block_height < 8`, so a plane whose own block is under
16072 // 8x8 keeps the translational prediction built above --
16073 // in 420 that is every chroma plane of a luma block below
16074 // 16x16 (lane-gmaffine r4: chroma-only mismatch of a few
16075 // levels on both 8x8-leaf motion gates).
16076 if chroma_side >= 8 {
16077 crate::warp::warp_affine(
16078 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
16079 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
16080 chroma_side as i32, chroma_side as i32, 1, 1,
16081 );
16082 crate::warp::warp_affine(
16083 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
16084 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
16085 chroma_side as i32, chroma_side as i32, 1, 1,
16086 );
16087 }
16088 }
16089
16090 if obmc_selected {
16091 obmc_blend(
16092 grid,
16093 neighbours,
16094 mi_row,
16095 mi_col,
16096 bw4,
16097 bh4,
16098 mi_rows as usize,
16099 mi_cols as usize,
16100 side,
16101 write_w,
16102 write_h,
16103 chroma_side,
16104 px,
16105 py,
16106 cpx,
16107 cpy,
16108 ref_y,
16109 ref_u,
16110 ref_v,
16111 other_refs,
16112 interp_fixed,
16113 frame_width,
16114 &mut pred_y,
16115 &mut pred_u,
16116 &mut pred_v,
16117 )?;
16118 }
16119
16120 // Mutually exclusive with warp/OBMC (motion_mode is not read for
16121 // an interintra block): blend the intra predictor over the MC
16122 // result, all planes (reconinter.c av1_build_interintra_predictor
16123 // plane loop).
16124 if let Some(ii) = interintra_mode {
16125 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
16126 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
16127 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
16128 }
16129
16130 vartx_leaves = read_block_tx_size(
16131 dec,
16132 cdfs,
16133 neighbours,
16134 at_mi,
16135 side,
16136 (mi_cols as usize, mi_rows as usize),
16137 true,
16138 skip,
16139 )?
16140 .1;
16141 if skip {
16142 y.reconstruct_mc_rect(
16143 px,
16144 py,
16145 side,
16146 write_w,
16147 write_h,
16148 &pred_y,
16149 &vec![0i32; side * side],
16150 );
16151 u.reconstruct_mc_rect(
16152 cpx,
16153 cpy,
16154 chroma_side,
16155 write_chroma_w,
16156 write_chroma_h,
16157 &pred_u,
16158 &vec![0i32; chroma_side * chroma_side],
16159 );
16160 v.reconstruct_mc_rect(
16161 cpx,
16162 cpy,
16163 chroma_side,
16164 write_chroma_w,
16165 write_chroma_h,
16166 &pred_v,
16167 &vec![0i32; chroma_side * chroma_side],
16168 );
16169 luma_grid = vec![0i32; side * side];
16170 u_grid = vec![0i32; chroma_side * chroma_side];
16171 v_grid = vec![0i32; chroma_side * chroma_side];
16172 } else {
16173 let around = neighbours.around(at, side);
16174 let luma_tx_type;
16175 if let Some(leaves) = vartx_leaves.clone() {
16176 // spec 5.11.17's transform tree, leaf by leaf in the order
16177 // `read_var_tx_size` coded it: each unit reads its own
16178 // coefficients against the neighbour magnitudes the
16179 // earlier units already wrote, and reconstructs over its
16180 // own slice of the block's motion-compensated predictor.
16181 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
16182 let mut first_tx_type = TxType::DctDct;
16183 for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() {
16184 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
16185 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
16186 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
16187 for rr in 0..tx_px {
16188 let start = (row * MI + rr) * side + col * MI;
16189 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
16190 }
16191 let scan = default_scan(tx_px);
16192 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
16193 let (tu_grid, tu_tx_type) = read_inter_plane(
16194 dec,
16195 cdfs,
16196 inter_txbset_for(tx_px, reduced),
16197 &scan,
16198 0,
16199 neighbours.around_mi(tu_mi, tx_px)[0],
16200 mode_for_tx,
16201 y,
16202 tu_px,
16203 tu_py,
16204 tx_px,
16205 base_q_idx,
16206 &tu_pred,
16207 None,
16208 Some(tu_skip_ctx),
16209 )?;
16210 if idx == 0 {
16211 first_tx_type = tu_tx_type;
16212 }
16213 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
16214 }
16215 // `av1_get_tx_type`'s chroma lookup scales the chroma
16216 // position back to luma, so an inter block's chroma
16217 // inherits the *first* (top-left) luma unit's coded type.
16218 luma_tx_type = first_tx_type;
16219 luma_grid = vec![0i32; side * side];
16220 } else {
16221 (luma_grid, luma_tx_type) = read_inter_plane(
16222 dec,
16223 cdfs,
16224 luma_set_inter,
16225 scan_luma,
16226 0,
16227 around[0],
16228 mode_for_tx,
16229 y,
16230 px,
16231 py,
16232 side,
16233 base_q_idx,
16234 &pred_y,
16235 None,
16236 None,
16237 )?;
16238 }
16239 u_grid = read_inter_plane(
16240 dec,
16241 cdfs,
16242 chroma_set,
16243 scan_chroma,
16244 1,
16245 around[1],
16246 mode_for_tx,
16247 u,
16248 cpx,
16249 cpy,
16250 chroma_side,
16251 base_q_idx,
16252 &pred_u,
16253 Some(luma_tx_type),
16254 None,
16255 )?
16256 .0;
16257 v_grid = read_inter_plane(
16258 dec,
16259 cdfs,
16260 chroma_set,
16261 scan_chroma,
16262 2,
16263 around[2],
16264 mode_for_tx,
16265 v,
16266 cpx,
16267 cpy,
16268 chroma_side,
16269 base_q_idx,
16270 &pred_v,
16271 Some(luma_tx_type),
16272 None,
16273 )?
16274 .0;
16275 }
16276 }
16277 } else {
16278 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
16279 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
16280 // its own true-width/height edge/predict math, unlike the inter
16281 // skip path above (which only needed a clipped write of an
16282 // already-square-predicted buffer). Named refusal instead of a
16283 // silently wrong square-shaped intra prediction.
16284 if write_w != side || write_h != side {
16285 return Err(unsupported(
16286 "an intra-coded HORZ/VERT strip needs rectangular intra prediction \
16287 this decoder does not code yet",
16288 ));
16289 }
16290 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
16291 if mode >= 13 {
16292 return Err(unsupported(
16293 "an intra mode this decoder does not code (round 2)",
16294 ));
16295 }
16296 if (V_PRED..=D67_PRED).contains(&mode) {
16297 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
16298 if angle != ANGLE_DELTA_ZERO {
16299 return Err(unsupported(
16300 "a nonzero angle delta (this encoder never writes one)",
16301 ));
16302 }
16303 }
16304 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
16305 if (9..=12).contains(&uv_mode) {
16306 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
16307 }
16308 let alpha = if uv_mode == DC_PRED {
16309 None
16310 } else if uv_mode == UV_CFL_PRED {
16311 Some(read_cfl_alphas(dec, cdfs))
16312 } else {
16313 None
16314 };
16315 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
16316 // the angle-delta question, same as [`read_intra_mode`]'s own copy
16317 // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
16318 // `else` branch below is exact for it either way.
16319 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
16320 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
16321 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
16322 } else {
16323 0
16324 };
16325 if angle_delta_uv != 0 {
16326 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
16327 }
16328 uv_predict_mode = if uv_mode == UV_CFL_PRED {
16329 DC_PRED
16330 } else {
16331 uv_mode
16332 };
16333 // lane-chroma r4: same chroma edge-filter-strength neighbour check
16334 // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
16335 // neighbour's own `uv_mode`, not the luma one.
16336 let smooth_neighbor_uv =
16337 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
16338 // `read_palette_mode_info` (decodemv.c:567, called from
16339 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
16340 // gating and same corner-cut as `read_intra_mode`'s own copy above
16341 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
16342 // safe since a nonzero neighbour `palette_size` would already have
16343 // refused the decode that produced it.
16344 if allow_screen_content_tools
16345 && let Some(bsize_ctx) = palette_bsize_ctx(side)
16346 {
16347 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
16348 return Err(unsupported(
16349 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
16350 ));
16351 }
16352 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
16353 return Err(unsupported(
16354 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
16355 ));
16356 }
16357 }
16358 // lane-fiinter r1: `read_filter_intra_mode_info` (libaom `decodemv.c`,
16359 // the tail of `read_intra_block_mode_info`) -- an intra block inside
16360 // an INTER frame reads `use_filter_intra` in exactly the same place a
16361 // key-frame block does, right after the palette syntax. Nothing read
16362 // it here before this round, and aomenc enables filter intra by
16363 // default, so every inter frame carrying one desynced at this symbol.
16364 // `av1_filter_intra_allowed`'s `palette_size[0] == 0` term is implied:
16365 // a real palette-Y block already returned above.
16366 let mut filter_intra = None;
16367 if mode == DC_PRED
16368 && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
16369 && let Some(class) = filter_intra_size_class(side)
16370 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
16371 {
16372 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
16373 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
16374 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
16375 }
16376 mode_for_tx = mode;
16377 block_filter = [3, 3];
16378 ref_frame_for_lf = 0;
16379 globalmv_for_lf = false;
16380 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
16381 for dr in 0..side / 4 {
16382 for dc in 0..side / 4 {
16383 grid.set(
16384 mi_row + dr,
16385 mi_col + dc,
16386 MiInfo {
16387 is_inter: false,
16388 ref_frame: -1,
16389 ref_frame1: None,
16390 mv1: None,
16391 mv: (0, 0),
16392 is_new_mv: false,
16393 size: side / 4,
16394 size_h: side / 4,
16395 is_global_mv0: false,
16396 is_global_mv1: false,
16397 },
16398 );
16399 }
16400 }
16401
16402 // lane-intrainter r1: an intra block in an inter frame reads the same
16403 // `tx_depth` symbol a key-frame block does, and when it splits, the
16404 // block codes one intra prediction + one coefficient set PER
16405 // transform unit (`decode_block`'s multi-TU branch), not one for the
16406 // whole block. The leaf list rides the existing `vartx_leaves` slot,
16407 // whose tail already does the split-block neighbour write-back
16408 // (`record_split_luma`) and the per-TU deblock edges.
16409 vartx_leaves = read_block_tx_size(
16410 dec,
16411 cdfs,
16412 neighbours,
16413 at_mi,
16414 side,
16415 (mi_cols as usize, mi_rows as usize),
16416 false,
16417 skip,
16418 )?
16419 .1;
16420 let reach = Reach::of(side, px, py, y.width, y.height);
16421 let split_luma = vartx_leaves.is_some();
16422 if let Some(leaves) = vartx_leaves.clone() {
16423 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
16424 for &(row, col, tx_px) in &leaves {
16425 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
16426 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
16427 // A transform unit inside a block is not a block at that
16428 // position (class from lane-palette2 r12): top-right /
16429 // bottom-left availability is the block's, narrowed by the
16430 // unit's own offset inside it.
16431 let tu_reach = Reach::of_tu(side, side, col * MI, row * MI, tx_px, tx_px, reach);
16432 let tu_grid = if skip {
16433 y.reconstruct(
16434 tu_px,
16435 tu_py,
16436 tx_px,
16437 mode,
16438 0,
16439 tu_reach,
16440 &vec![0i32; tx_px * tx_px],
16441 None,
16442 filter_intra,
16443 false,
16444 );
16445 vec![0i32; tx_px * tx_px]
16446 } else {
16447 // The unit's bsize is smaller than the block it sits in,
16448 // so `txb_skip_ctx` is the neighbour-magnitude table, not
16449 // the lone-TU 0 (`get_txb_ctx_general`).
16450 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
16451 read_plane(
16452 dec,
16453 cdfs,
16454 txbset_for(tx_px, reduced),
16455 &default_scan(tx_px),
16456 0,
16457 neighbours.around_mi(tu_mi, tx_px)[0],
16458 mode,
16459 mode,
16460 0,
16461 tu_reach,
16462 y,
16463 tu_px,
16464 tu_py,
16465 tx_px,
16466 tx_px,
16467 base_q_idx,
16468 None,
16469 filter_intra,
16470 Some(tu_skip_ctx),
16471 false,
16472 )?
16473 };
16474 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
16475 }
16476 }
16477 if skip {
16478 if !split_luma {
16479 y.reconstruct(
16480 px,
16481 py,
16482 side,
16483 mode,
16484 0,
16485 reach,
16486 &vec![0i32; side * side],
16487 None,
16488 filter_intra,
16489 false,
16490 );
16491 }
16492 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
16493 u.reconstruct(
16494 cpx,
16495 cpy,
16496 chroma_side,
16497 uv_predict_mode,
16498 angle_delta_uv,
16499 reach,
16500 &vec![0i32; chroma_side * chroma_side],
16501 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
16502 None,
16503 smooth_neighbor_uv,
16504 );
16505 v.reconstruct(
16506 cpx,
16507 cpy,
16508 chroma_side,
16509 uv_predict_mode,
16510 angle_delta_uv,
16511 reach,
16512 &vec![0i32; chroma_side * chroma_side],
16513 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
16514 None,
16515 smooth_neighbor_uv,
16516 );
16517 luma_grid = vec![0i32; side * side];
16518 u_grid = vec![0i32; chroma_side * chroma_side];
16519 v_grid = vec![0i32; chroma_side * chroma_side];
16520 } else {
16521 let around = neighbours.around(at, side);
16522 luma_grid = if split_luma {
16523 // Already coded and reconstructed unit by unit above; the
16524 // block-level grid is only the neighbour write-back's input,
16525 // which `record_split_luma` ignores for plane 0.
16526 vec![0i32; side * side]
16527 } else {
16528 read_plane(
16529 dec,
16530 cdfs,
16531 luma_set_intra,
16532 scan_luma,
16533 0,
16534 around[0],
16535 mode,
16536 mode,
16537 0,
16538 reach,
16539 y,
16540 px,
16541 py,
16542 side,
16543 luma_tx,
16544 base_q_idx,
16545 None,
16546 filter_intra,
16547 None,
16548 false,
16549 )?
16550 };
16551 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
16552 u_grid = read_plane(
16553 dec,
16554 cdfs,
16555 chroma_set,
16556 scan_chroma,
16557 1,
16558 around[1],
16559 mode,
16560 uv_predict_mode,
16561 angle_delta_uv,
16562 reach,
16563 u,
16564 cpx,
16565 cpy,
16566 chroma_side,
16567 chroma_tx,
16568 base_q_idx,
16569 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
16570 None,
16571 None,
16572 smooth_neighbor_uv,
16573 )?;
16574 v_grid = read_plane(
16575 dec,
16576 cdfs,
16577 chroma_set,
16578 scan_chroma,
16579 2,
16580 around[2],
16581 mode,
16582 uv_predict_mode,
16583 angle_delta_uv,
16584 reach,
16585 v,
16586 cpx,
16587 cpy,
16588 chroma_side,
16589 chroma_tx,
16590 base_q_idx,
16591 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
16592 None,
16593 None,
16594 smooth_neighbor_uv,
16595 )?;
16596 }
16597 }
16598 // lane-comppin r9: end-of-block checkpoint -- everything between
16599 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
16600 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
16601 // equivalent post-content point (added at the matching call site)
16602 // narrows the ladder to this block's own tail instead of the next
16603 // block's partition read.
16604 if std::env::var_os("EC_AV1_TELL").is_some() {
16605 eprintln!(
16606 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
16607 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
16608 );
16609 }
16610 if vartx_leaves.is_some() {
16611 // Plane 0 is already correct per transform unit
16612 // ([`Neighbours::record_mi_luma`] above); this writes everything else
16613 // [`Neighbours::record_rect`] would (a var-tx block is always square,
16614 // so `write_w == write_h == side`).
16615 neighbours.record_split_luma(at, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]);
16616 } else {
16617 neighbours.record_rect(
16618 at,
16619 write_w,
16620 write_h,
16621 mode_for_tx,
16622 uv_predict_mode,
16623 &[luma_grid, u_grid, v_grid],
16624 );
16625 }
16626 neighbours.record_inter_rect(
16627 at,
16628 write_w,
16629 write_h,
16630 skip,
16631 is_inter,
16632 ref_frame_for_lf,
16633 block_filter,
16634 skip_mode,
16635 );
16636 if let Some((ref1, group_idx, idx)) = compound_ctx {
16637 neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx);
16638 }
16639 neighbours.fill_skip_grid_rect(
16640 (r * (SUB / MI), c * (SUB / MI)),
16641 write_w / MI,
16642 write_h / MI,
16643 skip,
16644 );
16645 neighbours.fill_lf_grid_rect(
16646 (r * (SUB / MI), c * (SUB / MI)),
16647 write_w / MI,
16648 write_h / MI,
16649 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
16650 // single-scalar corner-cut deblocked the strip seam with the wrong
16651 // edge length (1-px chroma drift on rect-flake-1 f17+).
16652 write_w as u8,
16653 write_h as u8,
16654 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
16655 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
16656 if globalmv_for_lf {
16657 -ref_frame_for_lf
16658 } else {
16659 ref_frame_for_lf
16660 },
16661 );
16662 // lane-txselect: a var-tx block's deblock edges follow its own transform
16663 // units, not the block. Chroma still reads `tx_h_grid / 2` (the block's
16664 // uv transform is not split) -- a known corner-cut of this round.
16665 if let Some(leaves) = &vartx_leaves {
16666 for &(row, col, tx_px) in leaves {
16667 neighbours.fill_lf_grid_rect(
16668 (at_mi.0 + row, at_mi.1 + col),
16669 tx_px / MI,
16670 tx_px / MI,
16671 tx_px as u8,
16672 tx_px as u8,
16673 if globalmv_for_lf {
16674 -ref_frame_for_lf
16675 } else {
16676 ref_frame_for_lf
16677 },
16678 );
16679 }
16680 }
16681 Ok(())
16682}
16683
16684/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
16685/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
16686/// exact symbol order: its own skip flag, intra/inter choice and (when
16687/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
16688/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
16689/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
16690/// same as [`decode_leaf8`]'s coefficient layer but with
16691/// motion-compensated prediction instead of intra prediction when inter.
16692/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
16693/// skip/intra-inter context, overridden by `prev_leaf` exactly as
16694/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
16695/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
16696/// and intra/inter choice, for the next leaf or the caller's final
16697/// write-back.
16698#[allow(clippy::too_many_arguments)]
16699fn decode_inter_block8(
16700 dec: &mut SymbolDecoder,
16701 cdfs: &mut Cdfs,
16702 neighbours: &mut Neighbours,
16703 grid: &mut MiGrid,
16704 mi_cols: u32,
16705 mi_rows: u32,
16706 outer_at: (usize, usize),
16707 leaf_mi: (usize, usize),
16708 y: &mut PlaneBuf,
16709 u: &mut PlaneBuf,
16710 v: &mut PlaneBuf,
16711 ref_y: &PlaneBuf,
16712 ref_u: &PlaneBuf,
16713 ref_v: &PlaneBuf,
16714 other_refs: &RefSlots,
16715 base_q_idx: u8,
16716 scan8: &[u16],
16717 scan4: &[u16],
16718 allow_high_precision_mv: bool,
16719 force_integer_mv: bool,
16720 // lane-gmaffine r1: this frame header's own `global_motion` table (spec
16721 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` -- same table
16722 // [`decode_inter_block`] takes, threaded here so the 8x8 leaf can code
16723 // `GLOBALMV` (`gm_get_motion_vector`), fill its mv stack's missing
16724 // candidates with the gm mv (gm r6's root cause) and build a global
16725 // warp prediction.
16726 global_motion: &[ec_av1_syntax::WarpParams; 7],
16727 // lane-gmaffine r1: this sequence header's own `enable_dual_filter` bit,
16728 // for the leaf's own `read_mb_interp_filter` below.
16729 enable_dual_filter: bool,
16730 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
16731 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
16732 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
16733 // context uses that same approximation.
16734 reference_select: bool,
16735 enable_masked_compound: bool,
16736 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
16737 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
16738 // drops the `side` check entirely.
16739 enable_interintra_compound: bool,
16740 enable_jnt_comp: bool,
16741 order_hint_bits: u32,
16742 order_hint: u32,
16743 ref_order_hints: [u32; 7],
16744 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
16745 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
16746 // so its `skip_mode` context reuses the same [`SUB`]-grid
16747 // `above_skip_mode[cmi]`/`left_skip_mode[rmi]` the enclosing 16x16 slot
16748 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
16749 // just above).
16750 skip_mode_present: bool,
16751 skip_mode_frame: [u8; 2],
16752 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
16753 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
16754 reduced_tx_set: bool,
16755 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
16756 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
16757 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
16758 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
16759 // prediction is always `Regular` (documented corner-cut, `mc::predict`
16760 // has no filter param), but an OBMC neighbour can be a real 16x16+
16761 // block that DID resolve a switchable filter.
16762 interp_fixed: Option<mc::InterpFilterKind>,
16763 switchable_motion_mode: bool,
16764 allow_warped_motion: bool,
16765 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
16766 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
16767 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
16768 // `compound_ctx` local, just handed back instead of applied here (this
16769 // fn's `neighbours` recording happens once for the whole straddling
16770 // 16x16 block, after every leaf).
16771 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
16772 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
16773 // eligible (`bsize >= BLOCK_8X8`).
16774 allow_screen_content_tools: bool,
16775 // lane-inter8 r1: the leaf's mv stacks used to be built without the
16776 // frame's sign-bias table (`NO_SIGN_BIAS`), while [`decode_inter_block`]
16777 // one level up passed it -- it changes the candidate list and with it
16778 // `new_mv_ctx`/`ref_mv_ctx`, `drl_ctx` and the number of symbols read.
16779 // Measured: an 8x8 compound NEAR_NEWMV leaf desynced against aomdec's
16780 // EC_MODE ladder at exactly this block (mi 4,14 of the mandelbrot
16781 // 8x8-split gate).
16782 sign_bias_table: &SignBiasTable,
16783 // lane-inter8 r2: the frame's temporal mv field (spec 7.10.2.8), which
16784 // [`decode_inter_block`] one level up has always passed and this leaf
16785 // passed `None` for -- a `use_ref_frame_mvs` frame's stack then holds
16786 // fewer candidates here than in the reference decoder, which changes the
16787 // mode contexts AND the number of `drl_mode` bits read (class parsed
16788 // then discarded).
16789 tpl_frame: Option<&TplFrameArgs>,
16790 // lane-scaledref r1: this frame's own coded luma width (spec 7.11.3.3),
16791 // for the scaled-reference MC this leaf's own single-ref/compound/OBMC
16792 // predictions take when a stored reference was coded at another width
16793 // (`use_superres`) -- mirrors [`decode_inter_block`]'s own param.
16794 frame_width: usize,
16795) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>, [u8; 2], (i8, Option<i8>))> {
16796 const LAST_FRAME: i8 = 1;
16797 // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back
16798 // so the caller stamps them into `Neighbours` instead of the `[3, 3]`
16799 // placeholder. `[3, 3]` is the "intra neighbour, no filter" sentinel: an
16800 // OBMC blend that picks such a neighbour up feeds it to
16801 // `neighbour_filter`, which PANICS on it (`from_switchable_symbol`) --
16802 // that was the warp gate's crash, not an entropy desync. Stays `[3, 3]`
16803 // on the intra and compound paths.
16804 let mut leaf_filter_syms = [3u8; 2];
16805 // lane-gmaffine r1: this leaf's GLOBALMV vector AND the mv stack's
16806 // missing-candidate fallback both come from the frame's global motion
16807 // evaluated at THIS block's centre (gm r6's root cause).
16808 let gm_table = build_gm_mv_table(
16809 global_motion,
16810 leaf_mi.0,
16811 leaf_mi.1,
16812 2,
16813 2,
16814 allow_high_precision_mv,
16815 force_integer_mv,
16816 );
16817 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
16818 const SIZE_GROUP_8: usize = 1;
16819
16820 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
16821 let (cpx, cpy) = (px / 2, py / 2);
16822 // lane-txselect: whether this leaf's `TxMode::Select` var-tx tree took
16823 // the one split a `BLOCK_8X8` can take (`read_block_tx_size` below) --
16824 // read back by the luma residual read and the tail's neighbour/loop-filter
16825 // bookkeeping. Always `false` outside a `TxMode::Select` inter frame.
16826 let mut split8 = false;
16827 const SIDE: usize = 8;
16828 const CHROMA_SIDE: usize = 4;
16829
16830 let (r, c) = outer_at;
16831 let _ = (r, c);
16832 // lane-inter8 r2: this leaf's OWN mi cell, not the enclosing 16x16's --
16833 // leaf (mi_r, mi_c + 2)'s left neighbour is leaf (mi_r, mi_c), and the
16834 // left column of a 16x16's second leaf ROW is the previous 16x16 block's
16835 // bottom leaf, neither of which a SUB-grid slot can name.
16836 let (rmi, cmi) = leaf_mi;
16837 // lane-inter8 r2: no sibling-leaf override any more -- each leaf stamps
16838 // its own 2x2-mi span into the bands right after it decodes (the caller's
16839 // `record_inter_rect_mi`), so a plain mi read already names the correct
16840 // neighbour, including one belonging to the previous 16x16 block.
16841 let above_skip = neighbours.above_skip[cmi];
16842 let left_skip = neighbours.left_skip[rmi];
16843 let above_inter = neighbours.above_inter[cmi];
16844 let left_inter = neighbours.left_inter[rmi];
16845 let above_ref0 = neighbours.above_ref[cmi];
16846 let above_ref1 = neighbours.above_ref1[cmi];
16847 let left_ref0 = neighbours.left_ref[rmi];
16848 let left_ref1 = neighbours.left_ref1[rmi];
16849 let skip_mode_ctx =
16850 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
16851 // Same two `inter_segment_id` positions as [`decode_inter_block`]; this
16852 // leaf is always `BLOCK_8X8`, i.e. 2x2 mi.
16853 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true);
16854 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
16855 if skip_mode {
16856 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
16857 }
16858
16859 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
16860 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
16861 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false);
16862 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
16863 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
16864 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
16865 maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
16866
16867 let (has_above, has_left) = (
16868 leaf_mi.0 > neighbours.tile_row0_mi,
16869 leaf_mi.1 > neighbours.tile_col0_mi,
16870 );
16871 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
16872 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
16873 // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4,
16874 // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder
16875 // diffs line for line against a real aomdec.
16876 if std::env::var_os("EC_TRACE_MODE").is_some() {
16877 eprintln!(
16878 "EC_MODE mi_row={} mi_col={} rng={}",
16879 leaf_mi.0,
16880 leaf_mi.1,
16881 dec.debug_state().0
16882 );
16883 }
16884
16885 let mode_for_tx;
16886 let (luma_grid, u_grid, v_grid);
16887 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
16888 // lane-inter8 r1: this leaf's own resolved references, handed back so the
16889 // NEXT leaf of the same 16x16 can use them as its real above/left
16890 // neighbour (`Neighbours`' arrays only move once per 16x16 block).
16891 // `(0, None)` is intra.
16892 let mut leaf_refs: (i8, Option<i8>) = (0, None);
16893 if is_inter {
16894 if reference_select || skip_mode {
16895 // lane-inter8 r1: the REAL neighbour references, not a
16896 // `LAST_FRAME`-or-intra stand-in. `av1_get_reference_mode_context`
16897 // and `read_compound_ref_frames`' own contexts both ask whether a
16898 // neighbour is COMPOUND, so pretending every inter neighbour is
16899 // single-ref LAST picked the wrong `comp_mode` CDF row -- measured
16900 // as an 8x8 leaf reading single-ref where aomdec read compound
16901 // NEAR_NEWMV (mi 4,14).
16902 let above_nbr = has_above.then(|| NeighbourRef {
16903 is_inter: above_inter,
16904 ref0: if above_inter { above_ref0 } else { 0 },
16905 ref1: above_ref1,
16906 uni: above_ref1.is_some_and(|r1| is_uni_comp_ref(above_ref0, r1)),
16907 });
16908 let left_nbr = has_left.then(|| NeighbourRef {
16909 is_inter: left_inter,
16910 ref0: if left_inter { left_ref0 } else { 0 },
16911 ref1: left_ref1,
16912 uni: left_ref1.is_some_and(|r1| is_uni_comp_ref(left_ref0, r1)),
16913 });
16914 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
16915 let (ref0, ref1) = if skip_mode {
16916 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
16917 } else {
16918 read_compound_ref_frames(
16919 dec,
16920 cdfs,
16921 above_nbr,
16922 left_nbr,
16923 if has_above && above_inter {
16924 LAST_FRAME
16925 } else {
16926 -1
16927 },
16928 if has_left && left_inter {
16929 LAST_FRAME
16930 } else {
16931 -1
16932 },
16933 )
16934 };
16935 leaf_refs = (ref0, Some(ref1));
16936 let (mi_row, mi_col) = leaf_mi;
16937 // spec 7.10.2.8, mirroring [`decode_inter_block`]'s own
16938 // `comp_tpl` build (`use_ref_frame_mvs` frames only).
16939 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
16940 field: t.field,
16941 cur_offset_0: crate::motion_field::get_relative_dist(
16942 t.order_hint_bits,
16943 t.order_hint,
16944 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
16945 ),
16946 cur_offset_1: crate::motion_field::get_relative_dist(
16947 t.order_hint_bits,
16948 t.order_hint,
16949 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
16950 ),
16951 allow_high_precision_mv,
16952 });
16953 // lane-av1comp: this leaf path has neither a real sign-bias
16954 // table nor `tpl_frame` (see this function's own doc on the
16955 // coarse `LAST_FRAME`-or-intra neighbour approximation
16956 // already in force above), matching the plain `find_mv_stack`
16957 // (no bias, no tpl) the leaf's single-ref arm below already
16958 // uses.
16959 let comp_stack = crate::mvstack::find_mv_stack_compound(
16960 grid,
16961 mi_row,
16962 mi_col,
16963 2,
16964 2,
16965 (ref0, ref1),
16966 mi_cols as usize,
16967 mi_rows as usize,
16968 sign_bias_table,
16969 &gm_table,
16970 comp_tpl,
16971 );
16972 let compound_mode = if skip_mode {
16973 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
16974 } else {
16975 read_inter_compound_mode(
16976 dec,
16977 cdfs,
16978 comp_stack.new_mv_ctx,
16979 comp_stack.ref_mv_ctx,
16980 )
16981 };
16982 if std::env::var_os("EC_TRACE_MODE").is_some() {
16983 eprintln!(
16984 "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}",
16985 leaf_mi.0,
16986 leaf_mi.1,
16987 compound_mode + 17,
16988 comp_stack.entries.len(),
16989 comp_stack.new_mv_ctx,
16990 comp_stack.ref_mv_ctx,
16991 dec.debug_state().0
16992 );
16993 }
16994 let (mv0, mv1) = assign_compound_mv(
16995 dec,
16996 cdfs,
16997 &comp_stack,
16998 compound_mode,
16999 allow_high_precision_mv,
17000 force_integer_mv,
17001 // lane-inter8 r1: the real per-ref gm mvs, same as
17002 // [`decode_inter_block`]'s own compound arm.
17003 (
17004 gm_table[(ref0 - LAST_FRAME) as usize],
17005 gm_table[(ref1 - LAST_FRAME) as usize],
17006 ),
17007 );
17008 // lane-inter8 r3: byte-format-identical to the oracle's
17009 // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder
17010 // diffs line for line against a real aomdec.
17011 if std::env::var_os("EC_TRACE_MODE").is_some() {
17012 eprintln!(
17013 "EC_MODE_VAL mi_row={} mi_col={} mode={} ref0={} ref1={} mv0=({},{}) rng={}",
17014 leaf_mi.0,
17015 leaf_mi.1,
17016 compound_mode + 17,
17017 ref0,
17018 ref1,
17019 mv0.0,
17020 mv0.1,
17021 dec.debug_state().0
17022 );
17023 }
17024
17025 // spec 5.11.25: same gating [`decode_inter_block`]'s own
17026 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
17027 // slot -- the only granularity `Neighbours`' comp_group_idx/
17028 // compound_idx arrays track.
17029 let group_ctx = get_comp_group_idx_context(neighbours, leaf_mi, SIDE);
17030 let comp_group_idx = if !skip_mode
17031 && enable_masked_compound
17032 && is_any_masked_compound_used_here(SIDE)
17033 {
17034 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
17035 } else {
17036 0
17037 };
17038 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
17039 // leaf's own comment.
17040 let mut diffwtd_mask_type: Option<u8> = None;
17041 let mut wedge_mask: Option<&'static [u8]> = None;
17042 if comp_group_idx == 1 {
17043 // lane-maskcomp r1: see the 16x16 leaf's own comment
17044 // above -- SIDE==8 here, `wedge_bsize` index 3
17045 // (BLOCK_8X8, `wedge_types > 0`).
17046 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
17047 if compound_type == 0 {
17048 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
17049 // leaf's own comment.
17050 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
17051 let wedge_sign = dec.literal(1);
17052 WEDGE_HITS.with(|c| c.set(c.get() + 1));
17053 wedge_mask = Some(
17054 crate::wedge::wedge_masks()
17055 .codebook(SIDE)
17056 .mask(wedge_sign as usize, wedge_index as usize),
17057 );
17058 } else {
17059 let mask_type = dec.literal(1);
17060 diffwtd_mask_type = Some(mask_type as u8);
17061 }
17062 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
17063 }
17064 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
17065 // reference-slot defect as the 16x16 leaf's own mask above
17066 // (r1: falsified as an MC/blend math bug, isolated to a DPB
17067 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
17068 // that comment.
17069 // r3: same defect as the 16x16 leaf's own mask above -- see
17070 // that comment (compound_idx's decoded value, not the blend
17071 // math or reference-slot bookkeeping). r6/r7: same re-mask
17072 // as the 16x16 leaf above -- one real bug found and fixed
17073 // (mvstack.rs ref_ctx family), a second, still-unfound
17074 // compound_idx defect surfaces on the wide gate sweep.
17075 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
17076 // see that comment.
17077 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
17078 && !skip_mode
17079 && enable_jnt_comp
17080 {
17081 let idx_ctx = get_comp_index_context(
17082 neighbours,
17083 leaf_mi,
17084 SIDE,
17085 order_hint_bits,
17086 order_hint,
17087 ref_order_hints[(ref0 - LAST_FRAME) as usize],
17088 ref_order_hints[(ref1 - LAST_FRAME) as usize],
17089 );
17090 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
17091 if idx == 1 {
17092 (8, 8, 1u8)
17093 } else {
17094 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
17095 order_hint_bits,
17096 order_hint,
17097 ref_order_hints[(ref0 - LAST_FRAME) as usize],
17098 ref_order_hints[(ref1 - LAST_FRAME) as usize],
17099 );
17100 (fwd, bck, 0u8)
17101 }
17102 } else {
17103 (8, 8, 1u8)
17104 };
17105 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
17106 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
17107 eprintln!(
17108 "EC_COMPIDX mi_row={mi_row} mi_col={mi_col} bsize=8 mode={compound_mode} mv0=({},{}) mv1=({},{}) ref0={ref0} ref1={ref1} comp_group_idx={comp_group_idx} compound_idx={compound_idx} tell={}",
17109 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
17110 );
17111 }
17112
17113 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
17114 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
17115 let scale0 = mc::scale_factor(py0.width, frame_width);
17116 let scale1 = mc::scale_factor(py1.width, frame_width);
17117 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
17118 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
17119 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
17120 }
17121
17122 for dr in 0..2 {
17123 for dc in 0..2 {
17124 grid.set(
17125 mi_row + dr,
17126 mi_col + dc,
17127 MiInfo {
17128 is_inter: true,
17129 ref_frame: ref0,
17130 ref_frame1: Some(ref1),
17131 mv1: Some(mv1),
17132 mv: mv0,
17133 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
17134 size: 2,
17135 size_h: 2,
17136 is_global_mv0: false,
17137 is_global_mv1: false,
17138 },
17139 );
17140 }
17141 }
17142 mode_for_tx = 0;
17143
17144 // lane-av1comp corner-cut, matching this leaf's single-ref
17145 // arm below (`mc::predict`'s own fixed-Regular default):
17146 // `decode_inter_block8` never resolves a switchable filter,
17147 // so both compound taps use `Regular` too.
17148 use mc::InterpFilterKind::Regular;
17149 let mut inter0_y = vec![0i32; SIDE * SIDE];
17150 mc::predict_compound_intermediate(
17151 &py0.data,
17152 py0.width,
17153 py0.true_width,
17154 py0.true_height,
17155 mv_to_q4(px, mv0.1, true),
17156 mv_to_q4(py, mv0.0, true),
17157 scale0,
17158 SIDE,
17159 SIDE,
17160 Regular,
17161 Regular,
17162 &mut inter0_y,
17163 );
17164 let mut inter1_y = vec![0i32; SIDE * SIDE];
17165 mc::predict_compound_intermediate(
17166 &py1.data,
17167 py1.width,
17168 py1.true_width,
17169 py1.true_height,
17170 mv_to_q4(px, mv1.1, true),
17171 mv_to_q4(py, mv1.0, true),
17172 scale1,
17173 SIDE,
17174 SIDE,
17175 Regular,
17176 Regular,
17177 &mut inter1_y,
17178 );
17179 let mut pred_y = vec![0u16; SIDE * SIDE];
17180 let mut diffwtd_mask_y = Vec::new();
17181 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
17182 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
17183 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
17184 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
17185 Some(diffwtd_mask_y.as_slice())
17186 } else {
17187 wedge_mask
17188 };
17189 if let Some(mask_y) = mask_y {
17190 mc::blend_masked_compound(
17191 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
17192 );
17193 } else {
17194 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
17195 }
17196
17197 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17198 mc::predict_compound_intermediate(
17199 &pu0.data,
17200 pu0.width,
17201 pu0.true_width,
17202 pu0.true_height,
17203 mv_to_q4(cpx, mv0.1, false),
17204 mv_to_q4(cpy, mv0.0, false),
17205 scale0,
17206 CHROMA_SIDE,
17207 CHROMA_SIDE,
17208 Regular,
17209 Regular,
17210 &mut inter0_u,
17211 );
17212 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17213 mc::predict_compound_intermediate(
17214 &pu1.data,
17215 pu1.width,
17216 pu1.true_width,
17217 pu1.true_height,
17218 mv_to_q4(cpx, mv1.1, false),
17219 mv_to_q4(cpy, mv1.0, false),
17220 scale1,
17221 CHROMA_SIDE,
17222 CHROMA_SIDE,
17223 Regular,
17224 Regular,
17225 &mut inter1_u,
17226 );
17227 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
17228 if let Some(mask_y) = mask_y {
17229 mc::blend_masked_compound(
17230 &inter0_u,
17231 &inter1_u,
17232 mask_y,
17233 SIDE,
17234 CHROMA_SIDE,
17235 CHROMA_SIDE,
17236 true,
17237 &mut pred_u,
17238 );
17239 } else {
17240 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
17241 }
17242
17243 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17244 mc::predict_compound_intermediate(
17245 &pv0.data,
17246 pv0.width,
17247 pv0.true_width,
17248 pv0.true_height,
17249 mv_to_q4(cpx, mv0.1, false),
17250 mv_to_q4(cpy, mv0.0, false),
17251 scale0,
17252 CHROMA_SIDE,
17253 CHROMA_SIDE,
17254 Regular,
17255 Regular,
17256 &mut inter0_v,
17257 );
17258 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17259 mc::predict_compound_intermediate(
17260 &pv1.data,
17261 pv1.width,
17262 pv1.true_width,
17263 pv1.true_height,
17264 mv_to_q4(cpx, mv1.1, false),
17265 mv_to_q4(cpy, mv1.0, false),
17266 scale1,
17267 CHROMA_SIDE,
17268 CHROMA_SIDE,
17269 Regular,
17270 Regular,
17271 &mut inter1_v,
17272 );
17273 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
17274 if let Some(mask_y) = mask_y {
17275 mc::blend_masked_compound(
17276 &inter0_v,
17277 &inter1_v,
17278 mask_y,
17279 SIDE,
17280 CHROMA_SIDE,
17281 CHROMA_SIDE,
17282 true,
17283 &mut pred_v,
17284 );
17285 } else {
17286 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
17287 }
17288
17289 split8 = read_block_tx_size(
17290 dec,
17291 cdfs,
17292 neighbours,
17293 leaf_mi,
17294 SIDE,
17295 (mi_cols as usize, mi_rows as usize),
17296 true,
17297 skip,
17298 )?
17299 .1
17300 .is_some();
17301 if skip {
17302 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
17303 u.reconstruct_mc(
17304 cpx,
17305 cpy,
17306 CHROMA_SIDE,
17307 &pred_u,
17308 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17309 );
17310 v.reconstruct_mc(
17311 cpx,
17312 cpy,
17313 CHROMA_SIDE,
17314 &pred_v,
17315 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17316 );
17317 luma_grid = vec![0i32; SIDE * SIDE];
17318 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17319 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17320 } else {
17321 let around = neighbours.around_mi(leaf_mi, 8);
17322 let (grid8, luma_tx_type) = read_inter_luma8(
17323 dec,
17324 cdfs,
17325 neighbours,
17326 leaf_mi,
17327 y,
17328 px,
17329 py,
17330 &pred_y,
17331 mode_for_tx,
17332 base_q_idx,
17333 scan8,
17334 scan4,
17335 reduced_tx_set,
17336 split8,
17337 )?;
17338 luma_grid = grid8;
17339 u_grid = read_inter_plane(
17340 dec,
17341 cdfs,
17342 TxbSet::Chroma4,
17343 scan4,
17344 1,
17345 around[1],
17346 mode_for_tx,
17347 u,
17348 cpx,
17349 cpy,
17350 CHROMA_SIDE,
17351 base_q_idx,
17352 &pred_u,
17353 Some(luma_tx_type),
17354 None,
17355 )?
17356 .0;
17357 v_grid = read_inter_plane(
17358 dec,
17359 cdfs,
17360 TxbSet::Chroma4,
17361 scan4,
17362 2,
17363 around[2],
17364 mode_for_tx,
17365 v,
17366 cpx,
17367 cpy,
17368 CHROMA_SIDE,
17369 base_q_idx,
17370 &pred_v,
17371 Some(luma_tx_type),
17372 None,
17373 )?
17374 .0;
17375 }
17376 // lane-inter8 r2: the COMPOUND leaf used to return here
17377 // WITHOUT the end-of-function `record_mi`/`fill_lf_grid` the
17378 // single-ref path falls through to -- so a compound 8x8 leaf
17379 // left `above_side_mi`/`left_side_mi` (the next block's
17380 // partition context), the per-plane coefficient level state
17381 // and the loop-filter grid describing whatever block was
17382 // there before. Every leaf of the gate's stream is compound,
17383 // so the 16x16 below a split block read partition ctx 0
17384 // instead of 1 and mis-read PARTITION_SPLIT as NONE.
17385 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
17386 neighbours.fill_lf_grid(
17387 leaf_mi,
17388 2,
17389 8,
17390 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
17391 );
17392 return Ok((
17393 skip,
17394 is_inter,
17395 skip_mode,
17396 compound_ctx8,
17397 leaf_filter_syms,
17398 leaf_refs,
17399 ));
17400 }
17401 }
17402 // lane-gmaffine r1: the leaf reads the FULL `single_ref` tree
17403 // ([`read_single_ref`], the same one the 16x16+ leaf uses, with the
17404 // real per-neighbour p1..p6 contexts) instead of the old three-symbol
17405 // LAST-only probe plus a refusal -- aomenc picks GOLDEN/ALTREF for
17406 // 8x8 leaves constantly, so that refusal was what every 8x8 gate
17407 // actually stopped at.
17408 let ref_frame = read_single_ref(
17409 dec,
17410 cdfs,
17411 neighbours.above_ref[cmi],
17412 neighbours.above_ref1[cmi],
17413 neighbours.left_ref[rmi],
17414 neighbours.left_ref1[rmi],
17415 );
17416 leaf_refs = (ref_frame, None);
17417 let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
17418
17419 let (mi_row, mi_col) = leaf_mi;
17420 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS
17421 // leaf's own reference (lane-gmaffine r1 taught it non-LAST refs).
17422 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
17423 field: t.field,
17424 cur_offset_0: crate::motion_field::get_relative_dist(
17425 t.order_hint_bits,
17426 t.order_hint,
17427 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
17428 ),
17429 allow_high_precision_mv,
17430 });
17431 let stack = crate::mvstack::find_mv_stack_with_sign_bias(
17432 grid,
17433 mi_row,
17434 mi_col,
17435 2,
17436 2,
17437 ref_frame,
17438 mi_cols as usize,
17439 mi_rows as usize,
17440 sign_bias_table,
17441 &gm_table,
17442 tpl,
17443 );
17444
17445 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
17446 let mut is_globalmv = false;
17447 let (mv, is_new_mv) = if !not_new {
17448 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
17449 // read at most two `drl_mode` bits, one per stack entry past the
17450 // first, stopping at the first `0`. The chosen index selects
17451 // which stack entry `read_mv`'s base predictor comes from
17452 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
17453 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
17454 let mut idx = 0usize;
17455 while idx < 2 && stack.entries.len() > idx + 1 {
17456 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
17457 break;
17458 }
17459 idx += 1;
17460 }
17461 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
17462 (
17463 read_mv(
17464 dec,
17465 &mut cdfs.mv_comp,
17466 &mut cdfs.mv_joint,
17467 base_mv,
17468 allow_high_precision_mv,
17469 force_integer_mv,
17470 ),
17471 true,
17472 )
17473 } else {
17474 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
17475 is_globalmv = !not_zero;
17476 let mv = if !not_zero {
17477 // lane-gmaffine r1: GLOBALMV (spec 7.10.2.1) -- the same
17478 // `gm_get_motion_vector` value the 16x16+ leaf reads out of
17479 // its own `gm_table`, computed at this block's centre.
17480 GLOBALMV_HITS_8.with(|c| c.set(c.get() + 1));
17481 gm_table[(ref_frame - LAST_FRAME) as usize]
17482 } else {
17483 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
17484 if nearest {
17485 stack.nearest_mv
17486 } else {
17487 let mut idx = 1usize;
17488 while idx < 3 && stack.entries.len() > idx + 1 {
17489 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
17490 break;
17491 }
17492 idx += 1;
17493 }
17494 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
17495 }
17496 };
17497 (mv, false)
17498 };
17499 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
17500 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
17501 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
17502 // (compound already returned above), GLOBALMV already refused
17503 // (round 3), so the only real gate left is the header enable bit.
17504 let mut interintra_mode: Option<u8> = None;
17505 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
17506 if enable_interintra_compound && !skip_mode {
17507 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
17508 if interintra {
17509 // lane-interintra r1: same read pair as the 16/32 site;
17510 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
17511 // alone, never the `enable_interintra_wedge` seq bit.
17512 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
17513 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
17514 if wedge {
17515 // lane-wii r2: same adapting `wedge_index` symbol as the
17516 // 16/32 leaf, fixed sign 0 -- see that site's comment.
17517 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
17518 WII_HITS.with(|c| c.set(c.get() + 1));
17519 wedge_mask = Some((
17520 crate::wedge::wedge_masks()
17521 .codebook(SIDE)
17522 .mask(0, wedge_index as usize),
17523 SIDE,
17524 ));
17525 } else {
17526 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
17527 }
17528 interintra_mode = Some(ii);
17529 }
17530 }
17531 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
17532 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
17533 // is the spec's own minimum eligible size, single-ref-only branch,
17534 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
17535 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
17536 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
17537 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
17538 // lane-gmaffine r1: the two libaom predicates, exactly as the
17539 // 16x16+ leaf resolves them (see [`decode_inter_block`]'s own doc):
17540 // `is_global_mv_block` (mode GLOBAL*, model > TRANSLATION, block
17541 // >= 8x8 -- BLOCK_8X8 IS the 8px minimum, so the size predicate is
17542 // always true here) suppresses the motion_mode read entirely and
17543 // turns on the global warp below.
17544 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
17545 let is_global_mv_block = is_globalmv && gm_ref.model as u8 > 1;
17546 let motion_mode_eligible = switchable_motion_mode
17547 && !skip_mode
17548 && interintra_mode.is_none()
17549 && !(is_global_mv_block && !force_integer_mv)
17550 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
17551 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
17552 let mut warp_params: Option<crate::warp::WarpParams> = None;
17553 let mut warped_selected = false;
17554 let mut obmc_selected = false;
17555 if motion_mode_eligible {
17556 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
17557 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
17558 // (grid.set below hardcodes it).
17559 // lane-scaledref r2 sibling of the 16x16+ leaf's fix: libaom
17560 // drops WARPED_CAUSAL eligibility (so this reads `obmc_cdf`)
17561 // when the reference is scaled. Not gated here because an 8x8
17562 // leaf under a scaled reference is refused before this function
17563 // runs (see the block8 refusal below, ~12500) -- whoever lifts
17564 // that refusal must add `&& !ref_is_scaled` here too.
17565 // lane-fimv r1: libaom `motion_mode_allowed` also requires
17566 // `!xd->cur_frame_force_integer_mv`, so a screen-content frame
17567 // that set `force_integer_mv` reads the 2-symbol `obmc_cdf` here
17568 // (class wrong-alphabet-same-value).
17569 let proj_ok =
17570 num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
17571 let warp_eligible = allow_warped_motion && !force_integer_mv && proj_ok;
17572 if allow_warped_motion && proj_ok && force_integer_mv {
17573 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
17574 }
17575 if warp_eligible {
17576 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
17577 match mode {
17578 0 => {}
17579 1 => {
17580 obmc_selected = true;
17581 OBMC_HITS.with(|c| c.set(c.get() + 1));
17582 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
17583 }
17584 _ => {
17585 // lane-gmaffine r1: WARPED_CAUSAL at the 8x8 leaf --
17586 // the same findSamples -> select_samples ->
17587 // av1_find_projection chain the 16x16+ leaf runs,
17588 // with BLOCK_8X8's own 8x8 model centre; an
17589 // unusable projection falls back to the block's
17590 // translational mv (libaom `av1_find_projection`
17591 // returning 1 leaves `wm_params` invalid and
17592 // `build_inter_predictors` skips the warp).
17593 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
17594 let mut samples = find_samples(
17595 grid,
17596 mi_row,
17597 mi_col,
17598 2,
17599 2,
17600 mi_cols as usize,
17601 mi_rows as usize,
17602 ref_frame,
17603 );
17604 if samples.len() > 1 {
17605 crate::warp::select_samples(mv, &mut samples, SIDE as i32, SIDE as i32);
17606 }
17607 warp_params = crate::warp::find_projection(
17608 &samples,
17609 SIDE as i32,
17610 SIDE as i32,
17611 mv.1,
17612 mv.0,
17613 mi_row as i32,
17614 mi_col as i32,
17615 );
17616 warped_selected = true;
17617 if warp_params.is_some() {
17618 WARP_HITS_8.with(|c| c.set(c.get() + 1));
17619 }
17620 }
17621 }
17622 } else {
17623 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
17624 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
17625 if obmc_selected {
17626 OBMC_HITS.with(|c| c.set(c.get() + 1));
17627 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
17628 }
17629 }
17630 }
17631 // lane-gmaffine r1: `read_mb_interp_filter` (spec 5.11.26) at the 8x8
17632 // leaf, in libaom's own order (interintra, motion_mode, THEN the
17633 // filter). Until this round the leaf read no filter symbol at all and
17634 // predicted Regular unconditionally -- correct only for a frame with a
17635 // fixed `interp_filter`, and a silent entropy DESYNC for every
17636 // SWITCHABLE-filter stream that reaches an 8x8 leaf (which is what
17637 // made the interior-split wiring above unusable at first).
17638 // corner-cut: the neighbour filter context is the enclosing 16x16
17639 // block's own coarse `above_filter`/`left_filter` entry (this leaf
17640 // path keeps no per-leaf neighbour array), so all four siblings read
17641 // the same context row. Ceiling: a stream whose 8x8 siblings pick
17642 // DIFFERENT filters decodes the second..fourth leaf's symbol from the
17643 // wrong CDF row. Upgrade: give `Neighbours` a real 8x8-granular
17644 // filter array, same shape as the `[3, 3]` approximation the caller
17645 // records after the leaf loop.
17646 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
17647 || neighbours.above_ref1[cmi] == Some(ref_frame)
17648 {
17649 neighbours.above_filter[cmi]
17650 } else {
17651 [3, 3]
17652 };
17653 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
17654 || neighbours.left_ref1[rmi] == Some(ref_frame)
17655 {
17656 neighbours.left_filter[rmi]
17657 } else {
17658 [3, 3]
17659 };
17660 let gm_nontrans =
17661 is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation;
17662 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
17663 dec,
17664 cdfs,
17665 interp_fixed,
17666 enable_dual_filter,
17667 gm_nontrans || warped_selected || skip_mode,
17668 above_filter_ctx,
17669 left_filter_ctx,
17670 false,
17671 );
17672 leaf_filter_syms = resolved_filter;
17673 if std::env::var_os("EC_TRACE_MODE").is_some() {
17674 eprintln!(
17675 "EC_MODE_VAL8 mi_row={} mi_col={} newmv={is_new_mv} globalmv={is_globalmv} ref0={ref_frame} mv0=({},{}) stack={} rng={}",
17676 leaf_mi.0,
17677 leaf_mi.1,
17678 mv.0,
17679 mv.1,
17680 stack.entries.len(),
17681 dec.debug_state().0
17682 );
17683 }
17684 // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch
17685 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
17686 // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model
17687 // wins (`is_none()` guard); BLOCK_8X8 already satisfies the >=8px
17688 // size predicate baked into `is_global_mv_block`.
17689 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
17690 warp_params = crate::warp::global_warp_params(gm_ref.params);
17691 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
17692 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
17693 }
17694 }
17695 if std::env::var_os("EC_TRACE_MODE").is_some() {
17696 eprintln!(
17697 "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}",
17698 leaf_mi.0,
17699 leaf_mi.1,
17700 warp_params.is_some(),
17701 );
17702 }
17703 for dr in 0..2 {
17704 for dc in 0..2 {
17705 grid.set(
17706 mi_row + dr,
17707 mi_col + dc,
17708 MiInfo {
17709 is_inter: true,
17710 ref_frame,
17711 // INTRA_FRAME marker for interintra blocks -- keeps
17712 // them out of warp-sample gathering (see 16/32 site).
17713 ref_frame1: interintra_mode.map(|_| 0),
17714 mv1: None,
17715 mv,
17716 is_new_mv,
17717 size: 2,
17718 size_h: 2,
17719 is_global_mv0: is_global_mv_block,
17720 is_global_mv1: false,
17721 },
17722 );
17723 }
17724 }
17725 mode_for_tx = 0;
17726
17727 // lane-scaledref r1: this leaf's own prediction is always `Regular`
17728 // (documented corner-cut above); under a scaled reference the same
17729 // fixed kernel runs through spec 7.11.3.3's scaled walk instead.
17730 let luma_scale = mc::scale_factor(sref_y.width, frame_width);
17731 if luma_scale != mc::REF_NO_SCALE {
17732 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
17733 }
17734 let mut pred_y = vec![0u16; SIDE * SIDE];
17735 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
17736 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
17737 // Merge of lane-gmaffine (this leaf's own switchable filters) with
17738 // lane-scaledref (spec 7.11.3.3's scaled walk): same kernels either
17739 // way, only the sample walk differs.
17740 for (plane, x, y, dim, dst) in [
17741 (sref_y, px, py, SIDE, &mut pred_y),
17742 (sref_u, cpx, cpy, CHROMA_SIDE, &mut pred_u),
17743 (sref_v, cpx, cpy, CHROMA_SIDE, &mut pred_v),
17744 ] {
17745 let luma = std::ptr::eq(plane, sref_y);
17746 if luma_scale == mc::REF_NO_SCALE {
17747 mc::predict_with_filters(
17748 &plane.data,
17749 plane.width,
17750 plane.true_width,
17751 plane.true_height,
17752 mv_to_q4(x, mv.1, luma),
17753 mv_to_q4(y, mv.0, luma),
17754 dim,
17755 dim,
17756 h_filter,
17757 v_filter,
17758 dst,
17759 );
17760 } else {
17761 mc::predict_scaled(
17762 &plane.data,
17763 plane.width,
17764 plane.true_width,
17765 plane.true_height,
17766 mv_to_q4(x, mv.1, luma),
17767 mv_to_q4(y, mv.0, luma),
17768 luma_scale,
17769 dim,
17770 dim,
17771 h_filter,
17772 v_filter,
17773 dst,
17774 );
17775 }
17776 }
17777
17778 // lane-gmaffine r1: the warp filter REPLACES the translational
17779 // prediction just built (libaom builds one or the other), same as
17780 // the 16x16+ leaf's own call trio.
17781 if let Some(params) = &warp_params {
17782 crate::warp::warp_affine(
17783 params, &sref_y.data, sref_y.true_width as i32, sref_y.true_height as i32,
17784 sref_y.width as i32, &mut pred_y, px as i32, py as i32, SIDE as i32,
17785 SIDE as i32, SIDE as i32, 0, 0,
17786 );
17787 // `av1_init_warp_params`'s per-plane `block_width/height < 8`
17788 // bail-out: an 8x8 leaf's chroma plane is 4x4 in 420, so it is
17789 // predicted translationally even when the luma warps.
17790 #[allow(clippy::absurd_extreme_comparisons)]
17791 if CHROMA_SIDE >= 8 {
17792 crate::warp::warp_affine(
17793 params, &sref_u.data, sref_u.true_width as i32, sref_u.true_height as i32,
17794 sref_u.width as i32, &mut pred_u, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
17795 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
17796 );
17797 crate::warp::warp_affine(
17798 params, &sref_v.data, sref_v.true_width as i32, sref_v.true_height as i32,
17799 sref_v.width as i32, &mut pred_v, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
17800 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
17801 );
17802 }
17803 }
17804
17805 if obmc_selected {
17806 obmc_blend(
17807 grid,
17808 neighbours,
17809 mi_row,
17810 mi_col,
17811 2,
17812 2,
17813 mi_rows as usize,
17814 mi_cols as usize,
17815 SIDE,
17816 SIDE,
17817 SIDE,
17818 CHROMA_SIDE,
17819 px,
17820 py,
17821 cpx,
17822 cpy,
17823 ref_y,
17824 ref_u,
17825 ref_v,
17826 other_refs,
17827 interp_fixed,
17828 frame_width,
17829 &mut pred_y,
17830 &mut pred_u,
17831 &mut pred_v,
17832 )?;
17833 }
17834
17835 // Non-wedge interintra blend, mutually exclusive with OBMC (the
17836 // motion_mode symbol is not read for an interintra block).
17837 if let Some(ii) = interintra_mode {
17838 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
17839 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
17840 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
17841 }
17842
17843 split8 = read_block_tx_size(
17844 dec,
17845 cdfs,
17846 neighbours,
17847 leaf_mi,
17848 SIDE,
17849 (mi_cols as usize, mi_rows as usize),
17850 true,
17851 skip,
17852 )?
17853 .1
17854 .is_some();
17855 if skip {
17856 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
17857 u.reconstruct_mc(
17858 cpx,
17859 cpy,
17860 CHROMA_SIDE,
17861 &pred_u,
17862 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17863 );
17864 v.reconstruct_mc(
17865 cpx,
17866 cpy,
17867 CHROMA_SIDE,
17868 &pred_v,
17869 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17870 );
17871 luma_grid = vec![0i32; SIDE * SIDE];
17872 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17873 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17874 } else {
17875 let around = neighbours.around_mi(leaf_mi, 8);
17876 let (grid8, luma_tx_type) = read_inter_luma8(
17877 dec,
17878 cdfs,
17879 neighbours,
17880 leaf_mi,
17881 y,
17882 px,
17883 py,
17884 &pred_y,
17885 mode_for_tx,
17886 base_q_idx,
17887 scan8,
17888 scan4,
17889 reduced_tx_set,
17890 split8,
17891 )?;
17892 luma_grid = grid8;
17893 u_grid = read_inter_plane(
17894 dec,
17895 cdfs,
17896 TxbSet::Chroma4,
17897 scan4,
17898 1,
17899 around[1],
17900 mode_for_tx,
17901 u,
17902 cpx,
17903 cpy,
17904 CHROMA_SIDE,
17905 base_q_idx,
17906 &pred_u,
17907 Some(luma_tx_type),
17908 None,
17909 )?
17910 .0;
17911 v_grid = read_inter_plane(
17912 dec,
17913 cdfs,
17914 TxbSet::Chroma4,
17915 scan4,
17916 2,
17917 around[2],
17918 mode_for_tx,
17919 v,
17920 cpx,
17921 cpy,
17922 CHROMA_SIDE,
17923 base_q_idx,
17924 &pred_v,
17925 Some(luma_tx_type),
17926 None,
17927 )?
17928 .0;
17929 }
17930 } else {
17931 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
17932 if mode >= 13 {
17933 return Err(unsupported(
17934 "an intra mode this decoder does not code (round 2)",
17935 ));
17936 }
17937 if (V_PRED..=D67_PRED).contains(&mode) {
17938 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
17939 if angle != ANGLE_DELTA_ZERO {
17940 return Err(unsupported(
17941 "a nonzero angle delta (this encoder never writes one)",
17942 ));
17943 }
17944 }
17945 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
17946 if uv_mode != DC_PRED {
17947 return Err(unsupported(
17948 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
17949 ));
17950 }
17951 // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/
17952 // `uv_mode` are both effectively `DC_PRED`-gated already on this
17953 // leaf (a nonzero `mode` still passes, but `uv_mode` is forced
17954 // `DC_PRED` by the refusal just above), same order as libaom's
17955 // `read_palette_mode_info` call right after `xd->cfl.store_y`.
17956 if allow_screen_content_tools {
17957 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[0][0]) != 0 {
17958 return Err(unsupported(
17959 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
17960 ));
17961 }
17962 if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
17963 return Err(unsupported(
17964 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
17965 ));
17966 }
17967 }
17968 // lane-fiinter r1: `read_filter_intra_mode_info` (libaom `decodemv.c`,
17969 // the tail of `read_intra_block_mode_info`) -- an intra block inside
17970 // an INTER frame reads `use_filter_intra` in exactly the same place a
17971 // key-frame block does, right after the palette syntax. Nothing read
17972 // it here before this round, and aomenc enables filter intra by
17973 // default, so every inter frame carrying one desynced at this symbol.
17974 // `av1_filter_intra_allowed`'s `palette_size[0] == 0` term is implied:
17975 // a real palette-Y block already returned above.
17976 let mut filter_intra = None;
17977 if mode == DC_PRED
17978 && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
17979 && let Some(class) = filter_intra_size_class(SIDE)
17980 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
17981 {
17982 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
17983 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
17984 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
17985 }
17986 mode_for_tx = mode;
17987 let (mi_row, mi_col) = leaf_mi;
17988 for dr in 0..2 {
17989 for dc in 0..2 {
17990 grid.set(
17991 mi_row + dr,
17992 mi_col + dc,
17993 MiInfo {
17994 is_inter: false,
17995 ref_frame: -1,
17996 ref_frame1: None,
17997 mv1: None,
17998 mv: (0, 0),
17999 is_new_mv: false,
18000 size: 2,
18001 size_h: 2,
18002 is_global_mv0: false,
18003 is_global_mv1: false,
18004 },
18005 );
18006 }
18007 }
18008
18009 // lane-intrainter r1: the 8x8 leaf's own intra `tx_depth` can only
18010 // resolve to TX_4X4, whose 2x2 unit grid this leaf path has no
18011 // prediction loop for (the >=16x16 square path above does). Refuse by
18012 // name rather than mis-reconstruct.
18013 if read_block_tx_size(
18014 dec,
18015 cdfs,
18016 neighbours,
18017 leaf_mi,
18018 SIDE,
18019 (mi_cols as usize, mi_rows as usize),
18020 false,
18021 skip,
18022 )?
18023 .1
18024 .is_some()
18025 {
18026 return Err(unsupported(
18027 "an 8x8 intra leaf in an inter frame whose tx_depth splits it into 4x4 \
18028 transform units",
18029 ));
18030 }
18031 let reach = Reach::of(SIDE, px, py, y.width, y.height);
18032 if skip {
18033 y.reconstruct(
18034 px,
18035 py,
18036 SIDE,
18037 mode,
18038 0,
18039 reach,
18040 &vec![0i32; SIDE * SIDE],
18041 None,
18042 filter_intra,
18043 false,
18044 );
18045 u.reconstruct(
18046 cpx,
18047 cpy,
18048 CHROMA_SIDE,
18049 DC_PRED,
18050 0,
18051 reach,
18052 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
18053 None,
18054 None,
18055 false,
18056 );
18057 v.reconstruct(
18058 cpx,
18059 cpy,
18060 CHROMA_SIDE,
18061 DC_PRED,
18062 0,
18063 reach,
18064 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
18065 None,
18066 None,
18067 false,
18068 );
18069 luma_grid = vec![0i32; SIDE * SIDE];
18070 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
18071 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
18072 } else {
18073 let around = neighbours.around_mi(leaf_mi, 8);
18074 luma_grid = read_plane(
18075 dec,
18076 cdfs,
18077 TxbSet::Luma8,
18078 scan8,
18079 0,
18080 around[0],
18081 mode,
18082 mode,
18083 0,
18084 reach,
18085 y,
18086 px,
18087 py,
18088 SIDE,
18089 TX8,
18090 base_q_idx,
18091 None,
18092 filter_intra,
18093 None,
18094 false,
18095 )?;
18096 u_grid = read_plane(
18097 dec,
18098 cdfs,
18099 TxbSet::Chroma4,
18100 scan4,
18101 1,
18102 around[1],
18103 mode,
18104 DC_PRED,
18105 0,
18106 reach,
18107 u,
18108 cpx,
18109 cpy,
18110 CHROMA_SIDE,
18111 TX4,
18112 base_q_idx,
18113 None,
18114 None,
18115 None,
18116 false,
18117 )?;
18118 v_grid = read_plane(
18119 dec,
18120 cdfs,
18121 TxbSet::Chroma4,
18122 scan4,
18123 2,
18124 around[2],
18125 mode,
18126 DC_PRED,
18127 0,
18128 reach,
18129 v,
18130 cpx,
18131 cpy,
18132 CHROMA_SIDE,
18133 TX4,
18134 base_q_idx,
18135 None,
18136 None,
18137 None,
18138 false,
18139 )?;
18140 }
18141 }
18142 // lane-txselect: a split leaf's plane-0 neighbour context is per 4x4
18143 // transform unit (written by `record_mi_luma` inside `read_inter_luma8`),
18144 // but `record_mi` rewrites all three planes of these cells at once -- so
18145 // save plane 0 across it, exactly as `record_split_luma` leaves plane 0
18146 // alone at the bigger block sizes.
18147 let saved_luma_ctx = split8.then(|| {
18148 (
18149 [
18150 neighbours.left[leaf_mi.0][0],
18151 neighbours.left[leaf_mi.0 + 1][0],
18152 ],
18153 [
18154 neighbours.above[leaf_mi.1][0],
18155 neighbours.above[leaf_mi.1 + 1][0],
18156 ],
18157 )
18158 });
18159 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
18160 if let Some((left, above)) = saved_luma_ctx {
18161 for (cell, state) in left.into_iter().enumerate() {
18162 neighbours.left[leaf_mi.0 + cell][0] = state;
18163 }
18164 for (cell, state) in above.into_iter().enumerate() {
18165 neighbours.above[leaf_mi.1 + cell][0] = state;
18166 }
18167 }
18168 // lane-gmaffine r2: the deblock grid's ref id is the leaf's OWN reference
18169 // (r1 taught this leaf non-LAST refs; the hardcoded LAST_FRAME made every
18170 // GOLDEN/ALTREF leaf read as LAST at the loop-filter's ref/mv edge test).
18171 neighbours.fill_lf_grid(
18172 leaf_mi,
18173 2,
18174 if split8 { 4 } else { 8 },
18175 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
18176 );
18177 Ok((
18178 skip,
18179 is_inter,
18180 skip_mode,
18181 compound_ctx8,
18182 leaf_filter_syms,
18183 leaf_refs,
18184 ))
18185}
18186
18187/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
18188/// against `reference` (the previous frame's own decoded picture, at this
18189/// frame's true size -- a decoder's single-slot DPB, matching what this
18190/// crate's encoder always predicts from), returning the picture it
18191/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
18192/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
18193/// `frame_width`/`frame_height` its true render size).
18194///
18195/// # Errors
18196/// Returns an error under the same conditions [`decode_inter_block`] does,
18197/// or when `reference` is not this frame's own true size, or when the tile
18198/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
18199/// refusal [`crate::tile`]'s writer gives its encoder).
18200pub fn decode_inter_frame_tile(
18201 data: &[u8],
18202 mi_cols: u32,
18203 mi_rows: u32,
18204 base_q_idx: u8,
18205 frame_width: u32,
18206 frame_height: u32,
18207 reference: &Picture,
18208 other_refs: [Option<&Picture>; 8],
18209 cdef: &CdefParams,
18210 loop_filter: &LoopFilterParams,
18211 allow_high_precision_mv: bool,
18212 force_integer_mv: bool,
18213 interp_fixed: Option<mc::InterpFilterKind>,
18214 enable_dual_filter: bool,
18215 reference_select: bool,
18216) -> Result<Picture> {
18217 let single_tile = TileInfo {
18218 mi_col_starts: vec![0, mi_cols],
18219 mi_row_starts: vec![0, mi_rows],
18220 ..TileInfo::default()
18221 };
18222 decode_inter_frame_tile_with_cdfs(
18223 &[data],
18224 &single_tile,
18225 mi_cols,
18226 mi_rows,
18227 base_q_idx,
18228 crate::quant::QuantDeltas::default(),
18229 frame_width,
18230 frame_height,
18231 reference,
18232 other_refs,
18233 cdef,
18234 loop_filter,
18235 &LoopRestorationParams::default(),
18236 None,
18237 allow_high_precision_mv,
18238 force_integer_mv,
18239 NO_SIGN_BIAS,
18240 [ec_av1_syntax::WarpParams::default(); 7],
18241 interp_fixed,
18242 enable_dual_filter,
18243 0,
18244 0,
18245 [0; 7],
18246 None,
18247 reference_select,
18248 false,
18249 false,
18250 false,
18251 false,
18252 [0; 2],
18253 true,
18254 // `tx_select`: this raw entry point decodes this crate's own encoder's
18255 // streams, which always write `TxMode::Largest`.
18256 false,
18257 false,
18258 false,
18259 false,
18260 DeltaParams::default(),
18261 // `enable_filter_intra`: this crate's own encoder never writes the
18262 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream
18263 // reaching this entry point reads a `use_filter_intra` symbol.
18264 false,
18265 )
18266 .map(|(picture, _, _)| picture)
18267}
18268
18269/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
18270/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
18271/// end-of-tile table. An inter frame's own header can name
18272/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
18273/// so `None` is a real case here, not only a convenience default.
18274pub(crate) fn decode_inter_frame_tile_with_cdfs(
18275 tiles: &[&[u8]],
18276 tile_info: &TileInfo,
18277 mi_cols: u32,
18278 mi_rows: u32,
18279 base_q_idx: u8,
18280 // lane-sbpart r11: see [`decode_key_frame_tile_with_cdfs`]'s own `deltas`.
18281 deltas: crate::quant::QuantDeltas,
18282 frame_width: u32,
18283 frame_height: u32,
18284 reference: &Picture,
18285 other_refs: [Option<&Picture>; 8],
18286 cdef: &CdefParams,
18287 loop_filter: &LoopFilterParams,
18288 lr: &LoopRestorationParams,
18289 initial_cdfs: Option<Cdfs>,
18290 allow_high_precision_mv: bool,
18291 force_integer_mv: bool,
18292 sign_bias_table: SignBiasTable,
18293 // lane-gm r2: this frame header's own `global_motion` table (spec
18294 // 5.9.24), threaded to every `decode_inter_block` call below.
18295 global_motion: [ec_av1_syntax::WarpParams; 7],
18296 interp_fixed: Option<mc::InterpFilterKind>,
18297 enable_dual_filter: bool,
18298 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
18299 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
18300 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
18301 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
18302 // and the caller ([`crate::stream::decode_stream`]) projected one.
18303 order_hint_bits: u32,
18304 order_hint: u32,
18305 ref_order_hints: [u32; 7],
18306 tpl_field: Option<&crate::motion_field::TplField>,
18307 // lane-av1comp: this frame header's own `reference_select` bit, threaded
18308 // to every `decode_inter_block`/`decode_inter_block8` call below.
18309 reference_select: bool,
18310 // lane-av1comp: `seq_params`' own compound-blend enable bits.
18311 enable_masked_compound: bool,
18312 enable_jnt_comp: bool,
18313 // lane-sb128 r3: this sequence header's own `enable_interintra_compound`
18314 // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call
18315 // below (spec 5.11.24's `interintra` read).
18316 enable_interintra_compound: bool,
18317 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
18318 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
18319 // `decode_inter_block8` call below.
18320 skip_mode_present: bool,
18321 skip_mode_frame: [u8; 2],
18322 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to
18323 // every inter `tx_type` read below (`false` needs the 12-/16-symbol
18324 // `Set1` coefficient tables at 16x16/8x8 rather than the reduced
18325 // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]).
18326 reduced_tx_set: bool,
18327 // lane-txselect: this frame header's own `tx_mode == TxMode::Select`
18328 // bit (spec 5.9.14). Together with `reduced_tx_set` it is stashed in a
18329 // thread-local by [`set_inter_tx_mode`] rather than threaded through
18330 // `decode_inter_block`'s forty parameters -- both are frame-constant, and
18331 // only [`read_block_tx_size`]/the var-tx residual loop read them.
18332 tx_select: bool,
18333 // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/
18334 // `allow_warped_motion` bits, threaded to every `decode_inter_block`/
18335 // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`).
18336 switchable_motion_mode: bool,
18337 allow_warped_motion: bool,
18338 // lane-screen r2: this frame header's own `allow_screen_content_tools`
18339 // bit, threaded to every `decode_inter_block`/`decode_inter_block8`
18340 // call below -- consumes (never reconstructs) the intra-sub-block
18341 // palette syntax libaom's `read_intra_block_mode_info` reads under the
18342 // same `av1_allow_palette` gate as the key-frame path.
18343 allow_screen_content_tools: bool,
18344 // lane-realworld r5: this frame header's own `delta` (spec 5.9.17/5.9.18),
18345 // same contract as [`decode_key_frame_tile_with_cdfs`]'s own `delta`
18346 // param -- only `q_present`/`q_res` are read.
18347 delta: DeltaParams,
18348 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit
18349 // (spec 5.5.2), stashed in a thread-local with `tx_select` rather than
18350 // threaded through `decode_inter_block`'s fifty parameters -- read by the
18351 // intra-in-inter arms' `read_filter_intra_mode_info`.
18352 enable_filter_intra: bool,
18353) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
18354 set_inter_tx_mode(tx_select, reduced_tx_set, enable_filter_intra);
18355 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
18356 field,
18357 order_hint_bits,
18358 order_hint,
18359 ref_order_hints,
18360 });
18361 if mi_cols == 0 || mi_rows == 0 {
18362 return Err(unsupported("a frame with no mode-info grid"));
18363 }
18364 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
18365 // lane-superres r10: a width mismatch alone is no longer refused here --
18366 // `mc::predict_scaled` (spec 7.11.3.3, threaded through
18367 // `decode_inter_block`'s single-ref branch) exists precisely for a
18368 // `use_superres` reference at a different width than this frame's own
18369 // true size. Height must still match: AV1 superres never scales height
18370 // (r8's derivation, `mc.rs`'s own doc), and nothing in this decode path
18371 // has a vertical scaling pass.
18372 if reference.height != true_height {
18373 return Err(unsupported(
18374 "a reference picture whose height does not match this frame's own true size",
18375 ));
18376 }
18377 let (cols, rows) = block_grid(mi_cols, mi_rows);
18378 let sb128 = sb128();
18379 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
18380 CDEF_BITS.with(|c| c.set(cdef.bits));
18381 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
18382 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
18383 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
18384
18385 let ref_y = PlaneBuf {
18386 data: reference.y.iter().map(|&s| s as u16).collect(),
18387 width: reference.width,
18388 height: reference.height,
18389 true_width: reference.width,
18390 true_height: reference.height,
18391 tile_x0: 0,
18392 tile_y0: 0,
18393 tile_x1: reference.width,
18394 tile_y1: reference.height,
18395 };
18396 let ref_u = PlaneBuf {
18397 data: reference.u.iter().map(|&s| s as u16).collect(),
18398 width: reference.width / 2,
18399 height: reference.height / 2,
18400 true_width: reference.width / 2,
18401 true_height: reference.height / 2,
18402 tile_x0: 0,
18403 tile_y0: 0,
18404 tile_x1: reference.width / 2,
18405 tile_y1: reference.height / 2,
18406 };
18407 let ref_v = PlaneBuf {
18408 data: reference.v.iter().map(|&s| s as u16).collect(),
18409 width: reference.width / 2,
18410 height: reference.height / 2,
18411 true_width: reference.width / 2,
18412 true_height: reference.height / 2,
18413 tile_x0: 0,
18414 tile_y0: 0,
18415 tile_x1: reference.width / 2,
18416 tile_y1: reference.height / 2,
18417 };
18418 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
18419 // names a live DPB slot for (lane-av1refs: generalised from the old
18420 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
18421 // now per-reference). `decode_inter_block` refuses by name when the
18422 // block it is decoding selects an index that is still `None` here
18423 // (spec 7.9 requires every *active* reference be a compatible size;
18424 // an inactive one this frame never selects is simply left `None`).
18425 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
18426 other_refs[i]
18427 .filter(|g| g.width == reference.width && g.height == reference.height)
18428 .map(|g| {
18429 (
18430 PlaneBuf {
18431 data: g.y.iter().map(|&s| s as u16).collect(),
18432 width: g.width,
18433 height: g.height,
18434 true_width: g.width,
18435 true_height: g.height,
18436 tile_x0: 0,
18437 tile_y0: 0,
18438 tile_x1: g.width,
18439 tile_y1: g.height,
18440 },
18441 PlaneBuf {
18442 data: g.u.iter().map(|&s| s as u16).collect(),
18443 width: g.width / 2,
18444 height: g.height / 2,
18445 true_width: g.width / 2,
18446 true_height: g.height / 2,
18447 tile_x0: 0,
18448 tile_y0: 0,
18449 tile_x1: g.width / 2,
18450 tile_y1: g.height / 2,
18451 },
18452 PlaneBuf {
18453 data: g.v.iter().map(|&s| s as u16).collect(),
18454 width: g.width / 2,
18455 height: g.height / 2,
18456 true_width: g.width / 2,
18457 true_height: g.height / 2,
18458 tile_x0: 0,
18459 tile_y0: 0,
18460 tile_x1: g.width / 2,
18461 tile_y1: g.height / 2,
18462 },
18463 )
18464 })
18465 });
18466 let ref_slots: RefSlots =
18467 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
18468
18469 let mut y = PlaneBuf {
18470 data: vec![0u16; width * height],
18471 width,
18472 height,
18473 true_width,
18474 true_height,
18475 tile_x0: 0,
18476 tile_y0: 0,
18477 tile_x1: width,
18478 tile_y1: height,
18479 };
18480 let mut u = PlaneBuf {
18481 data: vec![0u16; width * height / 4],
18482 width: width / 2,
18483 height: height / 2,
18484 true_width: true_width / 2,
18485 true_height: true_height / 2,
18486 tile_x0: 0,
18487 tile_y0: 0,
18488 tile_x1: width / 2,
18489 tile_y1: height / 2,
18490 };
18491 let mut v = PlaneBuf {
18492 data: vec![0u16; width * height / 4],
18493 width: width / 2,
18494 height: height / 2,
18495 true_width: true_width / 2,
18496 true_height: true_height / 2,
18497 tile_x0: 0,
18498 tile_y0: 0,
18499 tile_x1: width / 2,
18500 tile_y1: height / 2,
18501 };
18502
18503 let scan32 = default_scan(TX32);
18504 let scan16 = default_scan(TX16);
18505 let scan8 = default_scan(TX8);
18506 let scan4 = default_scan(TX4);
18507
18508 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
18509 let mut result_cdfs = base_cdfs.clone();
18510 // spec `decode_tile`: `CurrentQIndex`/`DeltaLF` reset to the frame's own
18511 // `base_q_idx`/zero at the top of every tile, not once per frame (mirrors
18512 // `decode_key_frame_tile_with_cdfs`'s per-tile reset below); the
18513 // delta_q/delta_lf presence/resolution flags themselves are frame-level
18514 // and set once here.
18515 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
18516 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
18517 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
18518 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
18519 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
18520 let mut neighbours = Neighbours::new(
18521 cols as usize * 2,
18522 rows as usize * 2,
18523 mi_cols as usize,
18524 mi_rows as usize,
18525 );
18526 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
18527 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
18528 let mut lr_reference = [(
18529 crate::restoration::WienerInfo::default(),
18530 crate::restoration::SgrprojInfo::default(),
18531 ); 3];
18532
18533 // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile
18534 // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets
18535 // its own fresh SymbolDecoder over its own byte range and its own fresh
18536 // copy of the frame's initial CDFs; only context_update_tile_id's own
18537 // end-of-tile adapted table becomes the frame's own output.
18538 for (tile_idx, &data) in tiles.iter().enumerate() {
18539 let tile_num = tile_idx as u32;
18540 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
18541 let mi_row0 = tile_info.mi_row_starts[trow as usize];
18542 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
18543 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
18544 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
18545 let (sb_r0, sb_r1) = (
18546 (mi_row0 / SB_MI).min(sb_rows),
18547 mi_row1.div_ceil(SB_MI).min(sb_rows),
18548 );
18549 let (sb_c0, sb_c1) = (
18550 (mi_col0 / SB_MI).min(sb_cols),
18551 mi_col1.div_ceil(SB_MI).min(sb_cols),
18552 );
18553 let mut cdfs = base_cdfs.clone();
18554 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
18555 QUANT_DELTAS.with(|c| c.set(deltas));
18556 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
18557 let mut dec = SymbolDecoder::new(data);
18558 // lane-comppin r9: tile-entry range, the earliest point comparable
18559 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
18560 // first ladder rung before any symbol (partition or otherwise) is read.
18561 if std::env::var_os("EC_AV1_TELL").is_some() {
18562 eprintln!(
18563 "TELL label=tile_init tell={} range={}",
18564 dec.debug_bitpos(),
18565 dec.debug_state().0
18566 );
18567 }
18568 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
18569 y.set_tile_origin(
18570 mi_col0 as usize * 4,
18571 mi_row0 as usize * 4,
18572 (mi_col1 as usize * 4).min(y.width),
18573 (mi_row1 as usize * 4).min(y.height),
18574 );
18575 u.set_tile_origin(
18576 mi_col0 as usize * 2,
18577 mi_row0 as usize * 2,
18578 (mi_col1 as usize * 2).min(u.width),
18579 (mi_row1 as usize * 2).min(u.height),
18580 );
18581 v.set_tile_origin(
18582 mi_col0 as usize * 2,
18583 mi_row0 as usize * 2,
18584 (mi_col1 as usize * 2).min(v.width),
18585 (mi_row1 as usize * 2).min(v.height),
18586 );
18587 // lane-tiles r6: an MV candidate scan (mvstack.rs's grid.get) must
18588 // not reach across a tile boundary any more than intra prediction's
18589 // PlaneBuf reach does -- bounding the shared grid's own read window
18590 // per tile is equivalent to threading tile bounds through every
18591 // find_mv_stack* call site (all four read through this one grid).
18592 grid.set_tile_bounds(
18593 mi_row0 as usize,
18594 mi_col0 as usize,
18595 mi_row1 as usize,
18596 mi_col1 as usize,
18597 );
18598 TILE_HITS.with(|c| c.set(c.get() + 1));
18599
18600 // lane-sb128 r2: at `sb_size == 128` the tile walks each 128x128
18601 // superblock's four 64x64 quadrants in libaom `decode_partition` order
18602 // (TL, TR, BL, BR) and reads the 128 root's own loop-restoration units and
18603 // partition symbol once per superblock -- exactly what the key-frame tile
18604 // loop does; the 64-level body below is unchanged, `read_cdef`'s
18605 // per-64x64-quadrant reset (`CDEF_TRANSMITTED`) already matches libaom's
18606 // `cdef_idx[(mi_row & 16) >> 4 * 2 + (mi_col & 16) >> 4]` slot per quadrant.
18607 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
18608 if row_start {
18609 neighbours.start_row();
18610 }
18611 {
18612 if sb128 && sb_start {
18613 read_sb128_root(
18614 &mut dec,
18615 &mut cdfs,
18616 &neighbours,
18617 lr,
18618 &mut lr_grid,
18619 &mut lr_reference,
18620 sb_r,
18621 sb_c,
18622 mi_cols,
18623 mi_rows,
18624 )?;
18625 }
18626 if !sb128 {
18627 crate::restoration::read_lr(
18628 &mut dec,
18629 &mut cdfs,
18630 lr,
18631 &mut lr_grid,
18632 &mut lr_reference,
18633 sb_r * SB_MI,
18634 sb_c * SB_MI,
18635 SB_MI,
18636 );
18637 }
18638 CDEF_TRANSMITTED.with(|c| c.set(false));
18639 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
18640 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
18641 let (has_cols, has_rows) = (
18642 sb_c * SB_MI + SB_MI / 2 < mi_cols,
18643 sb_r * SB_MI + SB_MI / 2 < mi_rows,
18644 );
18645 // The straddle cases (one or both halves outside the true
18646 // frame) never carry a real alphabet symbol -- spec forces
18647 // SPLIT there (mirrors the intra key-frame tile's own
18648 // three-way write above). Only the (true, true) case can name
18649 // a non-SPLIT value, and this loop below only ever recurses as
18650 // SPLIT -- so a real non-SPLIT part64 here must refuse by name
18651 // instead of silently decoding as SPLIT and desyncing.
18652 let part64 = match (has_cols, has_rows) {
18653 (true, true) => {
18654 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
18655 if std::env::var_os("EC_AV1_TRACE").is_some() {
18656 eprintln!(
18657 "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}",
18658 sb_r * SB_MI,
18659 sb_c * SB_MI
18660 );
18661 }
18662 p
18663 }
18664 (true, false) => {
18665 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
18666 PARTITION_SPLIT
18667 }
18668 (false, true) => {
18669 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
18670 PARTITION_SPLIT
18671 }
18672 (false, false) => PARTITION_SPLIT,
18673 };
18674 if part64 == PARTITION_NONE {
18675 // lane-inter8 r1: the whole superblock as one 64x64 inter
18676 // block. `SB`-sized syntax throughout (size_group 3, same as
18677 // 32x32 -- `size_group_lookup[BLOCK_64X64] == 3`), luma
18678 // coefficients through `TxbSet::Luma64` with the 32-point
18679 // scan (TX_64X64 codes only its top-left corner, spec
18680 // 5.11.40 -- `read_inter_plane` widens the corner back to
18681 // 64x64 before the inverse transform), chroma as a plain
18682 // 32x32 `TxbSet::Chroma32`. TX_64X64 carries no `tx_type`
18683 // symbol at all, so the intra/inter luma sets coincide.
18684 INTER_SB_NONE_HITS.with(|c| c.set(c.get() + 1));
18685 decode_inter_block(
18686 &mut dec,
18687 &mut cdfs,
18688 &mut neighbours,
18689 &mut grid,
18690 sb_at,
18691 SB,
18692 mi_cols,
18693 mi_rows,
18694 &mut y,
18695 &mut u,
18696 &mut v,
18697 &ref_y,
18698 &ref_u,
18699 &ref_v,
18700 &ref_slots,
18701 &sign_bias_table,
18702 &global_motion,
18703 base_q_idx,
18704 TxbSet::Luma64,
18705 TxbSet::Luma64,
18706 TxbSet::Chroma32,
18707 TX32,
18708 TX32,
18709 &scan32,
18710 &scan32,
18711 3,
18712 allow_high_precision_mv,
18713 force_integer_mv,
18714 interp_fixed,
18715 enable_dual_filter,
18716 tpl_frame.as_ref(),
18717 reference_select,
18718 enable_masked_compound,
18719 enable_interintra_compound,
18720 enable_jnt_comp,
18721 order_hint_bits,
18722 order_hint,
18723 ref_order_hints,
18724 skip_mode_present,
18725 skip_mode_frame,
18726 switchable_motion_mode,
18727 allow_warped_motion,
18728 false,
18729 SB,
18730 SB,
18731 allow_screen_content_tools,
18732 frame_width as usize,
18733 )?;
18734 continue;
18735 }
18736 if part64 != PARTITION_SPLIT {
18737 return Err(unsupported(
18738 "an inter SB-level partition type other than NONE or SPLIT (this decoder's \
18739 inter tile path recurses a superblock only as SPLIT)",
18740 ));
18741 }
18742
18743 for quadrant in 0..4 {
18744 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
18745 if r32 >= rows || c32 >= cols {
18746 continue;
18747 }
18748 let at = (r32 as usize * 2, c32 as usize * 2);
18749 let ctx32 = neighbours.partition_ctx(at, BLOCK);
18750 let (has_cols32, has_rows32) = (
18751 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
18752 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
18753 );
18754 let part32 = if has_cols32 && has_rows32 {
18755 if std::env::var_os("EC_AV1_TRACE").is_some() {
18756 eprintln!(
18757 "TRACE part32_pre mi=({},{}) rng={}",
18758 r32 * BLOCK_MI,
18759 c32 * BLOCK_MI,
18760 dec.debug_state().0
18761 );
18762 }
18763 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
18764 if std::env::var_os("EC_AV1_TRACE").is_some() {
18765 eprintln!(
18766 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
18767 r32 * BLOCK_MI,
18768 c32 * BLOCK_MI
18769 );
18770 }
18771 p
18772 } else {
18773 match (has_cols32, has_rows32) {
18774 (true, false) => {
18775 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
18776 }
18777 (false, true) => {
18778 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
18779 }
18780 _ => {}
18781 }
18782 PARTITION_SPLIT
18783 };
18784 match part32 {
18785 PARTITION_NONE => {
18786 decode_inter_block(
18787 &mut dec,
18788 &mut cdfs,
18789 &mut neighbours,
18790 &mut grid,
18791 at,
18792 BLOCK,
18793 mi_cols,
18794 mi_rows,
18795 &mut y,
18796 &mut u,
18797 &mut v,
18798 &ref_y,
18799 &ref_u,
18800 &ref_v,
18801 &ref_slots,
18802 &sign_bias_table,
18803 &global_motion,
18804 base_q_idx,
18805 TxbSet::Luma32,
18806 TxbSet::Luma32Inter,
18807 TxbSet::Chroma16,
18808 TX32,
18809 TX16,
18810 &scan32,
18811 &scan16,
18812 3,
18813 allow_high_precision_mv,
18814 force_integer_mv,
18815 interp_fixed,
18816 enable_dual_filter,
18817 tpl_frame.as_ref(),
18818 reference_select,
18819 enable_masked_compound,
18820 enable_interintra_compound,
18821 enable_jnt_comp,
18822 order_hint_bits,
18823 order_hint,
18824 ref_order_hints,
18825 skip_mode_present,
18826 skip_mode_frame,
18827 switchable_motion_mode,
18828 allow_warped_motion,
18829 false,
18830 BLOCK,
18831 BLOCK,
18832 allow_screen_content_tools,
18833 frame_width as usize,
18834 )?;
18835 }
18836 PARTITION_SPLIT => {
18837 for sub in 0..4 {
18838 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
18839 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
18840 continue;
18841 }
18842 let (has_cols16, has_rows16) = (
18843 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
18844 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
18845 );
18846 if !has_cols16 && !has_rows16 {
18847 return Err(unsupported(
18848 "a 16x16 inter block whose true edge cuts through both \
18849 axes needs a rectangular transform this decoder does \
18850 not code yet",
18851 ));
18852 }
18853 let at16 = (sr, sc);
18854 let ctx16 = neighbours.partition_ctx(at16, SUB);
18855 // lane-inter8 r1: a straddling 16x16 cannot name a
18856 // value (spec forces SPLIT, one gathered bit); an
18857 // interior one reads the real alphabet, and
18858 // `PARTITION_SPLIT` now recurses into four 8x8
18859 // inter leaves through the very same loop the
18860 // straddling case has always used.
18861 let part16 = if has_cols16 && has_rows16 {
18862 let p = dec.symbol(&mut cdfs.partition_w16[ctx16]);
18863 if std::env::var_os("EC_AV1_TRACE").is_some() {
18864 let (rng, _) = dec.debug_state();
18865 eprintln!(
18866 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={p} rng={rng}",
18867 sr as u32 * SUB_MI,
18868 sc as u32 * SUB_MI
18869 );
18870 }
18871 p
18872 } else {
18873 if has_cols16 {
18874 dec.symbol_fixed(&gather(
18875 &cdfs.partition_w16[ctx16],
18876 VERT_ALIKE,
18877 ));
18878 } else {
18879 dec.symbol_fixed(&gather(
18880 &cdfs.partition_w16[ctx16],
18881 HORZ_ALIKE,
18882 ));
18883 }
18884 PARTITION_SPLIT
18885 };
18886 if part16 == PARTITION_NONE {
18887 decode_inter_block(
18888 &mut dec,
18889 &mut cdfs,
18890 &mut neighbours,
18891 &mut grid,
18892 at16,
18893 SUB,
18894 mi_cols,
18895 mi_rows,
18896 &mut y,
18897 &mut u,
18898 &mut v,
18899 &ref_y,
18900 &ref_u,
18901 &ref_v,
18902 &ref_slots,
18903 &sign_bias_table,
18904 &global_motion,
18905 base_q_idx,
18906 TxbSet::Luma16,
18907 if reduced_tx_set {
18908 TxbSet::Luma16Inter
18909 } else {
18910 TxbSet::Luma16InterSet1
18911 },
18912 TxbSet::Chroma8,
18913 TX16,
18914 TX8,
18915 &scan16,
18916 &scan8,
18917 2,
18918 allow_high_precision_mv,
18919 force_integer_mv,
18920 interp_fixed,
18921 enable_dual_filter,
18922 tpl_frame.as_ref(),
18923 reference_select,
18924 enable_masked_compound,
18925 enable_interintra_compound,
18926 enable_jnt_comp,
18927 order_hint_bits,
18928 order_hint,
18929 ref_order_hints,
18930 skip_mode_present,
18931 skip_mode_frame,
18932 switchable_motion_mode,
18933 allow_warped_motion,
18934 false,
18935 SUB,
18936 SUB,
18937 allow_screen_content_tools,
18938 frame_width as usize,
18939 )?;
18940 } else if part16 != PARTITION_SPLIT {
18941 return Err(unsupported(
18942 "an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet)",
18943 ));
18944 } else {
18945 if has_cols16 && has_rows16 {
18946 INTER_SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
18947 }
18948 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
18949 let leaf_positions: Vec<(u32, u32)> = (0..4)
18950 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
18951 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
18952 .collect();
18953 // lane-scaledref r1: `decode_inter_block8` IS
18954 // threaded for a scaled reference now (its
18955 // single-ref, compound and OBMC MC all take
18956 // spec 7.11.3.3's scaled walk), but the one
18957 // recipe that reaches this path at all -- a
18958 // 64x72 superres fixture whose bottom 16-row
18959 // band straddles the true edge, so the
18960 // gathered split bit lands on 8x8 leaves --
18961 // DESYNCS inside the leaf itself
18962 // (`from_switchable_symbol` handed a 4th
18963 // symbol, mc.rs:200), the same
18964 // below-8x8 desync lane-sub8 r2 left open and
18965 // unrelated to scaling. So the scaled MC here
18966 // is unproven: refuse by name rather than
18967 // ship a capability claim no gate exercises.
18968 // Deleting these six lines is the whole lift
18969 // once the leaf8 desync is fixed.
18970 if ref_y.width != frame_width as usize
18971 || ref_slots.iter().flatten().any(|(py, _, _)| {
18972 py.width != frame_width as usize
18973 })
18974 {
18975 return Err(unsupported(
18976 "an 8x8 partition leaf under a scaled reference (superres, unimplemented)",
18977 ));
18978 }
18979 let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option<i8>)> = Vec::new();
18980 for (mr, mc) in leaf_positions {
18981 let leaf_mi = (mr as usize, mc as usize);
18982 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
18983 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
18984 if part8 != PARTITION_NONE {
18985 return Err(unsupported(
18986 "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)",
18987 ));
18988 }
18989 let (
18990 skip,
18991 is_inter,
18992 skip_mode_leaf,
18993 compound_ctx8,
18994 leaf_filter,
18995 leaf_refs,
18996 ) = decode_inter_block8(
18997 &mut dec,
18998 &mut cdfs,
18999 &mut neighbours,
19000 &mut grid,
19001 mi_cols,
19002 mi_rows,
19003 at16,
19004 leaf_mi,
19005 &mut y,
19006 &mut u,
19007 &mut v,
19008 &ref_y,
19009 &ref_u,
19010 &ref_v,
19011 &ref_slots,
19012 base_q_idx,
19013 &scan8,
19014 &scan4,
19015 allow_high_precision_mv,
19016 force_integer_mv,
19017 &global_motion,
19018 enable_dual_filter,
19019 reference_select,
19020 enable_masked_compound,
19021 enable_interintra_compound,
19022 enable_jnt_comp,
19023 order_hint_bits,
19024 order_hint,
19025 ref_order_hints,
19026 skip_mode_present,
19027 skip_mode_frame,
19028 reduced_tx_set,
19029 interp_fixed,
19030 switchable_motion_mode,
19031 allow_warped_motion,
19032 allow_screen_content_tools,
19033 &sign_bias_table,
19034 tpl_frame.as_ref(),
19035 frame_width as usize,
19036 )?;
19037 prev_leaves.push((leaf_mi, skip, is_inter, leaf_refs.0, leaf_refs.1));
19038 // lane-inter8 r2: stamp THIS leaf's own
19039 // 2x2-mi span before the next leaf reads
19040 // it as a neighbour -- the whole-16x16
19041 // stamp below only ever described the
19042 // last leaf, so three quarters of the
19043 // block carried the wrong skip/ref/inter
19044 // state into the next block's contexts
19045 // (class context-read-from-one-cell).
19046 // lane-gmaffine r3: with the mi-granular
19047 // band, the leaf's OWN switchable-filter
19048 // symbols go in here -- the `[3, 3]`
19049 // ("intra, no filter") sentinel this used
19050 // to stamp made `obmc_blend`'s
19051 // `neighbour_filter` PANIC as soon as a
19052 // sibling leaf blended one of these.
19053 neighbours.record_inter_rect_mi(
19054 leaf_mi,
19055 2,
19056 2,
19057 skip,
19058 is_inter,
19059 leaf_refs.0,
19060 leaf_filter,
19061 skip_mode_leaf,
19062 );
19063 if let Some(ref1) = leaf_refs.1
19064 && let Some((_, _, group_idx, idx)) = compound_ctx8
19065 {
19066 neighbours.record_compound_ctx_rect_mi(
19067 leaf_mi, 2, 2, ref1, group_idx, idx,
19068 );
19069 }
19070 }
19071 // lane-inter8 r2: the four per-leaf
19072 // `record_inter_rect_mi` stamps above replace
19073 // the single whole-16x16 one that used to run
19074 // here with the LAST leaf's state.
19075 }
19076 }
19077 }
19078 PARTITION_HORZ_B => {
19079 // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip +
19080 // 16x16 bottom-left + 16x16 bottom-right. aomenc
19081 // carves static regions into it; the strip is
19082 // decoded as a square 32x32 block: for a `skip`
19083 // block the symbol stream is identical to the true
19084 // 32x16 coding (no residual, no motion_mode/warp
19085 // symbol), and the square stamps it leaves over the
19086 // bottom half (neighbour arrays, skip/lf grids) are
19087 // re-stamped by the C/D leaves right after. The
19088 // mi-granular `left_side_mi` rows of a last-block-in-
19089 // tile strip leak 32-vs-16 only until the per-tile
19090 // `Neighbours::new` reset.
19091 EXTENDED_PARTITION_HITS.with(|c| c.set(c.get() + 1));
19092 let at32 = at;
19093 decode_inter_block(
19094 &mut dec,
19095 &mut cdfs,
19096 &mut neighbours,
19097 &mut grid,
19098 at32,
19099 BLOCK,
19100 mi_cols,
19101 mi_rows,
19102 &mut y,
19103 &mut u,
19104 &mut v,
19105 &ref_y,
19106 &ref_u,
19107 &ref_v,
19108 &ref_slots,
19109 &sign_bias_table,
19110 &global_motion,
19111 base_q_idx,
19112 TxbSet::Luma32,
19113 TxbSet::Luma32Inter,
19114 TxbSet::Chroma16,
19115 TX32,
19116 TX16,
19117 &scan32,
19118 &scan16,
19119 3,
19120 allow_high_precision_mv,
19121 force_integer_mv,
19122 interp_fixed,
19123 enable_dual_filter,
19124 tpl_frame.as_ref(),
19125 reference_select,
19126 enable_masked_compound,
19127 enable_interintra_compound,
19128 enable_jnt_comp,
19129 order_hint_bits,
19130 order_hint,
19131 ref_order_hints,
19132 skip_mode_present,
19133 skip_mode_frame,
19134 switchable_motion_mode,
19135 allow_warped_motion,
19136 true,
19137 // lane-rect r2: the top strip's TRUE 32x16
19138 // footprint (was BLOCK,BLOCK -- the same square
19139 // corner-cut rect-flake-1 exposed on HORZ).
19140 BLOCK,
19141 SUB,
19142 allow_screen_content_tools,
19143 frame_width as usize,
19144 )?;
19145 if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows {
19146 decode_inter_block(
19147 &mut dec,
19148 &mut cdfs,
19149 &mut neighbours,
19150 &mut grid,
19151 (r32 as usize * 2 + 1, c32 as usize * 2),
19152 SUB,
19153 mi_cols,
19154 mi_rows,
19155 &mut y,
19156 &mut u,
19157 &mut v,
19158 &ref_y,
19159 &ref_u,
19160 &ref_v,
19161 &ref_slots,
19162 &sign_bias_table,
19163 &global_motion,
19164 base_q_idx,
19165 TxbSet::Luma16,
19166 if reduced_tx_set {
19167 TxbSet::Luma16Inter
19168 } else {
19169 TxbSet::Luma16InterSet1
19170 },
19171 TxbSet::Chroma8,
19172 TX16,
19173 TX8,
19174 &scan16,
19175 &scan8,
19176 2,
19177 allow_high_precision_mv,
19178 force_integer_mv,
19179 interp_fixed,
19180 enable_dual_filter,
19181 tpl_frame.as_ref(),
19182 reference_select,
19183 enable_masked_compound,
19184 enable_interintra_compound,
19185 enable_jnt_comp,
19186 order_hint_bits,
19187 order_hint,
19188 ref_order_hints,
19189 skip_mode_present,
19190 skip_mode_frame,
19191 switchable_motion_mode,
19192 allow_warped_motion,
19193 false,
19194 SUB,
19195 SUB,
19196 allow_screen_content_tools,
19197 frame_width as usize,
19198 )?;
19199 if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols {
19200 decode_inter_block(
19201 &mut dec,
19202 &mut cdfs,
19203 &mut neighbours,
19204 &mut grid,
19205 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
19206 SUB,
19207 mi_cols,
19208 mi_rows,
19209 &mut y,
19210 &mut u,
19211 &mut v,
19212 &ref_y,
19213 &ref_u,
19214 &ref_v,
19215 &ref_slots,
19216 &sign_bias_table,
19217 &global_motion,
19218 base_q_idx,
19219 TxbSet::Luma16,
19220 if reduced_tx_set {
19221 TxbSet::Luma16Inter
19222 } else {
19223 TxbSet::Luma16InterSet1
19224 },
19225 TxbSet::Chroma8,
19226 TX16,
19227 TX8,
19228 &scan16,
19229 &scan8,
19230 2,
19231 allow_high_precision_mv,
19232 force_integer_mv,
19233 interp_fixed,
19234 enable_dual_filter,
19235 tpl_frame.as_ref(),
19236 reference_select,
19237 enable_masked_compound,
19238 enable_interintra_compound,
19239 enable_jnt_comp,
19240 order_hint_bits,
19241 order_hint,
19242 ref_order_hints,
19243 skip_mode_present,
19244 skip_mode_frame,
19245 switchable_motion_mode,
19246 allow_warped_motion,
19247 false,
19248 SUB,
19249 SUB,
19250 allow_screen_content_tools,
19251 frame_width as usize,
19252 )?;
19253 }
19254 }
19255 }
19256 PARTITION_HORZ => {
19257 // lane-rect r2: two true 32x16 strips. Both read at
19258 // `side=BLOCK` (CDF/size-class selection stays square,
19259 // matching HORZ_B's accepted corner-cut) but bw4/bh4
19260 // (mvstack.rs, `motion_mode_eligible`) now derive from
19261 // `write_w`/`write_h`'s true 32x16 footprint -- the
19262 // pin's fix (r1's finding).
19263 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
19264 decode_inter_block(
19265 &mut dec,
19266 &mut cdfs,
19267 &mut neighbours,
19268 &mut grid,
19269 at,
19270 BLOCK,
19271 mi_cols,
19272 mi_rows,
19273 &mut y,
19274 &mut u,
19275 &mut v,
19276 &ref_y,
19277 &ref_u,
19278 &ref_v,
19279 &ref_slots,
19280 &sign_bias_table,
19281 &global_motion,
19282 base_q_idx,
19283 TxbSet::Luma32,
19284 TxbSet::Luma32Inter,
19285 TxbSet::Chroma16,
19286 TX32,
19287 TX16,
19288 &scan32,
19289 &scan16,
19290 3,
19291 allow_high_precision_mv,
19292 force_integer_mv,
19293 interp_fixed,
19294 enable_dual_filter,
19295 tpl_frame.as_ref(),
19296 reference_select,
19297 enable_masked_compound,
19298 enable_interintra_compound,
19299 enable_jnt_comp,
19300 order_hint_bits,
19301 order_hint,
19302 ref_order_hints,
19303 skip_mode_present,
19304 skip_mode_frame,
19305 switchable_motion_mode,
19306 allow_warped_motion,
19307 true,
19308 BLOCK,
19309 SUB,
19310 allow_screen_content_tools,
19311 frame_width as usize,
19312 )?;
19313 decode_inter_block(
19314 &mut dec,
19315 &mut cdfs,
19316 &mut neighbours,
19317 &mut grid,
19318 (r32 as usize * 2 + 1, c32 as usize * 2),
19319 BLOCK,
19320 mi_cols,
19321 mi_rows,
19322 &mut y,
19323 &mut u,
19324 &mut v,
19325 &ref_y,
19326 &ref_u,
19327 &ref_v,
19328 &ref_slots,
19329 &sign_bias_table,
19330 &global_motion,
19331 base_q_idx,
19332 TxbSet::Luma32,
19333 TxbSet::Luma32Inter,
19334 TxbSet::Chroma16,
19335 TX32,
19336 TX16,
19337 &scan32,
19338 &scan16,
19339 3,
19340 allow_high_precision_mv,
19341 force_integer_mv,
19342 interp_fixed,
19343 enable_dual_filter,
19344 tpl_frame.as_ref(),
19345 reference_select,
19346 enable_masked_compound,
19347 enable_interintra_compound,
19348 enable_jnt_comp,
19349 order_hint_bits,
19350 order_hint,
19351 ref_order_hints,
19352 skip_mode_present,
19353 skip_mode_frame,
19354 switchable_motion_mode,
19355 allow_warped_motion,
19356 true,
19357 BLOCK,
19358 SUB,
19359 allow_screen_content_tools,
19360 frame_width as usize,
19361 )?;
19362 }
19363 PARTITION_VERT => {
19364 // lane-rect r2: mirror of PARTITION_HORZ above with
19365 // width/height swapped.
19366 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
19367 decode_inter_block(
19368 &mut dec,
19369 &mut cdfs,
19370 &mut neighbours,
19371 &mut grid,
19372 at,
19373 BLOCK,
19374 mi_cols,
19375 mi_rows,
19376 &mut y,
19377 &mut u,
19378 &mut v,
19379 &ref_y,
19380 &ref_u,
19381 &ref_v,
19382 &ref_slots,
19383 &sign_bias_table,
19384 &global_motion,
19385 base_q_idx,
19386 TxbSet::Luma32,
19387 TxbSet::Luma32Inter,
19388 TxbSet::Chroma16,
19389 TX32,
19390 TX16,
19391 &scan32,
19392 &scan16,
19393 3,
19394 allow_high_precision_mv,
19395 force_integer_mv,
19396 interp_fixed,
19397 enable_dual_filter,
19398 tpl_frame.as_ref(),
19399 reference_select,
19400 enable_masked_compound,
19401 enable_interintra_compound,
19402 enable_jnt_comp,
19403 order_hint_bits,
19404 order_hint,
19405 ref_order_hints,
19406 skip_mode_present,
19407 skip_mode_frame,
19408 switchable_motion_mode,
19409 allow_warped_motion,
19410 true,
19411 SUB,
19412 BLOCK,
19413 allow_screen_content_tools,
19414 frame_width as usize,
19415 )?;
19416 decode_inter_block(
19417 &mut dec,
19418 &mut cdfs,
19419 &mut neighbours,
19420 &mut grid,
19421 (r32 as usize * 2, c32 as usize * 2 + 1),
19422 BLOCK,
19423 mi_cols,
19424 mi_rows,
19425 &mut y,
19426 &mut u,
19427 &mut v,
19428 &ref_y,
19429 &ref_u,
19430 &ref_v,
19431 &ref_slots,
19432 &sign_bias_table,
19433 &global_motion,
19434 base_q_idx,
19435 TxbSet::Luma32,
19436 TxbSet::Luma32Inter,
19437 TxbSet::Chroma16,
19438 TX32,
19439 TX16,
19440 &scan32,
19441 &scan16,
19442 3,
19443 allow_high_precision_mv,
19444 force_integer_mv,
19445 interp_fixed,
19446 enable_dual_filter,
19447 tpl_frame.as_ref(),
19448 reference_select,
19449 enable_masked_compound,
19450 enable_interintra_compound,
19451 enable_jnt_comp,
19452 order_hint_bits,
19453 order_hint,
19454 ref_order_hints,
19455 skip_mode_present,
19456 skip_mode_frame,
19457 switchable_motion_mode,
19458 allow_warped_motion,
19459 true,
19460 SUB,
19461 BLOCK,
19462 allow_screen_content_tools,
19463 frame_width as usize,
19464 )?;
19465 }
19466 PARTITION_HORZ_A => {
19467 // lane-partab r1: two 16x16 squares on top + a true
19468 // 32x16 strip below (libaom decode_partition
19469 // PARTITION_HORZ_A: TL, TR, bottom strip).
19470 PARTAB_HITS.with(|c| c.set(c.get() + 1));
19471 decode_inter_block(
19472 &mut dec,
19473 &mut cdfs,
19474 &mut neighbours,
19475 &mut grid,
19476 at,
19477 SUB,
19478 mi_cols,
19479 mi_rows,
19480 &mut y,
19481 &mut u,
19482 &mut v,
19483 &ref_y,
19484 &ref_u,
19485 &ref_v,
19486 &ref_slots,
19487 &sign_bias_table,
19488 &global_motion,
19489 base_q_idx,
19490 TxbSet::Luma16,
19491 if reduced_tx_set {
19492 TxbSet::Luma16Inter
19493 } else {
19494 TxbSet::Luma16InterSet1
19495 },
19496 TxbSet::Chroma8,
19497 TX16,
19498 TX8,
19499 &scan16,
19500 &scan8,
19501 2,
19502 allow_high_precision_mv,
19503 force_integer_mv,
19504 interp_fixed,
19505 enable_dual_filter,
19506 tpl_frame.as_ref(),
19507 reference_select,
19508 enable_masked_compound,
19509 enable_interintra_compound,
19510 enable_jnt_comp,
19511 order_hint_bits,
19512 order_hint,
19513 ref_order_hints,
19514 skip_mode_present,
19515 skip_mode_frame,
19516 switchable_motion_mode,
19517 allow_warped_motion,
19518 false,
19519 SUB,
19520 SUB,
19521 allow_screen_content_tools,
19522 frame_width as usize,
19523 )?;
19524 decode_inter_block(
19525 &mut dec,
19526 &mut cdfs,
19527 &mut neighbours,
19528 &mut grid,
19529 (r32 as usize * 2, c32 as usize * 2 + 1),
19530 SUB,
19531 mi_cols,
19532 mi_rows,
19533 &mut y,
19534 &mut u,
19535 &mut v,
19536 &ref_y,
19537 &ref_u,
19538 &ref_v,
19539 &ref_slots,
19540 &sign_bias_table,
19541 &global_motion,
19542 base_q_idx,
19543 TxbSet::Luma16,
19544 if reduced_tx_set {
19545 TxbSet::Luma16Inter
19546 } else {
19547 TxbSet::Luma16InterSet1
19548 },
19549 TxbSet::Chroma8,
19550 TX16,
19551 TX8,
19552 &scan16,
19553 &scan8,
19554 2,
19555 allow_high_precision_mv,
19556 force_integer_mv,
19557 interp_fixed,
19558 enable_dual_filter,
19559 tpl_frame.as_ref(),
19560 reference_select,
19561 enable_masked_compound,
19562 enable_interintra_compound,
19563 enable_jnt_comp,
19564 order_hint_bits,
19565 order_hint,
19566 ref_order_hints,
19567 skip_mode_present,
19568 skip_mode_frame,
19569 switchable_motion_mode,
19570 allow_warped_motion,
19571 false,
19572 SUB,
19573 SUB,
19574 allow_screen_content_tools,
19575 frame_width as usize,
19576 )?;
19577 decode_inter_block(
19578 &mut dec,
19579 &mut cdfs,
19580 &mut neighbours,
19581 &mut grid,
19582 (r32 as usize * 2 + 1, c32 as usize * 2),
19583 BLOCK,
19584 mi_cols,
19585 mi_rows,
19586 &mut y,
19587 &mut u,
19588 &mut v,
19589 &ref_y,
19590 &ref_u,
19591 &ref_v,
19592 &ref_slots,
19593 &sign_bias_table,
19594 &global_motion,
19595 base_q_idx,
19596 TxbSet::Luma32,
19597 TxbSet::Luma32Inter,
19598 TxbSet::Chroma16,
19599 TX32,
19600 TX16,
19601 &scan32,
19602 &scan16,
19603 3,
19604 allow_high_precision_mv,
19605 force_integer_mv,
19606 interp_fixed,
19607 enable_dual_filter,
19608 tpl_frame.as_ref(),
19609 reference_select,
19610 enable_masked_compound,
19611 enable_interintra_compound,
19612 enable_jnt_comp,
19613 order_hint_bits,
19614 order_hint,
19615 ref_order_hints,
19616 skip_mode_present,
19617 skip_mode_frame,
19618 switchable_motion_mode,
19619 allow_warped_motion,
19620 true,
19621 BLOCK,
19622 SUB,
19623 allow_screen_content_tools,
19624 frame_width as usize,
19625 )?;
19626 }
19627 PARTITION_VERT_A => {
19628 // lane-partab r1: mirror of PARTITION_HORZ_A with
19629 // width/height swapped (TL, BL, right 16x32 strip).
19630 PARTAB_HITS.with(|c| c.set(c.get() + 1));
19631 let _vert_ab = crate::encode::Reach::vert_ab_partition();
19632 decode_inter_block(
19633 &mut dec,
19634 &mut cdfs,
19635 &mut neighbours,
19636 &mut grid,
19637 at,
19638 SUB,
19639 mi_cols,
19640 mi_rows,
19641 &mut y,
19642 &mut u,
19643 &mut v,
19644 &ref_y,
19645 &ref_u,
19646 &ref_v,
19647 &ref_slots,
19648 &sign_bias_table,
19649 &global_motion,
19650 base_q_idx,
19651 TxbSet::Luma16,
19652 if reduced_tx_set {
19653 TxbSet::Luma16Inter
19654 } else {
19655 TxbSet::Luma16InterSet1
19656 },
19657 TxbSet::Chroma8,
19658 TX16,
19659 TX8,
19660 &scan16,
19661 &scan8,
19662 2,
19663 allow_high_precision_mv,
19664 force_integer_mv,
19665 interp_fixed,
19666 enable_dual_filter,
19667 tpl_frame.as_ref(),
19668 reference_select,
19669 enable_masked_compound,
19670 enable_interintra_compound,
19671 enable_jnt_comp,
19672 order_hint_bits,
19673 order_hint,
19674 ref_order_hints,
19675 skip_mode_present,
19676 skip_mode_frame,
19677 switchable_motion_mode,
19678 allow_warped_motion,
19679 false,
19680 SUB,
19681 SUB,
19682 allow_screen_content_tools,
19683 frame_width as usize,
19684 )?;
19685 decode_inter_block(
19686 &mut dec,
19687 &mut cdfs,
19688 &mut neighbours,
19689 &mut grid,
19690 (r32 as usize * 2 + 1, c32 as usize * 2),
19691 SUB,
19692 mi_cols,
19693 mi_rows,
19694 &mut y,
19695 &mut u,
19696 &mut v,
19697 &ref_y,
19698 &ref_u,
19699 &ref_v,
19700 &ref_slots,
19701 &sign_bias_table,
19702 &global_motion,
19703 base_q_idx,
19704 TxbSet::Luma16,
19705 if reduced_tx_set {
19706 TxbSet::Luma16Inter
19707 } else {
19708 TxbSet::Luma16InterSet1
19709 },
19710 TxbSet::Chroma8,
19711 TX16,
19712 TX8,
19713 &scan16,
19714 &scan8,
19715 2,
19716 allow_high_precision_mv,
19717 force_integer_mv,
19718 interp_fixed,
19719 enable_dual_filter,
19720 tpl_frame.as_ref(),
19721 reference_select,
19722 enable_masked_compound,
19723 enable_interintra_compound,
19724 enable_jnt_comp,
19725 order_hint_bits,
19726 order_hint,
19727 ref_order_hints,
19728 skip_mode_present,
19729 skip_mode_frame,
19730 switchable_motion_mode,
19731 allow_warped_motion,
19732 false,
19733 SUB,
19734 SUB,
19735 allow_screen_content_tools,
19736 frame_width as usize,
19737 )?;
19738 decode_inter_block(
19739 &mut dec,
19740 &mut cdfs,
19741 &mut neighbours,
19742 &mut grid,
19743 (r32 as usize * 2, c32 as usize * 2 + 1),
19744 BLOCK,
19745 mi_cols,
19746 mi_rows,
19747 &mut y,
19748 &mut u,
19749 &mut v,
19750 &ref_y,
19751 &ref_u,
19752 &ref_v,
19753 &ref_slots,
19754 &sign_bias_table,
19755 &global_motion,
19756 base_q_idx,
19757 TxbSet::Luma32,
19758 TxbSet::Luma32Inter,
19759 TxbSet::Chroma16,
19760 TX32,
19761 TX16,
19762 &scan32,
19763 &scan16,
19764 3,
19765 allow_high_precision_mv,
19766 force_integer_mv,
19767 interp_fixed,
19768 enable_dual_filter,
19769 tpl_frame.as_ref(),
19770 reference_select,
19771 enable_masked_compound,
19772 enable_interintra_compound,
19773 enable_jnt_comp,
19774 order_hint_bits,
19775 order_hint,
19776 ref_order_hints,
19777 skip_mode_present,
19778 skip_mode_frame,
19779 switchable_motion_mode,
19780 allow_warped_motion,
19781 true,
19782 SUB,
19783 BLOCK,
19784 allow_screen_content_tools,
19785 frame_width as usize,
19786 )?;
19787 }
19788 PARTITION_VERT_B => {
19789 // lane-partab r1: true 16x32 strip on the left + two
19790 // 16x16 squares on the right (libaom decode_partition
19791 // PARTITION_VERT_B: left strip, TR, BR).
19792 PARTAB_HITS.with(|c| c.set(c.get() + 1));
19793 let _vert_ab = crate::encode::Reach::vert_ab_partition();
19794 decode_inter_block(
19795 &mut dec,
19796 &mut cdfs,
19797 &mut neighbours,
19798 &mut grid,
19799 at,
19800 BLOCK,
19801 mi_cols,
19802 mi_rows,
19803 &mut y,
19804 &mut u,
19805 &mut v,
19806 &ref_y,
19807 &ref_u,
19808 &ref_v,
19809 &ref_slots,
19810 &sign_bias_table,
19811 &global_motion,
19812 base_q_idx,
19813 TxbSet::Luma32,
19814 TxbSet::Luma32Inter,
19815 TxbSet::Chroma16,
19816 TX32,
19817 TX16,
19818 &scan32,
19819 &scan16,
19820 3,
19821 allow_high_precision_mv,
19822 force_integer_mv,
19823 interp_fixed,
19824 enable_dual_filter,
19825 tpl_frame.as_ref(),
19826 reference_select,
19827 enable_masked_compound,
19828 enable_interintra_compound,
19829 enable_jnt_comp,
19830 order_hint_bits,
19831 order_hint,
19832 ref_order_hints,
19833 skip_mode_present,
19834 skip_mode_frame,
19835 switchable_motion_mode,
19836 allow_warped_motion,
19837 true,
19838 SUB,
19839 BLOCK,
19840 allow_screen_content_tools,
19841 frame_width as usize,
19842 )?;
19843 decode_inter_block(
19844 &mut dec,
19845 &mut cdfs,
19846 &mut neighbours,
19847 &mut grid,
19848 (r32 as usize * 2, c32 as usize * 2 + 1),
19849 SUB,
19850 mi_cols,
19851 mi_rows,
19852 &mut y,
19853 &mut u,
19854 &mut v,
19855 &ref_y,
19856 &ref_u,
19857 &ref_v,
19858 &ref_slots,
19859 &sign_bias_table,
19860 &global_motion,
19861 base_q_idx,
19862 TxbSet::Luma16,
19863 if reduced_tx_set {
19864 TxbSet::Luma16Inter
19865 } else {
19866 TxbSet::Luma16InterSet1
19867 },
19868 TxbSet::Chroma8,
19869 TX16,
19870 TX8,
19871 &scan16,
19872 &scan8,
19873 2,
19874 allow_high_precision_mv,
19875 force_integer_mv,
19876 interp_fixed,
19877 enable_dual_filter,
19878 tpl_frame.as_ref(),
19879 reference_select,
19880 enable_masked_compound,
19881 enable_interintra_compound,
19882 enable_jnt_comp,
19883 order_hint_bits,
19884 order_hint,
19885 ref_order_hints,
19886 skip_mode_present,
19887 skip_mode_frame,
19888 switchable_motion_mode,
19889 allow_warped_motion,
19890 false,
19891 SUB,
19892 SUB,
19893 allow_screen_content_tools,
19894 frame_width as usize,
19895 )?;
19896 decode_inter_block(
19897 &mut dec,
19898 &mut cdfs,
19899 &mut neighbours,
19900 &mut grid,
19901 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
19902 SUB,
19903 mi_cols,
19904 mi_rows,
19905 &mut y,
19906 &mut u,
19907 &mut v,
19908 &ref_y,
19909 &ref_u,
19910 &ref_v,
19911 &ref_slots,
19912 &sign_bias_table,
19913 &global_motion,
19914 base_q_idx,
19915 TxbSet::Luma16,
19916 if reduced_tx_set {
19917 TxbSet::Luma16Inter
19918 } else {
19919 TxbSet::Luma16InterSet1
19920 },
19921 TxbSet::Chroma8,
19922 TX16,
19923 TX8,
19924 &scan16,
19925 &scan8,
19926 2,
19927 allow_high_precision_mv,
19928 force_integer_mv,
19929 interp_fixed,
19930 enable_dual_filter,
19931 tpl_frame.as_ref(),
19932 reference_select,
19933 enable_masked_compound,
19934 enable_interintra_compound,
19935 enable_jnt_comp,
19936 order_hint_bits,
19937 order_hint,
19938 ref_order_hints,
19939 skip_mode_present,
19940 skip_mode_frame,
19941 switchable_motion_mode,
19942 allow_warped_motion,
19943 false,
19944 SUB,
19945 SUB,
19946 allow_screen_content_tools,
19947 frame_width as usize,
19948 )?;
19949 }
19950 _ => {
19951 return Err(unsupported(format!(
19952 "an INTER 32x32 partition type this decoder does not code (value={part32})"
19953 )));
19954 }
19955 }
19956 }
19957 }
19958 }
19959
19960 if tile_num == tile_info.context_update_tile_id {
19961 result_cdfs = cdfs;
19962 }
19963 }
19964
19965 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
19966 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
19967 // that isolate whether a decode-order frame's mismatch already exists
19968 // in reconstruction (this dump) vs is introduced by the loop filter
19969 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
19970 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
19971 use std::io::Write;
19972 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
19973 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
19974 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
19975 let _ = f.write_all(&narrow(&y));
19976 let _ = f.write_all(&narrow(&u));
19977 let _ = f.write_all(&narrow(&v));
19978 }
19979 } else {
19980 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
19981 }
19982 apply_deblock(
19983 &mut y,
19984 &mut u,
19985 &mut v,
19986 loop_filter,
19987 &neighbours,
19988 frame_width as usize,
19989 frame_height as usize,
19990 );
19991 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
19992 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
19993 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
19994 // dump above these bisect WHICH filter stage introduced a mismatch.
19995 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
19996 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
19997 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
19998 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
19999
20000 let motion_field = build_motion_field(
20001 &grid,
20002 mi_cols as usize,
20003 mi_rows as usize,
20004 order_hint,
20005 ref_order_hints,
20006 );
20007
20008 let (fw, fh) = (frame_width as usize, frame_height as usize);
20009 if fw == width && fh == height {
20010 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
20011 return Ok((
20012 Picture {
20013 width,
20014 height,
20015 y: y.data,
20016 u: u.data,
20017 v: v.data,
20018 },
20019 result_cdfs,
20020 motion_field,
20021 ));
20022 }
20023 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
20024 let mut out = Vec::with_capacity(w * h);
20025 for row in 0..h {
20026 out.extend(plane.data[row * plane.width..][..w].iter().copied());
20027 }
20028 out
20029 };
20030 // lane-superres r10 (fixed r9): same real-margin stash as
20031 // `decode_key_frame_tile_with_cdfs` (see that function's comment) -- the
20032 // real reconstructed extent is the mi-aligned `true_width`/`true_height`
20033 // (`mi_cols`/`mi_rows` * 4), NOT the superblock-padded `width`/`height`
20034 // this branch was reading before: columns `[true_width, width)` were
20035 // never actually coded (the last partial superblock stops at
20036 // `true_width`), so stashing out to `width` handed the chroma upscale's
20037 // right-edge replicate a slice of uninitialized/stale buffer one column
20038 // early -- the same shorten-vs-replicate shape as `av1-truesize`. The
20039 // key-frame branch above already used `true_width`/`true_height`; this
20040 // just matches it.
20041 LAST_FRAME_WIDE_MARGIN.with(|m| {
20042 *m.borrow_mut() = if true_width > fw || true_height > fh {
20043 Some(Picture {
20044 width: true_width,
20045 height: true_height,
20046 y: crop(&y, true_width, true_height),
20047 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
20048 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
20049 })
20050 } else {
20051 None
20052 }
20053 });
20054 Ok((
20055 Picture {
20056 width: fw,
20057 height: fh,
20058 y: crop(&y, fw, fh),
20059 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
20060 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
20061 },
20062 result_cdfs,
20063 motion_field,
20064 ))
20065}
20066
20067#[cfg(test)]
20068mod tests {
20069
20070 /// lane-fistrip r1 (class `enumerate-the-table-domain`): every block
20071 /// shape this decoder can hand [`filter_intra_size_class_rect`], against
20072 /// `av1_filter_intra_allowed_bsize` (`block_size_wide <= 32 &&
20073 /// block_size_high <= 32`) and `default_filter_intra_cdfs`
20074 /// (entropymode.c) row by row. A class that exists must carry ITS OWN
20075 /// bsize's default probability -- a wrong row is a silently different
20076 /// symbol, not a decode error. The shapes with no class are listed here
20077 /// with their reason so the residue is pinned rather than implied.
20078 #[test]
20079 fn filter_intra_classes_carry_their_own_libaom_default_row() {
20080 // `default_filter_intra_cdfs[bsize]`, BLOCK_SIZES_ALL order, as
20081 // (width, height, default, refused_by) for the shapes <= 32 on both
20082 // axes. The first three fields are GENERATED from the oracle by
20083 // `scripts/extract-filter-intra-cdfs.py` (it reads BLOCK_SIZES_ALL's
20084 // order from enums.h and the table from entropymode.c, so no hand
20085 // transcription can drift -- lane-fistrip r1 listed the four 1:4
20086 // shapes as 16384 out of exactly that kind of guess; their real rows
20087 // are 12770/10368/20229/18101). `refused_by` is `None` for a shape
20088 // this decoder's partition tree reaches today -- it must own a class,
20089 // and that class must carry exactly this row -- and the refusal
20090 // string that blocks the shape otherwise. Either way the row is
20091 // pinned HERE, so the round that lifts one of those refusals cannot
20092 // land a wrong CDF row for the shape it unlocks.
20093 const PART16: &str = "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes \
20094 only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)";
20095 let libaom: &[(usize, usize, u16, Option<&str>)] = &[
20096 (4, 4, 4621, None),
20097 (4, 8, 6743, None),
20098 (8, 4, 5893, None),
20099 (8, 8, 7866, None),
20100 (8, 16, 12551, None),
20101 (16, 8, 9394, None),
20102 (16, 16, 12408, None),
20103 (16, 32, 14301, None),
20104 (32, 16, 12756, None),
20105 (32, 32, 22343, None),
20106 // The 1:4 strips: a 16x16-level PARTITION_HORZ_4/VERT_4 gives
20107 // 4x16/16x4 (still refused by name before any leaf is coded),
20108 // a 32x32-level one 8x32/32x8.
20109 (4, 16, 12770, Some(PART16)),
20110 (16, 4, 10368, Some(PART16)),
20111 // lane-fi32x8 r1: the 32-level pair is coded (four 32x8/8x32
20112 // strips per `PARTITION_HORZ_4`/`VERT_4`) and now owns classes
20113 // 10/11; only the 16-level pair is still refused before any leaf.
20114 (8, 32, 20229, None),
20115 (32, 8, 18101, None),
20116 ];
20117 let mut classes_seen = std::collections::BTreeSet::new();
20118 for &(bw, bh, default, refused_by) in libaom {
20119 match filter_intra_size_class_rect(bw, bh) {
20120 Some(class) => {
20121 assert!(
20122 refused_by.is_none(),
20123 "{bw}x{bh} has a CDF class but is listed as refused by {refused_by:?} -- \
20124 one of the two is stale"
20125 );
20126 assert_eq!(
20127 crate::cdf::FILTER_INTRA[class][0],
20128 default,
20129 "{bw}x{bh} (class {class}) must carry default_filter_intra_cdfs' own row"
20130 );
20131 assert_eq!(
20132 &crate::cdf::FILTER_INTRA[class][1..],
20133 &[32768u16, 0][..],
20134 "{bw}x{bh} (class {class}) is a 2-symbol CDF: {{p, 32768, count}}"
20135 );
20136 assert!(
20137 classes_seen.insert(class),
20138 "class {class} is claimed by two shapes -- one of them reads the other's \
20139 probability"
20140 );
20141 }
20142 None => {
20143 let why = refused_by.unwrap_or_else(|| {
20144 panic!(
20145 "{bw}x{bh} is inside av1_filter_intra_allowed_bsize and reachable, \
20146 but has no CDF class -- its use_filter_intra symbol is never read"
20147 )
20148 });
20149 assert!(!why.is_empty(), "{bw}x{bh}'s refusal string must name the blocker");
20150 }
20151 }
20152 }
20153 // The other direction: every row of `cdf::FILTER_INTRA` was claimed
20154 // by exactly one shape above, so no row can be left over (or shared)
20155 // once a class is added or removed.
20156 assert_eq!(
20157 classes_seen.len(),
20158 crate::cdf::FILTER_INTRA.len(),
20159 "cdf::FILTER_INTRA has {} rows but only {:?} are claimed by an allowed shape",
20160 crate::cdf::FILTER_INTRA.len(),
20161 classes_seen
20162 );
20163 // Past the bound on either axis: no symbol at all (spec
20164 // `filter_intra_mode_info` never reads one).
20165 for (bw, bh) in [(64, 64), (64, 32), (32, 64)] {
20166 assert!(
20167 filter_intra_size_class_rect(bw, bh).is_none(),
20168 "{bw}x{bh} is past av1_filter_intra_allowed_bsize's <=32 bound"
20169 );
20170 }
20171 }
20172 use super::*;
20173
20174 /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR --
20175 /// `SCAN_4X16[i]` must name the transpose of the position
20176 /// `SCAN_16X4[i]` names (class scan-weights-cross-axis: a naive copy of
20177 /// libaom's column-major `default_scan_*` installs the transpose and only
20178 /// an asymmetric check catches it). Also pins both as permutations, and
20179 /// pins the same relation for the 32x8/8x32 luma pair this arm reuses.
20180 #[test]
20181 fn the_rect4_scans_are_transposed_pairs() {
20182 for (a, b, w, h) in [
20183 (&SCAN_16X4[..], &SCAN_4X16[..], 16usize, 4usize),
20184 (&SCAN_32X8[..], &SCAN_8X32[..], 32, 8),
20185 ] {
20186 let mut seen_a: Vec<u16> = a.to_vec();
20187 seen_a.sort_unstable();
20188 assert_eq!(
20189 seen_a,
20190 (0..(w * h) as u16).collect::<Vec<_>>(),
20191 "{w}x{h} scan is not a permutation of its positions"
20192 );
20193 for (i, (&pa, &pb)) in a.iter().zip(b.iter()).enumerate() {
20194 let (row, col) = (pa as usize / w, pa as usize % w);
20195 assert_eq!(
20196 pb as usize,
20197 col * w.min(h) + row,
20198 "scan step {i}: {w}x{h} visits (row {row}, col {col}) but its transpose \
20199 visits position {pb}"
20200 );
20201 }
20202 }
20203 }
20204
20205 /// lane-rectsplit r4 (class `enumerate-table-domain`): [`base_ctx`]'s
20206 /// `TX_CLASS_2D` arm must, over the WHOLE 5x5 domain of both rect shapes
20207 /// and the square one, return exactly what libaom's
20208 /// `av1_nz_map_ctx_offset[tx_size][coeff_idx]` holds -- the flat tables
20209 /// transcribed in [`cdf`], read at libaom's own COLUMN-major
20210 /// `coeff_idx = col * 32 + row`, i.e. `table[col][row]`. r1..r3 read them
20211 /// `[row][col]`, which is the transpose (the OTHER shape's rule, with 11
20212 /// and 16 swapped): it desynced the first superblock strip whose luma
20213 /// corner held a coefficient off the first row/column.
20214 #[test]
20215 fn base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain() {
20216 let grid = [0i32; 32 * 32];
20217 for (shape, table) in [
20218 (Some((64usize, 32usize)), &cdf::NZ_MAP_CTX_OFFSET_64X32),
20219 (Some((32, 64)), &cdf::NZ_MAP_CTX_OFFSET_32X64),
20220 (None, &cdf::NZ_MAP_CTX_OFFSET_32),
20221 ] {
20222 for row in 0..5usize {
20223 for col in 0..5usize {
20224 // An all-zero neighbourhood makes the magnitude term 0,
20225 // so `base_ctx` returns the offset itself.
20226 let got = base_ctx(&grid, 32, row, col, TxClass::TwoD, shape);
20227 let want = if row == 0 && col == 0 {
20228 0
20229 } else {
20230 table[col][row] as usize
20231 };
20232 assert_eq!(got, want, "{shape:?} at (row {row}, col {col})");
20233 }
20234 }
20235 }
20236 }
20237
20238 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
20239 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
20240 // single-purpose writers with their own skip-context rule (keyed to
20241 // superblock position, not the neighbour-tracked one every real block
20242 // uses), never reached by `encode_key_frame_with_modes` — decoding them
20243 // would need a second, throwaway context convention next to the real
20244 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
20245 // this decoder's one target, and the round-trip test below is against
20246 // that path with real quantised residual, not a synthetic all-DC frame.
20247
20248 /// [`SCAN_8X4`]/[`SCAN_4X8`] (lane-rectx r2): a bijection check alone
20249 /// cannot catch a transposed pair -- a swap of two orientation tables is
20250 /// still a bijection over the same 32 positions. This pins BOTH arrays
20251 /// at once, element-for-element, against literal transcriptions of
20252 /// libaom's real `default_scan_4x8`/`default_scan_8x4` in
20253 /// `av1/common/scan.c` (`~/.cache/aom-oracle/src`, read directly for
20254 /// this test, not re-derived from the zigzag formula). The two source
20255 /// sequences are themselves different in their own right (not equal to
20256 /// each other), so this is asymmetric in the two axes: if the repo's
20257 /// `SCAN_8X4`/`SCAN_4X8` were swapped with each other, one side of this
20258 /// assert pair would fail even though each individual array would still
20259 /// pass a same-orientation bijection test.
20260 #[test]
20261 fn scan_8x4_and_4x8_are_not_transposed_against_each_other() {
20262 // libaom `default_scan_4x8` verbatim (scan.c:29-32) -- this repo
20263 // names it `SCAN_8X4` under the established w/h axis swap (see
20264 // `SCAN_8X4`'s own doc comment).
20265 const LIBAOM_DEFAULT_SCAN_4X8: [u16; 32] = [
20266 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21,
20267 14, 7, 29, 22, 15, 30, 23, 31,
20268 ];
20269 // libaom `default_scan_8x4` verbatim (scan.c:44-47) -- this repo's
20270 // `SCAN_4X8`.
20271 const LIBAOM_DEFAULT_SCAN_8X4: [u16; 32] = [
20272 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22,
20273 25, 28, 23, 26, 29, 27, 30, 31,
20274 ];
20275 assert_ne!(
20276 LIBAOM_DEFAULT_SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4,
20277 "the two libaom source sequences must differ, or this pin would \
20278 pass regardless of a swap"
20279 );
20280 assert_eq!(SCAN_8X4, LIBAOM_DEFAULT_SCAN_4X8, "SCAN_8X4 vs libaom default_scan_4x8");
20281 assert_eq!(SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4, "SCAN_4X8 vs libaom default_scan_8x4");
20282 }
20283
20284 /// lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= 32",
20285 /// so a DC_PRED 16x8/8x16 strip reads a `use_filter_intra` flag exactly
20286 /// like a square 16x16 does. [`filter_intra_size_class_rect`] returned
20287 /// `None` at those two sizes, so the symbol was never read and the tile
20288 /// desynced from that block on (root-caused against an instrumented
20289 /// aomdec `EC_TRACE_COEFF` ladder on a real stream: identical `mode=0`/
20290 /// `uv_mode=9` values, our range 34808 vs the oracle's 40668 at the very
20291 /// next transform block).
20292 ///
20293 /// The two rows are ASYMMETRIC (9394 for 16x8, 12551 for 8x16), so this
20294 /// pin fails if the pair is ever transposed -- the shape the repo's
20295 /// scan tables already carry (`SCAN_8X4` == libaom `default_scan_4x8`).
20296 #[test]
20297 fn a_rect_strip_below_16x16_reads_its_own_filter_intra_cdf_row() {
20298 // `default_filter_intra_cdfs` (entropymode.c), indexed by BLOCK_SIZES_ALL:
20299 // [4] = BLOCK_8X16, [5] = BLOCK_16X8, [7] = BLOCK_16X32, [8] = BLOCK_32X16.
20300 const LIBAOM_8X16: u16 = 12551;
20301 const LIBAOM_16X8: u16 = 9394;
20302 let c16x8 = filter_intra_size_class_rect(16, 8).expect("16x8 reads use_filter_intra");
20303 let c8x16 = filter_intra_size_class_rect(8, 16).expect("8x16 reads use_filter_intra");
20304 assert_ne!(c16x8, c8x16, "the two orientations must not share a CDF row");
20305 assert_eq!(cdf::FILTER_INTRA[c16x8][0], LIBAOM_16X8, "16x8 filter_intra row");
20306 assert_eq!(cdf::FILTER_INTRA[c8x16][0], LIBAOM_8X16, "8x16 filter_intra row");
20307 // The sizes one class up keep their own distinct rows (lane-intradisp).
20308 assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(32, 16).unwrap()][0], 12756);
20309 assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(16, 32).unwrap()][0], 14301);
20310 // A size with a side over 32 is genuinely not allowed the flag.
20311 assert_eq!(filter_intra_size_class_rect(64, 32), None);
20312 }
20313
20314 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
20315 /// when both references sit on the same temporal side -- the three
20316 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
20317 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
20318 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
20319 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
20320 /// not just the three enumerated syntax pairs).
20321 #[test]
20322 fn is_uni_comp_ref_matches_forward_backward_sides() {
20323 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
20324 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
20325 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
20326 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
20327 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
20328 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
20329 }
20330
20331 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
20332 /// with the real second reference (lane-av1comp round 12: previously
20333 /// always cleared to `None` by `record_inter`, so the next block's own
20334 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
20335 /// -- could never see a real compound neighbour).
20336 #[test]
20337 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
20338 let mut n = Neighbours::new(4, 4, 16, 16);
20339 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
20340 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
20341 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
20342 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
20343 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
20344 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
20345 }
20346
20347 /// A below-16px leaf must clear the palette neighbour state over its own
20348 /// cell: before lane-palette2 r8 `record_palette_y_rect`'s `w / SUB` loops
20349 /// ran zero times for any sub-16 span, so `decode_leaf_rect` /
20350 /// `decode_leaf8` left a previous block's palette size and colours in the
20351 /// above/left arrays and the NEXT block read `palette_y_mode` off the
20352 /// wrong CDF row with a stale colour cache (class
20353 /// [[cdf-row-held-constant]]).
20354 #[test]
20355 fn a_sub16_leaf_after_a_palette_block_yields_palette_ctx_zero() {
20356 let mut n = Neighbours::new(4, 4, 16, 16);
20357 // A real 16x16 palette block covering SUB cell (1, 1).
20358 n.record_palette_y_rect((1, 1), 16, 16, 2, [7, 9, 0, 0, 0, 0, 0, 0]);
20359 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
20360 assert_eq!(ctx, 2, "the palette block itself must be visible");
20361 assert_eq!(cache, vec![7, 9]);
20362 // An 8x8 non-palette leaf in that same cell.
20363 n.record_palette_y_rect((1, 1), 8, 8, 0, [0u16; 8]);
20364 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
20365 assert_eq!(ctx, 0, "a sub-16 non-palette leaf must clear its own cell");
20366 assert!(cache.is_empty(), "and its stale colour cache with it");
20367 // Same for the chroma half.
20368 n.record_palette_uv_rect((1, 1), 16, 16, 2, [1, 2, 0, 0, 0, 0, 0, 0]);
20369 assert_eq!(n.palette_uv_cache((1, 1)), vec![1, 2]);
20370 n.record_palette_uv_rect((1, 1), 8, 8, 0, [0u16; 8]);
20371 assert!(n.palette_uv_cache((1, 1)).is_empty());
20372 }
20373
20374 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
20375 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
20376 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
20377 /// -- a few corner and interior points, not the whole 6x6 grid.
20378 #[test]
20379 fn compound_mode_ctx_map_matches_libaom_corners() {
20380 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
20381 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
20382 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
20383 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
20384 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
20385 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
20386 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
20387 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
20388 // exactly the ranges `find_mv_stack_compound` produces.
20389 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
20390 }
20391
20392 #[test]
20393 fn a_frame_with_no_mode_info_grid_is_refused() {
20394 assert!(
20395 decode_key_frame_tile(
20396 &[0u8; 4],
20397 0,
20398 32,
20399 32,
20400 0,
20401 128,
20402 false,
20403 &CdefParams::default(),
20404 &LoopFilterParams::default(),
20405 false,
20406 true,
20407 false,
20408 false,
20409 )
20410 .is_err()
20411 );
20412 }
20413
20414 /// Encodes and decodes one picture with `modes`, asserting the decoder's
20415 /// planes are byte-exact against the encoder's own reconstruction.
20416 fn round_trips(w: usize, h: usize, modes: &[u8]) {
20417 use crate::encode::{Encoded, Picture as Pic};
20418 let mut source = vec![0u16; w * h];
20419 for row in 0..h {
20420 for col in 0..w {
20421 source[row * w + col] = ((row * 3 + col * 5) % 251) as u16;
20422 }
20423 }
20424 let picture = Pic {
20425 width: w,
20426 height: h,
20427 y: source,
20428 u: vec![128; w * h / 4],
20429 v: vec![128; w * h / 4],
20430 };
20431 let Encoded {
20432 tile,
20433 reconstruction,
20434 mi_cols,
20435 mi_rows,
20436 base_q_idx,
20437 ..
20438 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
20439 let decoded = decode_key_frame_tile(
20440 &tile,
20441 mi_cols,
20442 mi_rows,
20443 base_q_idx,
20444 w as u32,
20445 h as u32,
20446 false,
20447 &CdefParams::default(),
20448 &LoopFilterParams::default(),
20449 false,
20450 true,
20451 false,
20452 false,
20453 )
20454 .unwrap();
20455 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
20456 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
20457 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
20458 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
20459 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
20460 }
20461
20462 #[test]
20463 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
20464 for (w, h) in [(128usize, 128usize), (192, 128)] {
20465 round_trips(w, h, &[DC_PRED as u8]);
20466 }
20467 }
20468
20469 /// Every one of the thirteen key-frame intra modes, at their base angle,
20470 /// on real (non-flat) content: the mode search picks whichever wins each
20471 /// block, so this exercises the directional edge/reach plumbing this
20472 /// decoder round adds, not just `DC_PRED`.
20473 #[test]
20474 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
20475 for (w, h) in [(128usize, 128usize), (192, 128)] {
20476 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
20477 }
20478 }
20479
20480 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
20481 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
20482 /// this decoder round adds.
20483 #[test]
20484 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
20485 for (w, h) in [(854usize, 480usize), (216, 96)] {
20486 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
20487 }
20488 }
20489
20490 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
20491 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
20492 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
20493 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
20494 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
20495 /// bit, `partition_w8` leaves).
20496 #[test]
20497 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
20498 for (w, h) in [(40usize, 32usize), (640, 360)] {
20499 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
20500 }
20501 }
20502
20503 /// A skipped block codes no residual syntax at all (spec 5.11.34):
20504 /// straight prediction on every plane. The real key-frame writer never
20505 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
20506 /// `0`), so this constructs the exact symbol sequence a writer that did
20507 /// emit it would produce, by hand, and asserts the decoded reconstruction
20508 /// is pure DC prediction (mid-grey, with no neighbours) rather than
20509 /// refusing.
20510 #[test]
20511 fn a_skipped_block_decodes_to_pure_prediction() {
20512 use crate::msac::SymbolEncoder;
20513 let mut cdfs = Cdfs::new(q_ctx_of(40));
20514 let mut enc = SymbolEncoder::new();
20515 // One whole, unsplit 64x64 superblock, coded skip = true.
20516 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
20517 enc.symbol(1, &mut cdfs.skip[0]);
20518 enc.symbol(
20519 DC_PRED,
20520 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
20521 );
20522 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
20523 let data = enc.finish();
20524 let decoded = decode_key_frame_tile(
20525 &data,
20526 16,
20527 16,
20528 40,
20529 64,
20530 64,
20531 false,
20532 &CdefParams::default(),
20533 &LoopFilterParams::default(),
20534 false,
20535 true,
20536 false,
20537 false,
20538 )
20539 .unwrap();
20540 assert!(
20541 decoded.y.iter().all(|&s| s == 128),
20542 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
20543 );
20544 }
20545
20546 /// An inter tile's SB-level `part64` used to be read and thrown away
20547 /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real
20548 /// non-SPLIT value there silently desynced the whole tile instead of
20549 /// refusing. Hand-writes a single whole superblock's `part64 = HORZ`
20550 /// symbol (never produced by this crate's own encoder, which only ever
20551 /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can)
20552 /// and asserts this decoder refuses by name rather than decoding garbage.
20553 #[test]
20554 fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
20555 use crate::msac::SymbolEncoder;
20556 let mut cdfs = Cdfs::new(q_ctx_of(40));
20557 let mut enc = SymbolEncoder::new();
20558 enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]);
20559 let data = enc.finish();
20560 let reference = crate::encode::Picture::grey(64, 64);
20561 let err = decode_inter_frame_tile(
20562 &data,
20563 16,
20564 16,
20565 40,
20566 64,
20567 64,
20568 &reference,
20569 [None; 8],
20570 &CdefParams::default(),
20571 &LoopFilterParams::default(),
20572 false,
20573 false,
20574 Some(mc::InterpFilterKind::Regular),
20575 false,
20576 false,
20577 )
20578 .unwrap_err();
20579 let msg = err.to_string();
20580 assert!(
20581 msg.contains("SPLIT"),
20582 "expected the named inter-SB-partition refusal, got: {msg}"
20583 );
20584 }
20585
20586 // ffmpeg cross-oracle: an independent decoder (not this crate's own
20587 // encoder-side reconstruction) agrees with what this module decodes,
20588 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
20589 // name (that module is another lane's territory this round, and the
20590 // helpers are `#[cfg(test)]`-private to it).
20591 use std::io::Write;
20592 use std::process::{Command, Stdio};
20593
20594 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
20595 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
20596 /// aomenc gate decodes its stream through ffmpeg and is meaningless
20597 /// without it -- turns it into a hard failure. Without this the require
20598 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
20599 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
20600 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
20601 fn have_ffmpeg() -> bool {
20602 let present = Command::new("ffmpeg")
20603 .arg("-version")
20604 .stdout(Stdio::null())
20605 .stderr(Stdio::null())
20606 .status()
20607 .is_ok_and(|s| s.success());
20608 assert!(
20609 present
20610 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
20611 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
20612 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
20613 );
20614 present
20615 }
20616
20617 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
20618 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
20619 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
20620 let mut child = Command::new("ffmpeg")
20621 .args([
20622 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
20623 ])
20624 .stdin(Stdio::piped())
20625 .stdout(Stdio::piped())
20626 .stderr(Stdio::piped())
20627 .spawn()
20628 .expect("ffmpeg failed to start");
20629 child
20630 .stdin
20631 .take()
20632 .expect("ffmpeg stdin")
20633 .write_all(stream)
20634 .expect("writing the stream to ffmpeg");
20635 let out = child.wait_with_output().expect("ffmpeg failed to run");
20636 assert!(
20637 out.status.success(),
20638 "ffmpeg refused the stream: {}",
20639 String::from_utf8_lossy(&out.stderr)
20640 );
20641 let (luma, chroma) = (width * height, width * height / 4);
20642 assert_eq!(
20643 out.stdout.len(),
20644 luma + 2 * chroma,
20645 "expected one 4:2:0 frame"
20646 );
20647 Picture {
20648 width,
20649 height,
20650 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
20651 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
20652 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
20653 }
20654 }
20655
20656 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
20657 fn ffmpeg_decode_sequence(
20658 stream: &[u8],
20659 width: usize,
20660 height: usize,
20661 frames: usize,
20662 ) -> Vec<Picture> {
20663 let mut child = Command::new("ffmpeg")
20664 .args([
20665 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
20666 ])
20667 .stdin(Stdio::piped())
20668 .stdout(Stdio::piped())
20669 .stderr(Stdio::piped())
20670 .spawn()
20671 .expect("ffmpeg failed to start");
20672 child
20673 .stdin
20674 .take()
20675 .expect("ffmpeg stdin")
20676 .write_all(stream)
20677 .expect("writing the stream to ffmpeg");
20678 let out = child.wait_with_output().expect("ffmpeg failed to run");
20679 assert!(
20680 out.status.success(),
20681 "ffmpeg refused the stream: {}",
20682 String::from_utf8_lossy(&out.stderr)
20683 );
20684 let (luma, chroma) = (width * height, width * height / 4);
20685 let frame_bytes = luma + 2 * chroma;
20686 assert_eq!(
20687 out.stdout.len(),
20688 frame_bytes * frames,
20689 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
20690 String::from_utf8_lossy(&out.stderr)
20691 );
20692 (0..frames)
20693 .map(|i| {
20694 let base = i * frame_bytes;
20695 Picture {
20696 width,
20697 height,
20698 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
20699 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
20700 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
20701 }
20702 })
20703 .collect()
20704 }
20705
20706 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
20707 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
20708 /// test binary runs callers on parallel threads, and a shared name lets
20709 /// one test's cleanup race another's still-reading ffprobe --
20710 /// pid-keyed-temp-path class).
20711 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
20712 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20713 let path = std::env::temp_dir().join(format!(
20714 "ec-av1-decode-probe-{}-{}.obu",
20715 std::process::id(),
20716 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20717 ));
20718 let _ = std::fs::remove_file(&path);
20719 std::fs::write(&path, stream).expect("writing the probe stream");
20720 let out = Command::new("ffprobe")
20721 .args([
20722 "-v",
20723 "error",
20724 "-f",
20725 "obu",
20726 "-select_streams",
20727 "v:0",
20728 "-show_entries",
20729 "stream=width,height",
20730 "-of",
20731 "csv=p=0",
20732 ])
20733 .arg(&path)
20734 .output()
20735 .expect("ffprobe failed to run");
20736 let _ = std::fs::remove_file(&path);
20737 assert!(
20738 out.status.success(),
20739 "ffprobe refused the stream: {}",
20740 String::from_utf8_lossy(&out.stderr)
20741 );
20742 let text = String::from_utf8_lossy(&out.stdout);
20743 let mut fields = text.trim().split(',');
20744 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
20745 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
20746 (width, height)
20747 }
20748
20749 /// This module's own decoder against an independent one (ffmpeg), not
20750 /// just against this crate's encoder-side reconstruction: both decoders
20751 /// read the identical tile bytes, so agreement here rules out a bug this
20752 /// crate's own writer and reader could otherwise share.
20753 #[test]
20754 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
20755 if !have_ffmpeg() {
20756 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
20757 return;
20758 }
20759 use crate::encode::encode_key_frame;
20760 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
20761 let picture = round_trip_test_card(width, height);
20762 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
20763 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
20764 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
20765 let ours = decode_key_frame_tile(
20766 &encoded.tile,
20767 encoded.mi_cols,
20768 encoded.mi_rows,
20769 encoded.base_q_idx,
20770 coded_w,
20771 coded_h,
20772 false,
20773 &CdefParams::default(),
20774 &LoopFilterParams::default(),
20775 false,
20776 true,
20777 false,
20778 false,
20779 )
20780 .unwrap();
20781 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
20782 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
20783 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
20784 }
20785 }
20786
20787 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
20788 let mut picture = crate::encode::Picture::grey(width, height);
20789 for row in 0..height {
20790 for col in 0..width {
20791 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
20792 }
20793 }
20794 for row in 0..height / 2 {
20795 for col in 0..width / 2 {
20796 let i = row * width / 2 + col;
20797 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
20798 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
20799 }
20800 }
20801 picture
20802 }
20803
20804 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
20805 let mut picture = crate::encode::Picture::grey(width, height);
20806 for y in 0..height {
20807 for x in 0..width {
20808 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
20809 let gradient = sx * 200.0 / width as f64;
20810 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
20811 }
20812 }
20813 for y in 0..height / 2 {
20814 for x in 0..width / 2 {
20815 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
20816 let i = y * width / 2 + x;
20817 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
20818 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
20819 }
20820 }
20821 picture
20822 }
20823
20824 /// A GOP (one key frame plus several inter frames, each panned so its
20825 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
20826 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
20827 /// reconstruction, frame by frame, chaining each decoded frame straight
20828 /// into the next as its reference -- exactly the single-slot DPB
20829 /// [`crate::encode::encode_sequence`] itself threads.
20830 fn gop_round_trips(width: usize, height: usize) {
20831 use crate::encode::encode_sequence;
20832 let pictures: Vec<_> = (0..4)
20833 .map(|i| panned_test_card(width, height, i * 3))
20834 .collect();
20835 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
20836 assert_eq!(encoded.frames.len(), 4);
20837
20838 let key = &encoded.frames[0];
20839 let mut reference = decode_key_frame_tile(
20840 &key.tile,
20841 key.mi_cols,
20842 key.mi_rows,
20843 key.base_q_idx,
20844 width as u32,
20845 height as u32,
20846 false,
20847 &CdefParams::default(),
20848 &LoopFilterParams::default(),
20849 false,
20850 true,
20851 false,
20852 false,
20853 )
20854 .unwrap();
20855 assert_eq!(
20856 reference.y, key.reconstruction.y,
20857 "{width}x{height} frame 0 luma"
20858 );
20859 assert_eq!(
20860 reference.u, key.reconstruction.u,
20861 "{width}x{height} frame 0 U"
20862 );
20863 assert_eq!(
20864 reference.v, key.reconstruction.v,
20865 "{width}x{height} frame 0 V"
20866 );
20867
20868 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
20869 let decoded = decode_inter_frame_tile(
20870 &frame.tile,
20871 frame.mi_cols,
20872 frame.mi_rows,
20873 frame.base_q_idx,
20874 width as u32,
20875 height as u32,
20876 &reference,
20877 [None; 8],
20878 &CdefParams::default(),
20879 &LoopFilterParams::default(),
20880 false,
20881 false,
20882 Some(mc::InterpFilterKind::Regular),
20883 false,
20884 false,
20885 )
20886 .unwrap();
20887 assert_eq!(
20888 decoded.y, frame.reconstruction.y,
20889 "{width}x{height} frame {i} luma"
20890 );
20891 assert_eq!(
20892 decoded.u, frame.reconstruction.u,
20893 "{width}x{height} frame {i} U"
20894 );
20895 assert_eq!(
20896 decoded.v, frame.reconstruction.v,
20897 "{width}x{height} frame {i} V"
20898 );
20899 reference = decoded;
20900 }
20901 }
20902
20903 #[test]
20904 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
20905 gop_round_trips(128, 64);
20906 }
20907
20908 /// Same claim, at a size that is not a whole number of 32x32 blocks
20909 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
20910 /// split path is exercised too.
20911 #[test]
20912 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
20913 gop_round_trips(216, 96);
20914 }
20915
20916 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
20917 /// this module does, frame for frame.
20918 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
20919 /// MV stack's *second* candidate (`near_mv`), not its first
20920 /// (`nearest_mv`) -- a hand-built symbol stream drives
20921 /// [`decode_inter_block`] directly, since this crate's own encoder never
20922 /// writes NEARMV (round 3: it never chooses the mode).
20923 #[test]
20924 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
20925 use crate::msac::SymbolEncoder;
20926 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
20927
20928 const LAST_FRAME: i8 = 1;
20929 let (mi_cols, mi_rows) = (12u32, 12u32);
20930 let side = 16usize; // one 16x16 leaf block
20931 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
20932 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
20933 let bw4 = side / 4;
20934
20935 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
20936 let (above_mv, left_mv) = ((4, 4), (8, 8));
20937 let neighbour = |mv| MiInfo {
20938 is_inter: true,
20939 ref_frame: LAST_FRAME,
20940 ref_frame1: None,
20941 mv1: None,
20942 mv,
20943 is_new_mv: false,
20944 size: 1,
20945 size_h: 1,
20946 is_global_mv0: false,
20947 is_global_mv1: false,
20948 };
20949 for col in mi_col..mi_col + bw4 {
20950 grid.set(mi_row - 1, col, neighbour(above_mv));
20951 }
20952 for row in mi_row..mi_row + bw4 {
20953 grid.set(row, mi_col - 1, neighbour(left_mv));
20954 }
20955
20956 let stack = find_mv_stack(
20957 &grid,
20958 mi_row,
20959 mi_col,
20960 bw4,
20961 bw4,
20962 LAST_FRAME,
20963 mi_cols as usize,
20964 mi_rows as usize,
20965 );
20966 // Sanity on the test's own setup, not the code under test: two equal-
20967 // weight candidates keep scan order (above, then left -- module doc).
20968 assert_eq!(stack.entries.len(), 2);
20969 assert_eq!(stack.nearest_mv, above_mv);
20970 assert_eq!(stack.near_mv, left_mv);
20971
20972 let (skip_ctx, ii_ctx, sr_ctx) = (
20973 0usize,
20974 intra_inter_ctx(true, true, false, false),
20975 single_ref_ctx(false),
20976 );
20977
20978 let mut cdfs = Cdfs::new(q_ctx_of(100));
20979 let mut enc = SymbolEncoder::new();
20980 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
20981 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
20982 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
20983 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
20984 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
20985 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
20986 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
20987 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
20988 let data = enc.finish();
20989
20990 let (width, height) = (64usize, 64usize);
20991 let ref_pattern: Vec<u16> = (0..width * height).map(|i| (i % 251) as u16).collect();
20992 let ref_plane = |scale: usize| PlaneBuf {
20993 data: ref_pattern
20994 .iter()
20995 .step_by(scale.max(1))
20996 .take((width / scale) * (height / scale))
20997 .copied()
20998 .collect(),
20999 width: width / scale,
21000 height: height / scale,
21001 true_width: width / scale,
21002 true_height: height / scale,
21003 tile_x0: 0,
21004 tile_y0: 0,
21005 tile_x1: width / scale,
21006 tile_y1: height / scale,
21007 };
21008 let ref_y = PlaneBuf {
21009 data: ref_pattern.clone(),
21010 width,
21011 height,
21012 true_width: width,
21013 true_height: height,
21014 tile_x0: 0,
21015 tile_y0: 0,
21016 tile_x1: width,
21017 tile_y1: height,
21018 };
21019 let ref_u = ref_plane(2);
21020 let ref_v = ref_plane(2);
21021
21022 let mut y = PlaneBuf {
21023 data: vec![0u16; width * height],
21024 width,
21025 height,
21026 true_width: width,
21027 true_height: height,
21028 tile_x0: 0,
21029 tile_y0: 0,
21030 tile_x1: width,
21031 tile_y1: height,
21032 };
21033 let mut u = PlaneBuf {
21034 data: vec![0u16; (width / 2) * (height / 2)],
21035 width: width / 2,
21036 height: height / 2,
21037 true_width: width / 2,
21038 true_height: height / 2,
21039 tile_x0: 0,
21040 tile_y0: 0,
21041 tile_x1: width / 2,
21042 tile_y1: height / 2,
21043 };
21044 let mut v = PlaneBuf {
21045 data: vec![0u16; (width / 2) * (height / 2)],
21046 width: width / 2,
21047 height: height / 2,
21048 true_width: width / 2,
21049 true_height: height / 2,
21050 tile_x0: 0,
21051 tile_y0: 0,
21052 tile_x1: width / 2,
21053 tile_y1: height / 2,
21054 };
21055
21056 let mut cdfs = Cdfs::new(q_ctx_of(100));
21057 let mut dec = SymbolDecoder::new(&data);
21058 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
21059 decode_inter_block(
21060 &mut dec,
21061 &mut cdfs,
21062 &mut neighbours,
21063 &mut grid,
21064 (r, c),
21065 side,
21066 mi_cols,
21067 mi_rows,
21068 &mut y,
21069 &mut u,
21070 &mut v,
21071 &ref_y,
21072 &ref_u,
21073 &ref_v,
21074 &[None; 8],
21075 &NO_SIGN_BIAS,
21076 &[ec_av1_syntax::WarpParams::default(); 7],
21077 100,
21078 TxbSet::Luma16,
21079 TxbSet::Luma16Inter,
21080 TxbSet::Chroma8,
21081 TX16,
21082 TX8,
21083 &[],
21084 &[],
21085 0,
21086 false,
21087 false,
21088 Some(mc::InterpFilterKind::Regular),
21089 false,
21090 None,
21091 false,
21092 false,
21093 false,
21094 false,
21095 0,
21096 0,
21097 [0; 7],
21098 false,
21099 [0; 2],
21100 false,
21101 false,
21102 false,
21103 side,
21104 side,
21105 false,
21106 width,
21107 )
21108 .unwrap();
21109
21110 let (px, py) = (c * SUB, r * SUB);
21111 let mut want_near = vec![0u16; side * side];
21112 crate::mc::predict(
21113 &ref_y.data,
21114 ref_y.width,
21115 ref_y.true_width,
21116 ref_y.true_height,
21117 mv_to_q4(px, left_mv.1, true),
21118 mv_to_q4(py, left_mv.0, true),
21119 side,
21120 side,
21121 &mut want_near,
21122 );
21123 let mut want_nearest = vec![0u16; side * side];
21124 crate::mc::predict(
21125 &ref_y.data,
21126 ref_y.width,
21127 ref_y.true_width,
21128 ref_y.true_height,
21129 mv_to_q4(px, above_mv.1, true),
21130 mv_to_q4(py, above_mv.0, true),
21131 side,
21132 side,
21133 &mut want_nearest,
21134 );
21135 assert_ne!(
21136 want_near, want_nearest,
21137 "test setup: the two candidate MVs must predict differently"
21138 );
21139
21140 let mut got = vec![0u16; side * side];
21141 for row in 0..side {
21142 got[row * side..(row + 1) * side].copy_from_slice(
21143 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
21144 );
21145 }
21146 assert_eq!(
21147 got, want_near,
21148 "NEARMV predicted from the wrong stack entry"
21149 );
21150 }
21151
21152 #[test]
21153 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
21154 if !have_ffmpeg() {
21155 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
21156 return;
21157 }
21158 use crate::encode::encode_sequence;
21159 let (width, height) = (128usize, 64usize);
21160 let pictures: Vec<_> = (0..3)
21161 .map(|i| panned_test_card(width, height, i * 3))
21162 .collect();
21163 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
21164 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
21165 let ffmpeg_frames =
21166 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
21167
21168 let key = &encoded.frames[0];
21169 let mut reference = decode_key_frame_tile(
21170 &key.tile,
21171 key.mi_cols,
21172 key.mi_rows,
21173 key.base_q_idx,
21174 coded_w,
21175 coded_h,
21176 false,
21177 &CdefParams::default(),
21178 &LoopFilterParams::default(),
21179 false,
21180 true,
21181 false,
21182 false,
21183 )
21184 .unwrap();
21185 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
21186
21187 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
21188 let decoded = decode_inter_frame_tile(
21189 &frame.tile,
21190 frame.mi_cols,
21191 frame.mi_rows,
21192 frame.base_q_idx,
21193 coded_w,
21194 coded_h,
21195 &reference,
21196 [None; 8],
21197 &CdefParams::default(),
21198 &LoopFilterParams::default(),
21199 false,
21200 false,
21201 Some(mc::InterpFilterKind::Regular),
21202 false,
21203 false,
21204 )
21205 .unwrap();
21206 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
21207 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
21208 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
21209 reference = decoded;
21210 }
21211 }
21212}
21213
21214#[cfg(test)]
21215mod tx4x8_table_tests {
21216 use super::*;
21217
21218 /// Asymmetric gate on the two new scan tables (class
21219 /// `reference-layout-not-spec`): a transposed pair of tables passes any
21220 /// "is a permutation" check, so this pins the pair AGAINST each other --
21221 /// `SCAN_8X4[k]` must be `SCAN_4X8[k]` reflected across the diagonal, and
21222 /// both must be bijections of `0..32` in our own row-major indexing.
21223 #[test]
21224 fn the_rect_4x8_scans_are_each_other_transposed() {
21225 let mut seen_a = [false; 32];
21226 let mut seen_b = [false; 32];
21227 for k in 0..32usize {
21228 let a = SCAN_4X8[k] as usize;
21229 let b = SCAN_8X4[k] as usize;
21230 assert!(!seen_a[a] && !seen_b[b], "scan position {k} repeats");
21231 seen_a[a] = true;
21232 seen_b[b] = true;
21233 let (row, col) = (a / 4, a % 4);
21234 assert_eq!(b, col * 8 + row, "SCAN_8X4[{k}] is not SCAN_4X8[{k}] transposed");
21235 }
21236 assert!(seen_a.iter().all(|&s| s) && seen_b.iter().all(|&s| s));
21237 }
21238
21239 /// `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/`mcol_scan_8x4`
21240 /// (libaom `scan.c`), converted out of their column-major encoding by
21241 /// `(p % h) * w + p / h` -- the head of each, pinned so the rect
21242 /// `V_DCT`/`H_DCT` walk cannot silently transpose.
21243 #[test]
21244 fn the_rect_class1_scans_match_libaom() {
21245 assert_eq!(
21246 class_scan_table_wh(4, 8, TxClass::Vert),
21247 (0..32u16).collect::<Vec<_>>()
21248 );
21249 assert_eq!(
21250 &class_scan_table_wh(4, 8, TxClass::Horiz)[..8],
21251 &[0u16, 4, 8, 12, 16, 20, 24, 28]
21252 );
21253 assert_eq!(
21254 class_scan_table_wh(8, 4, TxClass::Vert),
21255 (0..32u16).collect::<Vec<_>>()
21256 );
21257 assert_eq!(
21258 &class_scan_table_wh(8, 4, TxClass::Horiz)[..8],
21259 &[0u16, 8, 16, 24, 1, 9, 17, 25]
21260 );
21261 }
21262
21263 /// The 32-position `eob_pt` alphabet: six symbols (one more than the
21264 /// 16-position table, one fewer than the 64-position one), strictly
21265 /// increasing, terminated at 32768 with the adaptation counter after it.
21266 #[test]
21267 fn the_32_position_eob_tables_are_well_formed() {
21268 for table in [
21269 &cdf::EOB_PT_32_LUMA_Q0,
21270 &cdf::EOB_PT_32_LUMA_Q1,
21271 &cdf::EOB_PT_32_LUMA,
21272 &cdf::EOB_PT_32_LUMA_Q3,
21273 &cdf::EOB_PT_32_LUMA_CLASS1_Q0,
21274 &cdf::EOB_PT_32_LUMA_CLASS1_Q1,
21275 &cdf::EOB_PT_32_LUMA_CLASS1,
21276 &cdf::EOB_PT_32_LUMA_CLASS1_Q3,
21277 ] {
21278 assert_eq!(table.len(), 7);
21279 assert_eq!(table[5], 32768);
21280 assert_eq!(table[6], 0);
21281 for w in table[..6].windows(2) {
21282 assert!(w[0] < w[1], "{table:?} is not increasing");
21283 }
21284 }
21285 }
21286
21287 /// `Reach::of_rect` must read libaom's own `has_tr_4x8`/`has_tr_8x4`
21288 /// rows, not the 32x16 pair the two existing rect strips use: the two
21289 /// shapes disagree at a position inside the superblock, which is what
21290 /// makes this an asymmetric check rather than a tautology.
21291 #[test]
21292 fn the_sub8_rect_reach_tables_are_shape_specific() {
21293 let a = Reach::of_rect(4, 8, 4, 8, 64, 64);
21294 let b = Reach::of_rect(8, 4, 8, 4, 64, 64);
21295 assert!(
21296 a.above_right != b.above_right || a.below_left != b.below_left,
21297 "4x8 and 8x4 reach identically at mirrored positions -- one table is unused"
21298 );
21299 }
21300}