forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb123ba7Tahinli3 months ago1499 commits

decode.rs21414 lines, 917.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,
285 // computed against the sequence's own superblock size (lane-sb128b r1:
286 // it used to be hardcoded against 64 and disabled under `sb128`, which a
287 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
288 // wrong).
289 if is_whole_sb && skip {
290 return;
291 }
292 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
293 const DELTA_Q_SMALL: i32 = 3;
294 if abs >= DELTA_Q_SMALL {
295 let rem_bits = dec.literal(3) + 1;
296 let thr = (1i32 << rem_bits) + 1;
297 abs = dec.literal(rem_bits) as i32 + thr;
298 }
299 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
300 let reduced = if sign_negative { -abs } else { abs };
301 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
302 let res = DELTA_Q_RES.with(|c| c.get());
303 CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
304}
305
306// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
307// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
308thread_local! {
309 static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
310 static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
311 static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
312}
313// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
314// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
315// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
316// updates index 0 and every reader treats that as the value for all 4
317// indices (spec `read_delta_lf_params`'s own single-cdf branch).
318thread_local! {
319 static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
320}
321// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
322// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
323thread_local! {
324 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
325}
326
327/// Current value of [`DELTA_LF_HITS`].
328pub(crate) fn delta_lf_hits() -> usize {
329 DELTA_LF_HITS.with(|c| c.get())
330}
331
332/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
333/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
334/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
335/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
336/// read once into index 0 otherwise.
337fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
338 if !DELTA_LF_PRESENT.with(|c| c.get()) {
339 return;
340 }
341 let sb_mi = sb_mi_cur() as usize;
342 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
343 return;
344 }
345 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
346 // computed against the sequence's own superblock size (lane-sb128b r1:
347 // it used to be hardcoded against 64 and disabled under `sb128`, which a
348 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
349 // wrong).
350 if is_whole_sb && skip {
351 return;
352 }
353 let multi = DELTA_LF_MULTI.with(|c| c.get());
354 let res = DELTA_LF_RES.with(|c| c.get());
355 let count = if multi { 4 } else { 1 };
356 let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
357 for i in 0..count {
358 let mut abs = if multi {
359 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
360 } else {
361 dec.symbol(&mut cdfs.delta_lf) as i32
362 };
363 const DELTA_LF_SMALL: i32 = 3;
364 if abs >= DELTA_LF_SMALL {
365 let rem_bits = dec.literal(3) + 1;
366 let thr = (1i32 << rem_bits) + 1;
367 abs = dec.literal(rem_bits) as i32 + thr;
368 }
369 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
370 let reduced = if sign_negative { -abs } else { abs };
371 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
372 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
373 }
374 CURRENT_DELTA_LF.with(|c| c.set(cur));
375}
376
377/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
378/// after `skip` is known at every block-decode call site. A no-op at
379/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
380/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
381/// `allow_intrabc`, so neither needs a separate check here. Reads once per
382/// superblock, at the first non-skip block.
383fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
384 let bits = CDEF_BITS.with(|c| c.get());
385 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
386 return;
387 }
388 let idx = dec.literal(u32::from(bits)) as u8;
389 CDEF_TRANSMITTED.with(|c| c.set(true));
390 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
391 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
392 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
393 if sb_cols > 0 {
394 CDEF_IDX_GRID.with(|g| {
395 let mut g = g.borrow_mut();
396 let i = sb_r * sb_cols + sb_c;
397 if i < g.len() {
398 g[i] = idx;
399 }
400 });
401 }
402}
403
404// ---------------------------------------------------------------------------
405// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
406// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
407// the two consumers a real stream exercises: the per-segment quantizer index
408// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
409// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
410// `read_intra_segment_id`/`read_inter_segment_id` and
411// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
412// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
413// is what the oracle every gate here compares against actually does.
414thread_local! {
415 static SEG: std::cell::RefCell<SegmentationParams> =
416 std::cell::RefCell::new(SegmentationParams::default());
417 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
418 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
419 static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
420 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
421 /// this frame has no primary reference (spec `load_previous_segment_ids`).
422 static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
423 /// `(mi_rows, mi_cols)` for both maps above.
424 static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
425 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
426 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
427 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
428 static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
429 static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
430 /// The block currently being decoded -- read back by [`block_q_idx`].
431 static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
432 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
433 static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
434 /// How many real `segment_id` symbols were read, and the set of segment
435 /// ids any block ended up with -- the gate's proof the feature fired.
436 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
437 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
438 /// How many `seg_id_predicted` symbols were read (temporal update).
439 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
440}
441
442/// Installs this frame's segmentation parameters and allocates its map, with
443/// `prev` the primary reference frame's saved map (spec
444/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
445/// slot). Called once per frame, whether or not segmentation is enabled.
446pub(crate) fn set_segmentation(
447 seg: SegmentationParams,
448 mi_rows: usize,
449 mi_cols: usize,
450 prev: Option<&[u8]>,
451) {
452 SEG.with(|s| *s.borrow_mut() = seg);
453 SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));
454 SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
455 PREV_SEG_IDS.with(|m| {
456 let mut m = m.borrow_mut();
457 m.clear();
458 if let Some(p) = prev {
459 if p.len() == mi_rows * mi_cols {
460 m.extend_from_slice(p);
461 }
462 }
463 });
464 ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
465 LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
466 CUR_SEGMENT_ID.with(|c| c.set(0));
467}
468
469/// This frame's decoded segment map, to be stored into whichever reference
470/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
471pub(crate) fn take_segment_ids() -> Vec<u8> {
472 SEG_IDS.with(|m| m.borrow().clone())
473}
474
475/// How many `segment_id` symbols have been read (never reset per frame).
476pub(crate) fn segment_id_hits() -> usize {
477 SEG_ID_HITS.with(|c| c.get())
478}
479
480/// How many distinct segment ids any decoded block has carried.
481pub(crate) fn segment_ids_seen() -> usize {
482 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
483}
484
485/// How many `seg_id_predicted` symbols have been read (temporal update).
486pub(crate) fn segment_pred_hits() -> usize {
487 SEG_PRED_HITS.with(|c| c.get())
488}
489
490/// Resets the segmentation hit counters (gate setup).
491pub(crate) fn reset_segment_hits() {
492 SEG_ID_HITS.with(|c| c.set(0));
493 SEG_IDS_SEEN.with(|c| c.set(0));
494 SEG_PRED_HITS.with(|c| c.set(0));
495}
496
497/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
498/// being decoded, with its `FeatureData` value.
499fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
500 SEG.with(|s| {
501 let s = s.borrow();
502 s.feature_active(segment_id, feature)
503 .then(|| i32::from(s.feature_data[segment_id][feature]))
504 })
505}
506
507/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
508/// `av1_get_qindex`) for the block currently being decoded: the running
509/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
510/// Every dequant call site reads the block's quantizer through here.
511fn block_q_idx() -> i32 {
512 let base = CURRENT_Q_IDX.with(|c| c.get());
513 let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
514 match seg_feature(seg_id, SEG_LVL_ALT_Q) {
515 Some(data) => (base + data).clamp(0, 255),
516 None => base,
517 }
518}
519
520/// The segment id recorded for one mi cell of the current frame's map.
521fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {
522 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
523 if mi_r >= mi_rows || mi_c >= mi_cols {
524 return 0;
525 }
526 SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
527}
528
529/// `set_segment_id`: stamps `id` over every mi cell this block covers.
530fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {
531 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
532 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
533 SEG_IDS.with(|m| {
534 let mut m = m.borrow_mut();
535 for y in 0..y_mis {
536 for x in 0..x_mis {
537 m[(mi_r + y) * mi_cols + mi_c + x] = id;
538 }
539 }
540 });
541 CUR_SEGMENT_ID.with(|c| c.set(id));
542 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
543}
544
545/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
546/// `last_frame_seg_map`): the minimum previous-frame segment id over the
547/// block's own mi footprint. `0` when there is no previous map.
548fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {
549 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
550 PREV_SEG_IDS.with(|m| {
551 let m = m.borrow();
552 if m.is_empty() {
553 return 0;
554 }
555 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
556 let mut id = u8::MAX;
557 for y in 0..y_mis {
558 for x in 0..x_mis {
559 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
560 }
561 }
562 if id == u8::MAX { 0 } else { id }
563 })
564}
565
566/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
567fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
568 if reference == 0 {
569 return diff;
570 }
571 if reference >= max - 1 {
572 return max - diff - 1;
573 }
574 let half = if 2 * reference < max {
575 diff <= 2 * reference
576 } else {
577 diff <= 2 * (max - reference - 1)
578 };
579 if half {
580 return if diff & 1 != 0 {
581 reference + ((diff + 1) >> 1)
582 } else {
583 reference - (diff >> 1)
584 };
585 }
586 if 2 * reference < max { diff } else { max - (diff + 1) }
587}
588
589/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
590/// frame's already-decoded above/left/above-left neighbours.
591fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
592 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
593 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
594 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));
595 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
596 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
597 let ctx = match prev_ul {
598 None => 0,
599 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
600 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
601 Some(_) => 0,
602 };
603 let pred = match (prev_u, prev_l) {
604 (None, l) => l.unwrap_or(0),
605 (Some(u), None) => u,
606 (Some(u), Some(l)) => {
607 if prev_ul == Some(u) {
608 u
609 } else {
610 l
611 }
612 }
613 };
614 (pred, ctx)
615}
616
617/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
618/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
619/// that prediction. Does NOT write the map -- callers do.
620fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {
621 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
622 if skip {
623 return pred as u8;
624 }
625 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
626 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
627 let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));
628 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
629}
630
631/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
632/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
633/// caller decides which by passing `pre_skip`).
634fn intra_segment_id(
635 dec: &mut SymbolDecoder,
636 cdfs: &mut Cdfs,
637 mi_r: usize,
638 mi_c: usize,
639 w_mi: usize,
640 h_mi: usize,
641 skip: bool,
642) {
643 if !SEG.with(|s| s.borrow().enabled) {
644 return;
645 }
646 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
647 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
648}
649
650/// Whether this frame's intra blocks read their `segment_id` before `skip`
651/// (`SegIdPreSkip`); `false` also when segmentation is off.
652fn seg_id_pre_skip() -> bool {
653 SEG.with(|s| {
654 let s = s.borrow();
655 s.enabled && s.seg_id_pre_skip
656 })
657}
658
659/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
660/// Called at both spec positions of an inter frame's block: `pre_skip = true`
661/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
662fn inter_segment_id(
663 dec: &mut SymbolDecoder,
664 cdfs: &mut Cdfs,
665 mi_r: usize,
666 mi_c: usize,
667 w_mi: usize,
668 h_mi: usize,
669 skip: bool,
670 pre_skip: bool,
671) {
672 let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
673 let s = s.borrow();
674 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
675 });
676 if !enabled {
677 return;
678 }
679 if !update_map {
680 // The map is inherited wholesale from the previous frame.
681 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
682 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
683 return;
684 }
685 if pre_skip && !pre_skip_frame {
686 return;
687 }
688 if !pre_skip && skip {
689 // libaom: a skipped block never codes `seg_id_predicted`, and its
690 // segment id is the spatial prediction.
691 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
692 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
693 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
694 return;
695 }
696 let id = if temporal_update {
697 let ctx = seg_pred_ctx(mi_r, mi_c);
698 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
699 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
700 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));
701 if predicted {
702 predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
703 } else {
704 read_segment_id(dec, cdfs, mi_r, mi_c, false)
705 }
706 } else {
707 read_segment_id(dec, cdfs, mi_r, mi_c, false)
708 };
709 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
710}
711
712/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
713fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
714 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
715 // so contribute 0) outside the tile -- the availability check here is
716 // what keeps a previous tile's stamps out of this tile's context.
717 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
718 let above = if mi_r > row0 {
719 ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
720 } else {
721 0
722 };
723 let left = if mi_c > col0 {
724 LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
725 } else {
726 0
727 };
728 usize::from(above + left)
729}
730
731/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
732fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {
733 ABOVE_SEG_PRED.with(|m| {
734 let mut m = m.borrow_mut();
735 for i in 0..w_mi {
736 if let Some(cell) = m.get_mut(mi_c + i) {
737 *cell = value;
738 }
739 }
740 });
741 LEFT_SEG_PRED.with(|m| {
742 let mut m = m.borrow_mut();
743 for i in 0..h_mi {
744 if let Some(cell) = m.get_mut(mi_r + i) {
745 *cell = value;
746 }
747 }
748 });
749}
750
751// How many key-frame luma blocks resolved `smooth_neighbor` (spec
752// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
753// counter, proving a stream actually put a directional block next to a
754// smooth-predicted neighbour rather than every block reading the (previously
755// hardcoded `false`) edge-filter strength bucket unchanged.
756thread_local! {
757 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
758 const { std::cell::Cell::new(0) };
759}
760
761/// Current value of [`SMOOTH_LUMA_HITS`].
762pub(crate) fn smooth_luma_hits() -> usize {
763 SMOOTH_LUMA_HITS.with(|c| c.get())
764}
765
766thread_local! {
767 /// lane-band46 r1: how many split-transform units answered their intra
768 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
769 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
770 /// apply to them (class reach-is-per-transform-unit). Every hit is a
771 /// transform unit whose above-right / below-left reference samples would
772 /// be wrong without that fix.
773 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
774 const { std::cell::Cell::new(0) };
775}
776
777/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
778pub(crate) fn split_tu_reach_fix_hits() -> usize {
779 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
780}
781
782/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
783/// answer differs from the standalone-block answer the call sites used before
784/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
785/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
786/// block's top-left `(px, py)`.
787#[allow(clippy::too_many_arguments)]
788fn tu_reach(
789 bw: usize,
790 bh: usize,
791 col_off: usize,
792 row_off: usize,
793 tx: usize,
794 block: Reach,
795 px: usize,
796 py: usize,
797 width: usize,
798 height: usize,
799) -> Reach {
800 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
801 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height);
802 if fixed != standalone {
803 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));
804 }
805 fixed
806}
807
808// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
809// across every call on the current thread -- lane-chroma r3's own before/after
810// counter, proving a stream actually exercised chroma's smooth/paeth
811// predictor (the previously-refused round-2 gap) rather than every block
812// landing on DC/CFL/directional.
813thread_local! {
814 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
815 const { std::cell::Cell::new(0) };
816}
817
818/// Current value of [`SMOOTH_UV_HITS`].
819pub(crate) fn smooth_uv_hits() -> usize {
820 SMOOTH_UV_HITS.with(|c| c.get())
821}
822
823// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
824// full superblock walk over, across every call on the current thread --
825// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
826// multi-tile stream must prove more than one tile actually fired, not just
827// that the stream carried tile_info.cols > 1.
828thread_local! {
829 static TILE_HITS: std::cell::Cell<usize> =
830 const { std::cell::Cell::new(0) };
831}
832/// Current value of [`TILE_HITS`].
833pub(crate) fn tile_hits() -> usize {
834 TILE_HITS.with(|c| c.get())
835}
836
837// How many 4-pixel deblocking edge groups [`edge_params`] has actually
838// selected for filtering, across every call on the current thread -- the same
839// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
840// exercised `apply_deblock` rather than every edge landing on level 0.
841thread_local! {
842 static DEBLOCK_HITS: std::cell::Cell<usize> =
843 const { std::cell::Cell::new(0) };
844}
845/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
846/// mirroring stream.rs's `pictures_decoded` so the two dumps index
847/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
848static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
849 std::sync::atomic::AtomicUsize::new(0);
850
851/// Current value of [`DEBLOCK_HITS`].
852pub(crate) fn deblock_hits() -> usize {
853 DEBLOCK_HITS.with(|c| c.get())
854}
855
856// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
857// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
858// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
859// stream built with `--enable-onesided-comp=1` really exercised the
860// `uni_comp_ref` alphabet rather than only bidirectional pairs.
861thread_local! {
862 static UNI_COMP_HITS: std::cell::Cell<usize> =
863 const { std::cell::Cell::new(0) };
864}
865
866/// Current value of [`UNI_COMP_HITS`].
867pub(crate) fn uni_comp_hits() -> usize {
868 UNI_COMP_HITS.with(|c| c.get())
869}
870
871// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
872// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
873// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
874// blend and not only the wedge arm.
875thread_local! {
876 static DIFFWTD_HITS: std::cell::Cell<usize> =
877 const { std::cell::Cell::new(0) };
878}
879
880/// Current value of [`DIFFWTD_HITS`].
881pub(crate) fn diffwtd_hits() -> usize {
882 DIFFWTD_HITS.with(|c| c.get())
883}
884
885// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
886// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
887// this decoder's square inter path reaches), so no `compound_type` symbol is
888// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
889// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
890thread_local! {
891 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
892 const { std::cell::Cell::new(0) };
893}
894
895/// Current value of [`DIFFWTD_INFERRED_HITS`].
896pub(crate) fn diffwtd_inferred_hits() -> usize {
897 DIFFWTD_INFERRED_HITS.with(|c| c.get())
898}
899
900// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
901// with `show_frame == 0`, output later by a `show_existing_frame` header
902// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
903// `stream::decode_stream`, which is where the frame header is consumed; the
904// gate's proof that the on-value really reached the bitstream rather than
905// being dropped by the rate control.
906thread_local! {
907 static FWD_KF_HITS: std::cell::Cell<usize> =
908 const { std::cell::Cell::new(0) };
909}
910
911/// Current value of [`FWD_KF_HITS`].
912pub(crate) fn fwd_kf_hits() -> usize {
913 FWD_KF_HITS.with(|c| c.get())
914}
915
916/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
917pub(crate) fn note_fwd_kf() {
918 FWD_KF_HITS.with(|c| c.set(c.get() + 1));
919}
920
921// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
922// the block's own side, across every call on the current thread -- the same
923// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
924// actually exercised a *split* transform under `TxMode::Select` rather than
925// every block coincidentally resolving `depth=0` (indistinguishable from
926// `TxMode::Largest` pixel-wise).
927thread_local! {
928 static TX_DEPTH_HITS: std::cell::Cell<usize> =
929 const { std::cell::Cell::new(0) };
930}
931
932// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
933// transform smaller than their own side (`tx_depth != 0`) while coding a
934// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
935// only exercises with aomenc's tx-size search left ON (its default), which
936// every older recipe in this file pins off. Counted at the block, so a stream
937// where RD happened to give every split-transform block a DC chroma mode
938// reads as zero rather than silently passing for free.
939thread_local! {
940 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
941 const { std::cell::Cell::new(0) };
942}
943
944/// Current value of [`SQ_CHROMA_TX_HITS`].
945pub(crate) fn sq_chroma_tx_hits() -> usize {
946 SQ_CHROMA_TX_HITS.with(|c| c.get())
947}
948
949/// Current value of [`TX_DEPTH_HITS`].
950pub(crate) fn tx_depth_hits() -> usize {
951 TX_DEPTH_HITS.with(|c| c.get())
952}
953
954// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
955// read, and how many of those actually took the split, on the current thread
956// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
957// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
958// coincidentally coding one whole-block transform.
959thread_local! {
960 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
961 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
962 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
963 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
964 // `decode_inter_block` already carries forty parameters and both are
965 // frame-constant.
966 static TX_SELECT_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
967 static REDUCED_TX_SET_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
968 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
969 // frame-constant like the two above and stashed the same way -- an intra
970 // block inside an inter frame reads `use_filter_intra` under it.
971 static ENABLE_FILTER_INTRA_INTER: std::cell::Cell<bool> =
972 const { std::cell::Cell::new(false) };
973}
974
975/// Current value of [`TXFM_SPLIT_READS`].
976pub(crate) fn txfm_split_reads() -> usize {
977 TXFM_SPLIT_READS.with(|c| c.get())
978}
979
980/// Current value of [`TXFM_SPLIT_HITS`].
981pub(crate) fn txfm_split_hits() -> usize {
982 TXFM_SPLIT_HITS.with(|c| c.get())
983}
984
985/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
986/// [`ENABLE_FILTER_INTRA_INTER`].
987pub(crate) fn set_inter_tx_mode(
988 tx_select: bool,
989 reduced_tx_set: bool,
990 enable_filter_intra: bool,
991) {
992 TX_SELECT_INTER.with(|c| c.set(tx_select));
993 REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));
994 ENABLE_FILTER_INTRA_INTER.with(|c| c.set(enable_filter_intra));
995}
996
997// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
998// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
999// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1000// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1001// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1002// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1003// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1004// path above).
1005thread_local! {
1006 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1007 const { std::cell::Cell::new(0) };
1008}
1009
1010/// Current value of [`VERT_B_INTRA_HITS`].
1011pub(crate) fn vert_b_intra_hits() -> usize {
1012 VERT_B_INTRA_HITS.with(|c| c.get())
1013}
1014
1015// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1016// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1017// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1018// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1019// every arm separately so a run where aomenc's RD only picked one cannot
1020// pass as proof of four.
1021thread_local! {
1022 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1023}
1024
1025/// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1026thread_local! {
1027 /// 4x4 transform units decoded inside an 8x8 square of a
1028 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1029 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1030 /// a real `--enable-tx-size-search=1` stream reaches it.
1031 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1032}
1033
1034pub(crate) fn vert_ab_tx4_hits() -> usize {
1035 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1036}
1037
1038pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1039 AB16_HITS.with(std::cell::Cell::get)
1040}
1041
1042fn bump_ab16(arm: usize) {
1043 AB16_HITS.with(|c| {
1044 let mut v = c.get();
1045 v[arm] += 1;
1046 c.set(v);
1047 });
1048}
1049
1050// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1051// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1052// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1053// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1054// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1055// superblock's z-order recursion, not raster mi position).
1056thread_local! {
1057 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1058 const { std::cell::Cell::new(0) };
1059}
1060
1061/// Current value of [`HORZ_VERT_INTRA_HITS`].
1062pub(crate) fn horz_vert_intra_hits() -> usize {
1063 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1064}
1065
1066// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1067// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1068// the case every rect path here refused by name before, and the first
1069// refusal the user's ReelB extract (600s in) stops at.
1070thread_local! {
1071 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1072 const { std::cell::Cell::new(0) };
1073}
1074
1075/// Current value of [`RECT_SPLIT_TX_HITS`].
1076pub(crate) fn rect_split_tx_hits() -> usize {
1077 RECT_SPLIT_TX_HITS.with(|c| c.get())
1078}
1079
1080// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1081// side 64) AND split past the first depth, i.e. tiled more than one unit in
1082// each axis -- the only shape with a transform unit that has neighbours on
1083// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1084// no gate fired before lane-rectsplit r2 (the shared counter above also
1085// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1086thread_local! {
1087 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1088 const { std::cell::Cell::new(0) };
1089}
1090
1091/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1092pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1093 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1094}
1095
1096// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1097// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1098// chroma half takes that had no coefficient tables before (index order:
1099// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1100// proves the pair it happens to hit cannot catch a transposed scan/context
1101// table (class scan-weights-cross-axis).
1102thread_local! {
1103 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1104 const { std::cell::Cell::new([0; 4]) };
1105}
1106
1107/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1108pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1109 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1110}
1111
1112// How many HORZ/VERT intra strips actually predicted with filter intra
1113// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1114// ("this decoder predicts square-only") until `predict_filter_intra` took
1115// `bw`x`bh`.
1116thread_local! {
1117 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1118 const { std::cell::Cell::new(0) };
1119}
1120
1121/// Current value of [`FILTER_INTRA_RECT_HITS`].
1122pub(crate) fn filter_intra_rect_hits() -> usize {
1123 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1124}
1125
1126// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1127// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1128// was never read at all before that round, so a gate needs to prove the flag
1129// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1130// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1131// carry different probabilities (18101 vs 20229), so a transposed pair is
1132// only caught by a gate that sees the flag fire on BOTH shapes (class
1133// scan-weights-cross-axis).
1134thread_local! {
1135 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1136 const { std::cell::Cell::new(0) };
1137 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1138 const { std::cell::Cell::new(0) };
1139}
1140
1141/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1142pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1143 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1144}
1145
1146/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1147pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1148 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1149}
1150
1151// How many rectangular transform units actually coded coefficients through
1152// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1153// exercised the rect coefficient reader at all rather than passing on
1154// all-skip blocks.
1155thread_local! {
1156 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1157 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1158}
1159
1160/// Current value of [`RECT_COEFF_TU_HITS`].
1161pub(crate) fn rect_coeff_tu_hits() -> usize {
1162 RECT_COEFF_TU_HITS.with(|c| c.get())
1163}
1164
1165/// Rectangular transform units whose resolved `tx_type` is a 1D class
1166/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1167/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1168/// for the square reader's own 1D types.
1169pub(crate) fn rect_class1_hits() -> usize {
1170 RECT_CLASS1_HITS.with(|c| c.get())
1171}
1172
1173// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1174// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1175// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1176// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1177// prove nothing about the new shapes.
1178thread_local! {
1179 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1180 const { std::cell::Cell::new(0) };
1181}
1182
1183/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1184pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1185 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1186}
1187
1188// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1189// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1190// counter would be satisfied by a 16x8 strip and prove nothing here.
1191thread_local! {
1192 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1193 const { std::cell::Cell::new(0) };
1194}
1195
1196/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1197pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1198 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1199}
1200
1201// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1202// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1203// call on the current thread -- the same before/after counter pattern as
1204// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1205// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1206// landing on `DCT_DCT`.
1207thread_local! {
1208 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1209 const { std::cell::Cell::new(0) };
1210}
1211
1212// How many `uv_mode` reads resolved to a directional chroma mode (neither
1213// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1214// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1215// actually exercised chroma's own directional predictor.
1216thread_local! {
1217 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1218 const { std::cell::Cell::new(0) };
1219}
1220
1221/// Current value of [`DIRECTIONAL_UV_HITS`].
1222pub(crate) fn directional_uv_hits() -> usize {
1223 DIRECTIONAL_UV_HITS.with(|c| c.get())
1224}
1225
1226// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1227// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1228// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1229// proving a stream actually exercised a nonzero angle delta.
1230thread_local! {
1231 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1232 const { std::cell::Cell::new(0) };
1233}
1234
1235// How many [`read_single_ref`] reads resolved to a reference other than
1236// `LAST_FRAME`, across every call on the current thread -- the same before/after
1237// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1238// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1239// only other supported one so far) rather than every block coincidentally
1240// resolving `LAST_FRAME`.
1241thread_local! {
1242 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1243 const { std::cell::Cell::new(0) };
1244}
1245
1246/// Current value of [`NON_LAST_REF_HITS`].
1247pub(crate) fn non_last_ref_hits() -> usize {
1248 NON_LAST_REF_HITS.with(|c| c.get())
1249}
1250
1251// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1252// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1253// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1254// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1255// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1256// `GOLDEN_FRAME` draw it did not ask for.
1257thread_local! {
1258 static LAST2_HITS: std::cell::Cell<usize> =
1259 const { std::cell::Cell::new(0) };
1260}
1261thread_local! {
1262 static LAST3_HITS: std::cell::Cell<usize> =
1263 const { std::cell::Cell::new(0) };
1264}
1265thread_local! {
1266 static GOLDEN_HITS: std::cell::Cell<usize> =
1267 const { std::cell::Cell::new(0) };
1268}
1269thread_local! {
1270 static BWDREF_HITS: std::cell::Cell<usize> =
1271 const { std::cell::Cell::new(0) };
1272}
1273thread_local! {
1274 static ALTREF2_HITS: std::cell::Cell<usize> =
1275 const { std::cell::Cell::new(0) };
1276}
1277thread_local! {
1278 static ALTREF_HITS: std::cell::Cell<usize> =
1279 const { std::cell::Cell::new(0) };
1280}
1281
1282// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1283// -- proves a `reference_select` stream actually reached a block that picked
1284// compound, not just that the header bit was set. Every such block is
1285// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1286// so this only ever counts attempted reads, never a completed decode.
1287thread_local! {
1288 static COMP_MODE_HITS: std::cell::Cell<usize> =
1289 const { std::cell::Cell::new(0) };
1290}
1291
1292/// Current value of [`COMP_MODE_HITS`].
1293pub(crate) fn comp_mode_hits() -> usize {
1294 COMP_MODE_HITS.with(|c| c.get())
1295}
1296
1297// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1298// use for, across every call on the current thread -- the same before/after
1299// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1300// exercised palette reconstruction rather than only reading and refusing the
1301// `palette_y_mode` symbol.
1302thread_local! {
1303 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1304}
1305
1306/// Current value of [`PALETTE_HITS`].
1307pub(crate) fn palette_hits() -> usize {
1308 PALETTE_HITS.with(|c| c.get())
1309}
1310
1311// lane-tiles r12: of those, how many sat at their own TILE's left column --
1312// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1313// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1314// palette gate that never hits one proves nothing about the tile guard.
1315thread_local! {
1316 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1317}
1318
1319/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1320pub(crate) fn palette_tile_left_hits() -> usize {
1321 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1322}
1323
1324// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1325// palette use -- proves a stream actually reconstructed UV palette pixels,
1326// not just read and refused the `palette_uv_mode` symbol.
1327thread_local! {
1328 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1329}
1330
1331/// Current value of [`PALETTE_UV_HITS`].
1332pub(crate) fn palette_uv_hits() -> usize {
1333 PALETTE_UV_HITS.with(|c| c.get())
1334}
1335
1336// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1337// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1338// (not just the square path's) actually fired.
1339thread_local! {
1340 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1341}
1342
1343/// Current value of [`PALETTE_RECT_HITS`].
1344pub(crate) fn palette_rect_hits() -> usize {
1345 PALETTE_RECT_HITS.with(|c| c.get())
1346}
1347
1348// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1349// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1350// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1351// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1352// RD, almost always refused-on-use because the block doesn't end up USING a
1353// palette -- see r5's report). This is the site the removed refusal
1354// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1355// fired here whether or not the block picked a palette, so this is the
1356// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1357// never observes.
1358thread_local! {
1359 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1360}
1361
1362/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1363pub(crate) fn rect_screen_content_hits() -> usize {
1364 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1365}
1366
1367// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1368// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1369// windowing actually ran, not just that the whole-block path stayed exact.
1370// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1371// first actually incremented in r7, when the refusal it guarded was lifted.
1372thread_local! {
1373 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1374}
1375
1376/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1377pub(crate) fn palette_split_tx_hits() -> usize {
1378 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1379}
1380
1381// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
1382// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
1383// the gate's proof that the lifted path actually ran, per size.
1384thread_local! {
1385 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
1386 const { std::cell::Cell::new([0; 4]) };
1387}
1388
1389/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
1390pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
1391 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
1392}
1393
1394thread_local! {
1395 /// A just-decoded palette-Y block's own predicted pixels
1396 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1397 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1398 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1399 /// per-block override through `read_plane`'s two dozen call sites is the
1400 /// alternative this avoids). Always empty again once that call consumes
1401 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
1402 /// sees stale state.
1403 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1404 const { std::cell::RefCell::new(None) };
1405}
1406
1407
1408/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
1409/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
1410/// site whose reconstruct never runs would be picked up by the NEXT block's
1411/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1412/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1413#[track_caller]
1414fn set_palette_pred(buf: Vec<u16>) {
1415 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1416 let stale = PALETTE_PRED.with(|c| c.borrow().is_some());
1417 eprintln!(
1418 "PALSET len={} stale={stale} at {}",
1419 buf.len(),
1420 std::panic::Location::caller()
1421 );
1422 }
1423 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
1424}
1425
1426#[track_caller]
1427fn take_palette_pred() -> Option<Vec<u16>> {
1428 let got = PALETTE_PRED.with(|c| c.borrow_mut().take());
1429 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1430 eprintln!(
1431 "PALTAKE len={:?} at {}",
1432 got.as_ref().map(Vec::len),
1433 std::panic::Location::caller()
1434 );
1435 }
1436 got
1437}
1438
1439thread_local! {
1440 /// The current frame's `mi` grid, kept only while a frame header set
1441 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
1442 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
1443 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
1444 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
1445 /// does not allow intrabc (so nothing is paid for it).
1446 ///
1447 /// corner-cut: only [`decode_block`] (the square path) records into it,
1448 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
1449 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
1450 /// be wrong there; upgrade = record from the rect/leaf paths too.
1451 static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1452 const { std::cell::RefCell::new(None) };
1453 /// The block vector [`read_intra_mode`] just decoded, handed to
1454 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1455 /// which the alternative -- a tenth tuple member through every caller --
1456 /// already avoids). Always `.take()`n by the block that reads it.
1457 static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1458 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1459 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1460}
1461
1462/// Current value of [`INTRABC_HITS`].
1463pub(crate) fn intrabc_hits() -> usize {
1464 INTRABC_HITS.with(|c| c.get())
1465}
1466
1467/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
1468pub(crate) fn reset_intrabc_hits() {
1469 INTRABC_HITS.with(|c| c.set(0));
1470}
1471
1472/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1473/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1474/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1475/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1476fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1477 INTRABC_MI_GRID.with(|g| {
1478 let mut g = g.borrow_mut();
1479 let Some((grid, _, _)) = g.as_mut() else {
1480 return;
1481 };
1482 let info = crate::mvstack::MiInfo {
1483 is_inter: dv.is_some(),
1484 ref_frame: 0,
1485 ref_frame1: None,
1486 mv: dv.unwrap_or((0, 0)),
1487 mv1: None,
1488 is_new_mv: dv.is_some(),
1489 is_global_mv0: false,
1490 is_global_mv1: false,
1491 size: n4,
1492 size_h: n4,
1493 };
1494 for r in mi_r..mi_r + n4 {
1495 for c in mi_c..mi_c + n4 {
1496 grid.set(r, c, info);
1497 }
1498 }
1499 });
1500}
1501
1502// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
1503// proves a real `skip_mode_present` stream actually reached a block that
1504// picked it, not just that the frame header bit was set.
1505thread_local! {
1506 static SKIP_MODE_HITS: std::cell::Cell<usize> =
1507 const { std::cell::Cell::new(0) };
1508}
1509
1510/// Current value of [`SKIP_MODE_HITS`].
1511pub(crate) fn skip_mode_hits() -> usize {
1512 SKIP_MODE_HITS.with(|c| c.get())
1513}
1514
1515// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
1516// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
1517// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
1518// reached [`obmc_blend`], not just the header bit.
1519thread_local! {
1520 static OBMC_HITS: std::cell::Cell<usize> =
1521 const { std::cell::Cell::new(0) };
1522}
1523
1524// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
1525// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
1526// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
1527// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
1528// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
1529// decoder used to read with the wrong alphabet, so a gate that asserts this
1530// counter advanced proves the fixed path fired (class
1531// `gate-blind-to-feature`).
1532thread_local! {
1533 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1534}
1535
1536/// Current value of [`FIMV_ALPHABET_HITS`].
1537pub fn fimv_alphabet_hits() -> usize {
1538 FIMV_ALPHABET_HITS.with(|c| c.get())
1539}
1540
1541// lane-fimv r1: how many frame headers this decoder has decoded with
1542/// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
1543// prove the encoder really produced the header state under test rather than
1544// assume it.
1545thread_local! {
1546 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1547}
1548
1549/// Current value of [`FIMV_FRAME_HITS`].
1550pub fn fimv_frame_hits() -> usize {
1551 FIMV_FRAME_HITS.with(|c| c.get())
1552}
1553
1554/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
1555/// `force_integer_mv` bit is set.
1556pub fn note_force_integer_mv_frame() {
1557 FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1));
1558}
1559
1560/// Current value of [`OBMC_HITS`].
1561pub(crate) fn obmc_hits() -> usize {
1562 OBMC_HITS.with(|c| c.get())
1563}
1564
1565// lane-scaledref r1: per-case firing counts for the scaled-reference gate
1566// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
1567// reference would pass just as well and prove nothing, so the gate
1568// hard-asserts each combination this round lifts actually occurred:
1569// a compound block with a scaled tap, a warp block whose warp libaom
1570// suppresses because the reference is scaled, an OBMC block, an interintra
1571// block, and an 8x8 leaf.
1572thread_local! {
1573 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1574 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1575 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1576 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1577 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1578 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1579 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1580}
1581
1582/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
1583/// scaled and one unscaled tap.
1584pub(crate) fn mixed_scale_compound_hits() -> usize {
1585 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
1586}
1587
1588/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
1589/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
1590/// instead because their reference is scaled (libaom `motion_mode_allowed`,
1591/// `blockd.h:1484`).
1592pub(crate) fn scaled_warp_suppressed_hits() -> usize {
1593 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
1594}
1595
1596/// Current value of [`SCALED_COMPOUND_HITS`].
1597pub(crate) fn scaled_compound_hits() -> usize {
1598 SCALED_COMPOUND_HITS.with(|c| c.get())
1599}
1600
1601/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
1602pub(crate) fn scaled_warp_fallback_hits() -> usize {
1603 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
1604}
1605
1606/// Current value of [`SCALED_OBMC_HITS`].
1607pub(crate) fn scaled_obmc_hits() -> usize {
1608 SCALED_OBMC_HITS.with(|c| c.get())
1609}
1610
1611/// Current value of [`SCALED_INTERINTRA_HITS`].
1612pub(crate) fn scaled_interintra_hits() -> usize {
1613 SCALED_INTERINTRA_HITS.with(|c| c.get())
1614}
1615
1616/// Current value of [`SCALED_BLOCK8_HITS`].
1617pub(crate) fn scaled_block8_hits() -> usize {
1618 SCALED_BLOCK8_HITS.with(|c| c.get())
1619}
1620
1621// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
1622// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
1623// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
1624// 8x8-leaf OBMC block apart from a 16x16+ one.
1625thread_local! {
1626 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1627}
1628
1629// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
1630// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
1631// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
1632// -- the gate's proof that a fixture really exercises the alphabet this
1633// round changed, even though the block itself still refuses (warp
1634// estimation/filter not ported).
1635thread_local! {
1636 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
1637 const { std::cell::Cell::new(0) };
1638}
1639
1640/// Current value of [`WARP_SELECTED_HITS`].
1641pub(crate) fn warp_selected_hits() -> usize {
1642 WARP_SELECTED_HITS.with(|c| c.get())
1643}
1644
1645// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
1646// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
1647// into the compound intermediate) rather than translationally -- the
1648// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
1649// really reached [`crate::warp::warp_affine_compound`].
1650thread_local! {
1651 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
1652 const { std::cell::Cell::new(0) };
1653}
1654
1655/// Current value of [`COMPOUND_WARP_HITS`].
1656pub(crate) fn compound_warp_hits() -> usize {
1657 COMPOUND_WARP_HITS.with(|c| c.get())
1658}
1659
1660// lane-gmaffine r1: how many blocks built their prediction from a
1661// SIX-parameter (`AFFINE`) global-motion model through
1662// `crate::warp::global_warp_params` -- the gate's proof that a stream really
1663// carried an AFFINE `global_motion_params` AND that a block was predicted
1664// with it, not merely that the header parsed one.
1665thread_local! {
1666 static AFFINE_GM_HITS: std::cell::Cell<usize> =
1667 const { std::cell::Cell::new(0) };
1668}
1669
1670/// Current value of [`AFFINE_GM_HITS`].
1671pub(crate) fn affine_gm_hits() -> usize {
1672 AFFINE_GM_HITS.with(|c| c.get())
1673}
1674
1675// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
1676// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
1677// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
1678// only once `find_projection` returned a usable model, unlike
1679// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
1680// proof that the leaf path itself fired, not the 16x16+ one.
1681thread_local! {
1682 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1683 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1684}
1685
1686/// Current value of [`GLOBALMV_HITS_8`].
1687pub(crate) fn globalmv_hits_8() -> usize {
1688 GLOBALMV_HITS_8.with(|c| c.get())
1689}
1690
1691/// Current value of [`WARP_HITS_8`].
1692pub(crate) fn warp_hits_8() -> usize {
1693 WARP_HITS_8.with(|c| c.get())
1694}
1695
1696// How many blocks decoded `interintra == 1` with the non-wedge blended
1697// prediction applied (lane-interintra r1) -- the gate's proof that a
1698// stream actually exercised interintra.
1699thread_local! {
1700 static INTERINTRA_HITS: std::cell::Cell<usize> =
1701 const { std::cell::Cell::new(0) };
1702}
1703
1704/// Current value of [`INTERINTRA_HITS`].
1705pub(crate) fn interintra_hits() -> usize {
1706 INTERINTRA_HITS.with(|c| c.get())
1707}
1708
1709// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
1710// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
1711// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
1712// gate fixture actually exercises this alphabet, even though the block
1713// still refuses (the mask blend itself is unported).
1714thread_local! {
1715 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
1716 const { std::cell::Cell::new(0) };
1717}
1718
1719/// Current value of [`MASKED_COMPOUND_HITS`].
1720pub(crate) fn masked_compound_hits() -> usize {
1721 MASKED_COMPOUND_HITS.with(|c| c.get())
1722}
1723
1724// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
1725// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
1726// actually exercised the wedge blend, not just the DIFFWTD half of
1727// `MASKED_COMPOUND_HITS`.
1728thread_local! {
1729 static WEDGE_HITS: std::cell::Cell<usize> =
1730 const { std::cell::Cell::new(0) };
1731}
1732
1733/// Current value of [`WEDGE_HITS`].
1734pub(crate) fn wedge_hits() -> usize {
1735 WEDGE_HITS.with(|c| c.get())
1736}
1737
1738// How many blocks decoded a real wedge-INTERINTRA block
1739// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
1740// a gate fixture exercised the wedge blend (fixed sign 0), not just the
1741// smooth arm counted by `INTERINTRA_HITS`.
1742thread_local! {
1743 static WII_HITS: std::cell::Cell<usize> =
1744 const { std::cell::Cell::new(0) };
1745}
1746
1747/// Current value of [`WII_HITS`].
1748pub(crate) fn wii_hits() -> usize {
1749 WII_HITS.with(|c| c.get())
1750}
1751
1752/// Current value of [`OBMC_HITS_8`].
1753pub(crate) fn obmc_hits_8() -> usize {
1754 OBMC_HITS_8.with(|c| c.get())
1755}
1756
1757// lane-rectgate r1: how many 32x32 quadrants actually decoded a
1758// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
1759// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
1760// `VERT_B` all still fall into the generic "a partition type this encoder
1761// never writes" refusal below) -- the gate's proof that a free-partition
1762// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
1763// coincidentally never selecting one.
1764thread_local! {
1765 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
1766 const { std::cell::Cell::new(0) };
1767}
1768
1769/// Current value of [`EXTENDED_PARTITION_HITS`].
1770pub(crate) fn extended_partition_hits() -> usize {
1771 EXTENDED_PARTITION_HITS.with(|c| c.get())
1772}
1773
1774// lane-partitions r1: how many 32x32 quadrants decoded a real
1775// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
1776// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
1777// gate's proof this round's arms actually fired.
1778thread_local! {
1779 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
1780 const { std::cell::Cell::new(0) };
1781}
1782
1783/// Current value of [`RECT_PARTITION_HITS`].
1784pub(crate) fn rect_partition_hits() -> usize {
1785 RECT_PARTITION_HITS.with(|c| c.get())
1786}
1787
1788// lane-inter8 r1: how many superblocks an inter tile coded as a single
1789// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
1790// static content, previously a named refusal).
1791thread_local! {
1792 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
1793 const { std::cell::Cell::new(0) };
1794}
1795
1796/// Current value of [`INTER_SB_NONE_HITS`].
1797pub(crate) fn inter_sb_none_hits() -> usize {
1798 INTER_SB_NONE_HITS.with(|c| c.get())
1799}
1800
1801// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
1802// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
1803// path has always run that loop, so only this counter proves the newly-lifted
1804// alphabet value fired.
1805thread_local! {
1806 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
1807 const { std::cell::Cell::new(0) };
1808}
1809
1810/// Current value of [`INTER_SUB16_SPLIT_HITS`].
1811pub(crate) fn inter_sub16_split_hits() -> usize {
1812 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
1813}
1814
1815// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
1816// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
1817// rect coefficient reader itself fired, not just the strip-level partition
1818// symbol [`RECT_PARTITION_HITS`] already counts.
1819thread_local! {
1820 static RECT_COEFF_HITS: std::cell::Cell<usize> =
1821 const { std::cell::Cell::new(0) };
1822}
1823
1824/// Current value of [`RECT_COEFF_HITS`].
1825pub(crate) fn rect_coeff_hits() -> usize {
1826 RECT_COEFF_HITS.with(|c| c.get())
1827}
1828
1829// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
1830// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
1831// charter's real-aomenc gate hard-asserts.
1832thread_local! {
1833 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
1834 const { std::cell::Cell::new(0) };
1835}
1836
1837/// Current value of [`RECT_LEAF_COEFF_HITS`].
1838pub(crate) fn rect_leaf_coeff_hits() -> usize {
1839 RECT_LEAF_COEFF_HITS.with(|c| c.get())
1840}
1841
1842// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
1843// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
1844// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
1845// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
1846thread_local! {
1847 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
1848 const { std::cell::Cell::new(0) };
1849}
1850
1851/// Current value of [`MODE_MI_OVERRIDE_HITS`].
1852pub(crate) fn mode_mi_override_hits() -> usize {
1853 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
1854}
1855
1856// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
1857// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
1858// mode from the previous tile, where libaom's `up_available`/`left_available`
1859// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
1860// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
1861// per superblock row in `start_row`, so the luma fallback cannot leak the way
1862// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
1863// the invariant that makes the coarse fallback safe.
1864thread_local! {
1865 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
1866 const { std::cell::Cell::new(0) };
1867}
1868
1869/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
1870pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
1871 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
1872}
1873
1874// lane-cfl r1: how many times a chroma intra-edge filter-type read
1875// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
1876// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
1877// r1 defect would have filtered a chroma edge with the wrong strength.
1878thread_local! {
1879 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
1880 const { std::cell::Cell::new(0) };
1881}
1882
1883/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
1884pub(crate) fn uv_mode_mi_override_hits() -> usize {
1885 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
1886}
1887
1888// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
1889// suppressed at a TILE edge that is not a frame edge -- the above/left
1890// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
1891// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
1892// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
1893// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
1894// above would decide this tile's chroma edge filter strength.
1895thread_local! {
1896 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
1897 const { std::cell::Cell::new(0) };
1898}
1899
1900/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
1901pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
1902 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
1903}
1904
1905// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
1906// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
1907// shapes the r1 chroma defect showed up on.
1908thread_local! {
1909 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1910 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1911}
1912
1913/// Current value of [`CFL_BLOCK_HITS`].
1914pub(crate) fn cfl_block_hits() -> usize {
1915 CFL_BLOCK_HITS.with(|c| c.get())
1916}
1917
1918/// Current value of [`UV_ANGLE_DELTA_HITS`].
1919pub(crate) fn uv_angle_delta_hits() -> usize {
1920 UV_ANGLE_DELTA_HITS.with(|c| c.get())
1921}
1922
1923// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
1924// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
1925// gate's proof this round's arms actually reached a real block, not just
1926// that `partition_w64` read one of those two symbol values.
1927thread_local! {
1928 static SB_RECT_HITS: std::cell::Cell<usize> =
1929 const { std::cell::Cell::new(0) };
1930}
1931
1932/// Current value of [`SB_RECT_HITS`].
1933pub(crate) fn sb_rect_hits() -> usize {
1934 SB_RECT_HITS.with(|c| c.get())
1935}
1936
1937// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
1938// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
1939// strip) fired. Real aomenc picks these at 64 even with
1940// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
1941// the counter the gate hard-asserts.
1942thread_local! {
1943 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
1944 const { std::cell::Cell::new([0; 4]) };
1945}
1946
1947/// Current value of [`SB_AB_HITS`], summed over the four arms.
1948pub(crate) fn sb_ab_hits() -> usize {
1949 SB_AB_HITS.with(|c| c.get().iter().sum())
1950}
1951
1952/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
1953/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
1954/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
1955/// proof of all four.
1956pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
1957 SB_AB_HITS.with(std::cell::Cell::get)
1958}
1959
1960// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
1961// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
1962// strips). Two counters, not one, because a gate that only proved "some 1:4
1963// strip fired" would pass on a stream that never coded the other axis, and
1964// every scan/context table this round added comes in a transposed pair.
1965thread_local! {
1966 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1967 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1968}
1969
1970/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
1971pub(crate) fn sb_rect4_horz_hits() -> usize {
1972 SB_RECT4_HORZ_HITS.with(|c| c.get())
1973}
1974
1975/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
1976pub(crate) fn sb_rect4_vert_hits() -> usize {
1977 SB_RECT4_VERT_HITS.with(|c| c.get())
1978}
1979
1980// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
1981// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
1982// strips), the arms the ReelB mid-film extract stops at.
1983thread_local! {
1984 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1985 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1986}
1987
1988/// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
1989/// a gate that only counted strips would pass on an all-skip stream, which
1990/// exercises none of the new scan/context tables.
1991thread_local! {
1992 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1993}
1994
1995// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
1996// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
1997// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
1998// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
1999// counts the same for a 16x8/8x16 strip below 16x16.
2000thread_local! {
2001 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2002 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2003 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2004}
2005
2006/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
2007pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
2008 (
2009 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
2010 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
2011 )
2012}
2013
2014/// Current value of `SUB16_SPLIT_HITS`.
2015pub(crate) fn sub16_split_hits() -> usize {
2016 SUB16_SPLIT_HITS.with(|c| c.get())
2017}
2018
2019/// Current value of `RECT4_COEFF_HITS`.
2020pub(crate) fn rect4_coeff_hits() -> usize {
2021 RECT4_COEFF_HITS.with(|c| c.get())
2022}
2023
2024/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
2025pub(crate) fn rect4_32_horz_hits() -> usize {
2026 RECT4_32_HORZ_HITS.with(|c| c.get())
2027}
2028
2029/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
2030pub(crate) fn rect4_32_vert_hits() -> usize {
2031 RECT4_32_VERT_HITS.with(|c| c.get())
2032}
2033
2034// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
2035// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
2036// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
2037// just inert-compiled. Zero forever on a passing gate means that gate's
2038// stream never carries `delta_q_present=1` through a rect64 block.
2039thread_local! {
2040 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
2041 const { std::cell::Cell::new(0) };
2042}
2043
2044/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
2045pub(crate) fn rect64_qidx_drift_hits() -> usize {
2046 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
2047}
2048
2049// lane-partab r1: how many 32x32 quadrants decoded an AB partition
2050// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
2051// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
2052// free-partition gate's proof this round's arms actually fired.
2053thread_local! {
2054 static PARTAB_HITS: std::cell::Cell<usize> =
2055 const { std::cell::Cell::new(0) };
2056}
2057
2058/// Current value of [`PARTAB_HITS`].
2059pub(crate) fn partab_hits() -> usize {
2060 PARTAB_HITS.with(|c| c.get())
2061}
2062
2063// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
2064// one counter per arm rather than one shared total -- the gate hard-asserts
2065// each of these individually nonzero so a recipe that only ever fires
2066// HORZ_A can't silently stand in for the whole set.
2067thread_local! {
2068 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
2069 const { std::cell::Cell::new(0) };
2070 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
2071 const { std::cell::Cell::new(0) };
2072 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
2073 const { std::cell::Cell::new(0) };
2074 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
2075 const { std::cell::Cell::new(0) };
2076}
2077
2078/// Current value of [`INTRA_HORZ_A_HITS`].
2079pub(crate) fn intra_horz_a_hits() -> usize {
2080 INTRA_HORZ_A_HITS.with(|c| c.get())
2081}
2082/// Current value of [`INTRA_HORZ_B_HITS`].
2083pub(crate) fn intra_horz_b_hits() -> usize {
2084 INTRA_HORZ_B_HITS.with(|c| c.get())
2085}
2086/// Current value of [`INTRA_VERT_A_HITS`].
2087pub(crate) fn intra_vert_a_hits() -> usize {
2088 INTRA_VERT_A_HITS.with(|c| c.get())
2089}
2090/// Current value of [`INTRA_VERT_B_HITS`].
2091pub(crate) fn intra_vert_b_hits() -> usize {
2092 INTRA_VERT_B_HITS.with(|c| c.get())
2093}
2094
2095// How many [`read_inter_compound_mode`] reads actually happened
2096// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
2097// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
2098// mvstack build), not just that `comp_mode` fired. Still refused right
2099// after (no MV assignment or MC wired), so this only counts attempted
2100// reads.
2101thread_local! {
2102 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
2103 const { std::cell::Cell::new(0) };
2104}
2105
2106/// Current value of [`COMPOUND_MODE_HITS`].
2107pub(crate) fn compound_mode_hits() -> usize {
2108 COMPOUND_MODE_HITS.with(|c| c.get())
2109}
2110
2111/// How many query blocks folded in at least one temporal MV candidate
2112/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
2113/// temporal-MV gate's own firing counter (lane-av1tmvp).
2114///
2115/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
2116/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
2117/// this file (`decode_inter_block`) still passes `tpl: None` -- this
2118/// counter compiles and the projection math it counts is unit-tested
2119/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
2120/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
2121/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
2122/// against any real stream today. See the module doc on
2123/// `crate::motion_field` and this crate's ledger for the remaining wiring.
2124pub(crate) fn tmv_hits() -> usize {
2125 crate::mvstack::tmv_hits()
2126}
2127
2128/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
2129/// produced on this thread, the 10-bit inter gate's firing proof.
2130pub(crate) fn inter_pred_hits() -> usize {
2131 crate::mc::inter_pred_hits()
2132}
2133
2134/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
2135/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
2136/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
2137/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
2138/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
2139/// needs to turn a query block's own resolved `ref_frame` into
2140/// `TplArgs::cur_offset_0` (spec 7.9.3).
2141pub(crate) struct TplFrameArgs<'a> {
2142 pub field: &'a crate::motion_field::TplField,
2143 pub order_hint_bits: u32,
2144 pub order_hint: u32,
2145 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
2146 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
2147 /// frame's own `ref_frame_idx` names for each single reference.
2148 pub ref_order_hints: [u32; 7],
2149}
2150
2151/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
2152/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
2153/// decoded `grid`: every 4x4 unit an inter block covers reads the same
2154/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
2155/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
2156/// exact — every block this crate ever codes is at least 8x8, so no 8x8
2157/// cell straddles two different blocks' values.
2158pub(crate) fn build_motion_field(
2159 grid: &MiGrid,
2160 mi_cols: usize,
2161 mi_rows: usize,
2162 order_hint: u32,
2163 ref_order_hints: [u32; 7],
2164) -> crate::motion_field::MotionField {
2165 let mut field =
2166 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
2167 for row in 0..mi_rows {
2168 for col in 0..mi_cols {
2169 if let Some(info) = grid.get(row, col)
2170 && info.is_inter
2171 && info.ref_frame > 0
2172 {
2173 field.set(
2174 row,
2175 col,
2176 crate::motion_field::SavedMv {
2177 mv: info.mv,
2178 ref_frame: info.ref_frame,
2179 },
2180 );
2181 }
2182 }
2183 }
2184 field
2185}
2186
2187/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
2188/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
2189pub(crate) fn ref_hits(ref_frame: i8) -> usize {
2190 let c = match ref_frame {
2191 LAST2_FRAME => &LAST2_HITS,
2192 LAST3_FRAME => &LAST3_HITS,
2193 GOLDEN_FRAME => &GOLDEN_HITS,
2194 BWDREF_FRAME => &BWDREF_HITS,
2195 ALTREF2_FRAME => &ALTREF2_HITS,
2196 ALTREF_FRAME => &ALTREF_HITS,
2197 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
2198 };
2199 c.with(|v| v.get())
2200}
2201
2202thread_local! {
2203 /// The sequence header's `enable_intra_edge_filter`, set once per
2204 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
2205 /// own read of it, kept off the call stack (see that function's own doc
2206 /// comment for why) rather than threaded through every `read_plane`/
2207 /// `decode_block`/`decode_leaf8` call between here and there.
2208 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2209}
2210
2211/// Set [`ENABLE_EDGE_FILTER`] for this thread.
2212///
2213/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
2214/// never did -- so an inter frame's intra blocks read whatever value the last
2215/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
2216/// harmless (its own key frame sets it first), but a caller that decodes an
2217/// inter frame directly, or a test harness running several streams on one
2218/// thread, inherits a foreign sequence's bit: decode stops being a pure
2219/// function of the bitstream. `decode_stream` now calls this once per stream
2220/// from the sequence header, which covers every frame including inter ones.
2221pub(crate) fn set_enable_edge_filter(value: bool) {
2222 ENABLE_EDGE_FILTER.with(|f| f.set(value));
2223}
2224
2225/// Current value of [`ANGLE_DELTA_HITS`].
2226pub(crate) fn angle_delta_hits() -> usize {
2227 ANGLE_DELTA_HITS.with(|c| c.get())
2228}
2229
2230/// Current value of [`TX_CLASS1_HITS`].
2231pub(crate) fn tx_class1_hits() -> usize {
2232 TX_CLASS1_HITS.with(|c| c.get())
2233}
2234
2235// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
2236// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
2237// bottom) this thread's decode actually reconstructed -- the same
2238// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
2239// genuinely exercised the sub-8x8 leaf path rather than every attempt
2240// coincidentally landing on `PARTITION_NONE`.
2241thread_local! {
2242 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2243}
2244
2245/// Current value of [`SUB8_SPLIT_HITS`].
2246pub(crate) fn sub8_split_hits() -> usize {
2247 SUB8_SPLIT_HITS.with(|c| c.get())
2248}
2249
2250// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
2251// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
2252// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
2253// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
2254// asserts on these two rather than a plain leaf count.
2255thread_local! {
2256 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2257 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2258 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
2259 /// two 4x4 transform units, predicted one after the other. A separate
2260 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
2261 /// the gate can prove THIS path fired.
2262 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2263 /// 16x8/8x16 intra strips whose prediction actually read past the block's
2264 /// own width (above-right) or height (below-left) -- the samples
2265 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
2266 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
2267 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2268 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
2269 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
2270 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2271}
2272
2273/// Current value of [`RECT8_SPLIT_TX_HITS`].
2274pub(crate) fn rect8_split_tx_hits() -> usize {
2275 RECT8_SPLIT_TX_HITS.with(|c| c.get())
2276}
2277
2278/// Current value of [`RECT_STRIP_PRED_HITS`].
2279pub(crate) fn rect_strip_pred_hits() -> usize {
2280 RECT_STRIP_PRED_HITS.with(|c| c.get())
2281}
2282
2283/// Current value of [`RECT_STRIP_REACH_HITS`].
2284pub(crate) fn rect_strip_reach_hits() -> usize {
2285 RECT_STRIP_REACH_HITS.with(|c| c.get())
2286}
2287
2288/// Current value of [`TX4X8_CODED_HITS`].
2289pub(crate) fn tx4x8_coded_hits() -> usize {
2290 TX4X8_CODED_HITS.with(|c| c.get())
2291}
2292
2293/// Current value of [`TX8X4_CODED_HITS`].
2294pub(crate) fn tx8x4_coded_hits() -> usize {
2295 TX8X4_CODED_HITS.with(|c| c.get())
2296}
2297
2298// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
2299// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
2300// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
2301// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
2302// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
2303// (`eob_pt_{16,64,128,256}_chroma_class1`).
2304thread_local! {
2305 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
2306 const { std::cell::Cell::new(0) };
2307}
2308
2309/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
2310pub(crate) fn chroma_eob_class1_hits() -> usize {
2311 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
2312}
2313
2314/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
2315/// `tx_type` put this block's `eob_pt` on the class-1 row.
2316fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
2317 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
2318 CHROMA_EOB_CLASS1_HITS.with(|c| c.set(c.get() + 1));
2319 }
2320}
2321
2322const SUB_MI: u32 = 4;
2323const MI: usize = 4;
2324const SB: usize = 64;
2325/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
2326/// (tile start, superblock-row start).
2327///
2328/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
2329/// `av1_get_partition_plane_context` reads its own zero-initialised
2330/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
2331/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
2332/// (64), which reads identically at every level up to 64x64 but sets the bit
2333/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
2334/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
2335/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
2336const NO_NEIGHBOUR_SIDE: usize = 128;
2337const BLOCK: usize = 32;
2338const SUB: usize = 16;
2339const TX32: usize = 32;
2340const TX16: usize = 16;
2341const TX8: usize = 8;
2342const TX4: usize = 4;
2343const DC_PRED: usize = 0;
2344/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
2345/// carries an angle delta — [`crate::tile`]'s own private copy of the same
2346/// constant.
2347const V_PRED: usize = 1;
2348const H_PRED: usize = 2;
2349/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
2350/// `Fimode_To_Intradir`, libaom `blockd.h`).
2351const D157_PRED: usize = 6;
2352/// The last directional mode, `D67_PRED`.
2353const D67_PRED: usize = 8;
2354/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
2355/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
2356/// codes anything else, so this decoder never reads anything else either.
2357const ANGLE_DELTA_ZERO: usize = 3;
2358const NUM_BASE_LEVELS: i32 = 2;
2359const COEFF_BASE_RANGE: i32 = 12;
2360const BR_STEP: i32 = 3;
2361const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
2362
2363/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
2364/// whose probability mass a superblock or block half outside the frame
2365/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
2366/// duplicated here (that module is another lane's territory this round) and
2367/// kept in step with it by the byte-exact round-trip tests below rather than
2368/// by sharing code.
2369const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
2370const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
2371
2372fn element_prob(cdf: &[u16], element: usize) -> u16 {
2373 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
2374}
2375
2376/// The two-symbol CDF a partial superblock/block's forced-split flag is read
2377/// with: the mass of `elements` becomes the probability of the one partition
2378/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
2379/// (the encoder's non-adapting counterpart to this read).
2380fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
2381 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
2382 [32768 - split, 32768, 0]
2383}
2384
2385fn unsupported(what: impl Into<String>) -> Error {
2386 Error::unsupported("AV1 tile", what.into())
2387}
2388
2389/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
2390/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
2391/// same rule.
2392pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
2393 match base_q_idx {
2394 0..=20 => 0,
2395 21..=60 => 1,
2396 61..=120 => 2,
2397 _ => 3,
2398 }
2399}
2400
2401/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
2402/// [`crate::tile`]'s writer generates its scan tables with.
2403fn default_scan(side: usize) -> Vec<u16> {
2404 let mut scan = Vec::with_capacity(side * side);
2405 for d in 0..(2 * side - 1) {
2406 let lo = d.saturating_sub(side - 1);
2407 let hi = d.min(side - 1);
2408 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
2409 if d % 2 == 0 {
2410 scan.extend(diagonal.rev());
2411 } else {
2412 scan.extend(diagonal);
2413 }
2414 }
2415 scan
2416}
2417
2418/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
2419/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
2420/// in, instead of the default zigzag. libaom's own tables are keyed by a
2421/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
2422/// physically column-major level buffer, but they decompose to the exact
2423/// same (row, col) walk as a flat row-major traversal of *our* row-major
2424/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
2425/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
2426/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
2427/// transposed (column 0 down every row, then column 1, ...).
2428fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
2429 class_scan_table_wh(side, side, class)
2430}
2431
2432/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
2433/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
2434/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
2435/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
2436/// transcribed with -- `mrow` is the plain row-major raster in our indexing
2437/// and `mcol` its transpose, at rect sizes exactly as at square ones.
2438fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
2439 match class {
2440 TxClass::Vert => (0..(w * h) as u16).collect(),
2441 TxClass::Horiz => (0..w)
2442 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
2443 .collect(),
2444 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
2445 }
2446}
2447
2448fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
2449 match scan_idx {
2450 0 => 0,
2451 i if i <= area / 8 => 1,
2452 i if i <= area / 4 => 2,
2453 _ => 3,
2454 }
2455}
2456
2457fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
2458 if row >= side || col >= side {
2459 0
2460 } else {
2461 grid[row * side + col]
2462 }
2463}
2464
2465/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
2466/// `txb_common.h`): everything but the two lone-axis-identity types this
2467/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
2468#[derive(Clone, Copy, PartialEq, Eq)]
2469enum TxClass {
2470 TwoD,
2471 Horiz,
2472 Vert,
2473}
2474
2475impl TxClass {
2476 fn of(tx_type: TxType) -> Self {
2477 match tx_type {
2478 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
2479 // key on axis alone -- FLIPADST is still ADST for this purpose.
2480 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
2481 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
2482 _ => Self::TwoD,
2483 }
2484 }
2485}
2486
2487/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
2488/// table (indexed by the position along the transform's *coded* axis --
2489/// `col` for horiz, `row` for vert) that places their contexts past the 2D
2490/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
2491/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
2492fn nz_map_ctx_offset_1d(i: usize) -> usize {
2493 match i {
2494 0 => 26,
2495 1 => 31,
2496 _ => 36,
2497 }
2498}
2499
2500fn base_ctx(
2501 grid: &[i32],
2502 side: usize,
2503 row: usize,
2504 col: usize,
2505 class: TxClass,
2506 rect_shape: Option<(usize, usize)>,
2507) -> usize {
2508 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
2509 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
2510 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
2511 // position through the full 1D neighbour sum and offset table. Skipping
2512 // that for every class desynced the last (DC) coefficient of a
2513 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
2514 // 0, which then read one extra `BR` symbol at the max and forced a
2515 // spurious third Golomb call).
2516 if class == TxClass::TwoD && row == 0 && col == 0 {
2517 return 0;
2518 }
2519 let offsets: [(usize, usize); 5] = match class {
2520 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
2521 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
2522 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
2523 };
2524 let mag: i32 = offsets
2525 .iter()
2526 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
2527 .sum();
2528 let ctx = ((mag + 1) >> 1).min(4) as usize;
2529 match class {
2530 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
2531 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
2532 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
2533 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
2534 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
2535 // strip, which own a genuinely different table from the square one
2536 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
2537 // square table vs the real ctx 13 the rect table gives).
2538 TxClass::TwoD => {
2539 // lane-rectsplit r4: apply libaom's GENERATING RULE
2540 // (`txb_common.h:199-209`) directly instead of indexing the
2541 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
2542 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
2543 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
2544 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
2545 // so 32 consecutive entries are one COLUMN: the [`cdf`]
2546 // transcriptions are `[col][row]` and this read had them as
2547 // `[row][col]` -- the transpose, i.e. the other shape's rule with
2548 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
2549 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
2550 // pins the rule against the tables over their whole 5x5 domain.
2551 if let Some((w, h)) = rect_shape {
2552 if std::env::var_os("EC_NZOFF_DUMP").is_some() {
2553 eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}");
2554 }
2555 if w < h && row < 2 {
2556 return ctx + 11;
2557 }
2558 if w > h && col < 2 {
2559 return ctx + 16;
2560 }
2561 }
2562 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2563 }
2564 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
2565 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
2566 }
2567}
2568
2569fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
2570 let extra = match class {
2571 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
2572 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
2573 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
2574 };
2575 let mag = neighbour(grid, side, row + 1, col).abs()
2576 + neighbour(grid, side, row, col + 1).abs()
2577 + extra;
2578 let mag = (((mag + 1) >> 1).min(6)) as usize;
2579 if row == 0 && col == 0 {
2580 return mag;
2581 }
2582 let near_origin = match class {
2583 TxClass::TwoD => row < 2 && col < 2,
2584 TxClass::Horiz => col == 0,
2585 TxClass::Vert => row == 0,
2586 };
2587 if near_origin { mag + 7 } else { mag + 14 }
2588}
2589
2590/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
2591/// transposed from libaom's column-major buffer into this decoder's row-major
2592/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
2593/// against the real table). Not the square zigzag formula generalized to
2594/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
2595const SCAN_32X16: [u16; 512] = [
2596 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
2597 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
2598 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
2599 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
2600 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
2601 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
2602 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
2603 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
2604 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
2605 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
2606 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
2607 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
2608 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
2609 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
2610 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
2611 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
2612 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
2613 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
2614 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
2615 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
2616 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
2617 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
2618 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
2619 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
2620 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
2621 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
2622 509, 478, 447, 510, 479, 511,
2623];
2624
2625/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
2626/// [`SCAN_32X16`]'s doc comment).
2627const SCAN_16X32: [u16; 512] = [
2628 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,
2629 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
2630 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
2631 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
2632 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
2633 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
2634 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
2635 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
2636 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
2637 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
2638 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
2639 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
2640 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
2641 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
2642 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
2643 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
2644 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
2645 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
2646 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
2647 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
2648 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
2649 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
2650 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
2651 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
2652 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
2653 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
2654];
2655
2656/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
2657/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
2658/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
2659/// the same source).
2660const SCAN_4X8: [u16; 32] = [
2661 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,
2662 23, 26, 29, 27, 30, 31,
2663];
2664
2665/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
2666const SCAN_8X4: [u16; 32] = [
2667 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,
2668 29, 22, 15, 30, 23, 31,
2669];
2670
2671/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
2672/// [`SCAN_32X16`]'s doc comment).
2673const SCAN_16X8: [u16; 128] = [
2674 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,
2675 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
2676 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
2677 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
2678 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
2679 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
2680];
2681
2682/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
2683/// [`SCAN_32X16`]'s doc comment).
2684const SCAN_8X16: [u16; 128] = [
2685 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,
2686 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
2687 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
2688 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
2689 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
2690 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
2691];
2692
2693/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
2694/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
2695/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
2696/// scans column-major (`p = col * height + row`), so a naive copy of
2697/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
2698/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
2699/// are byte-identical to this decoder's [`SCAN_8X16`].
2700const SCAN_32X8: [u16; 256] = [
2701 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
2702 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
2703 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
2704 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
2705 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
2706 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
2707 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
2708 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
2709 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
2710 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
2711 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
2712 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
2713 222, 191, 254, 223, 255,
2714];
2715/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
2716/// 16x64 `PARTITION_VERT_4` strip).
2717const SCAN_8X32: [u16; 256] = [
2718 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,
2719 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
2720 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
2721 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
2722 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
2723 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
2724 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
2725 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
2726 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
2727 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
2728 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
2729 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
2730 239, 246, 253, 247, 254, 255,
2731];
2732/// `Default_Scan_16x4`, this decoder's own row-major transcription of
2733/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
2734/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
2735/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
2736/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
2737/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
2738/// were emitted -- a naive copy installs the transpose (class
2739/// reference-layout-not-spec).
2740const SCAN_16X4: [u16; 64] = [
2741 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,
2742 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
2743 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
2744];
2745/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
2746/// 8x32 `PARTITION_VERT_4` strip).
2747const SCAN_4X16: [u16; 64] = [
2748 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,
2749 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
2750 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
2751];
2752
2753/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
2754/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
2755/// asymmetric-extent pattern).
2756fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
2757 if row >= h || col >= w {
2758 0
2759 } else {
2760 grid[row * w + col]
2761 }
2762}
2763
2764/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
2765/// the rect generalization is libaom's own comment in
2766/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
2767/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
2768/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
2769/// [`decode_block_rect`] codes (see that function's own doc comment).
2770fn base_ctx_rect(
2771 grid: &[i32],
2772 w: usize,
2773 h: usize,
2774 row: usize,
2775 col: usize,
2776 class: TxClass,
2777) -> usize {
2778 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
2779 // the 2D class short-circuits the DC position.
2780 if class == TxClass::TwoD && row == 0 && col == 0 {
2781 return 0;
2782 }
2783 let offsets: [(usize, usize); 5] = match class {
2784 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
2785 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
2786 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
2787 };
2788 let mag: i32 = offsets
2789 .iter()
2790 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
2791 .sum();
2792 let ctx = ((mag + 1) >> 1).min(4) as usize;
2793 match class {
2794 TxClass::TwoD => {
2795 if w < h && row < 2 {
2796 return ctx + 11;
2797 }
2798 if w > h && col < 2 {
2799 return ctx + 16;
2800 }
2801 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2802 }
2803 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
2804 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
2805 // position along one axis only).
2806 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
2807 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
2808 }
2809}
2810
2811/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
2812/// neighbour-offset math itself is shape-independent, only the boundary
2813/// clamp needs the real bound in each axis.
2814fn br_ctx_rect(
2815 grid: &[i32],
2816 w: usize,
2817 h: usize,
2818 row: usize,
2819 col: usize,
2820 class: TxClass,
2821) -> usize {
2822 let extra = match class {
2823 TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(),
2824 TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(),
2825 TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(),
2826 };
2827 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
2828 + neighbour_rect(grid, w, h, row, col + 1).abs()
2829 + extra;
2830 let mag = (((mag + 1) >> 1).min(6)) as usize;
2831 if row == 0 && col == 0 {
2832 return mag;
2833 }
2834 let near_origin = match class {
2835 TxClass::TwoD => row < 2 && col < 2,
2836 TxClass::Horiz => col == 0,
2837 TxClass::Vert => row == 0,
2838 };
2839 if near_origin { mag + 7 } else { mag + 14 }
2840}
2841
2842fn dc_vote(dc: Option<bool>) -> i32 {
2843 match dc {
2844 None => 0,
2845 Some(true) => -1,
2846 Some(false) => 1,
2847 }
2848}
2849
2850fn dc_sign_ctx(vote: i32) -> usize {
2851 match vote.signum() {
2852 0 => 0,
2853 -1 => 1,
2854 _ => 2,
2855 }
2856}
2857
2858/// The remainder of a level the base and base-range syntax could not reach
2859/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
2860/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
2861fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
2862 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
2863 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
2864 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
2865 // for every tail any encoder writes -- our own writer tops out at 19 zeros
2866 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
2867 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
2868 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
2869 // RED: seed 67 stops here today, and with the cap raised it decodes to a
2870 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
2871 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
2872 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
2873 // together with that defect's fix, not before.
2874 let mut length = 1u32;
2875 while dec.literal(1) == 0 {
2876 length += 1;
2877 if length > 20 {
2878 return Err(unsupported("a Golomb tail longer than this decoder reads"));
2879 }
2880 }
2881 let mut x = 1u32;
2882 for _ in 1..length {
2883 x = (x << 1) | dec.literal(1);
2884 }
2885 Ok(x - 1)
2886}
2887
2888/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
2889/// [`crate::tile`]'s `write_eob`.
2890fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
2891 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
2892 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
2893
2894 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2895 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
2896 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
2897 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
2898 // `eob_multi_ctx`). Missing that split desynced the very first
2899 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
2900 // against a real aomdec trace).
2901 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
2902 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
2903 (_, Some(class1)) => class1,
2904 };
2905 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2906 let (range, value) = dec.debug_state();
2907 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
2908 }
2909 let group = dec.symbol(eob_pt) + 1;
2910 if trace {
2911 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
2912 }
2913 let bits = OFFSET_BITS[group];
2914 let mut offset = 0u32;
2915 if bits > 0 {
2916 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
2917 if trace {
2918 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
2919 }
2920 offset = top << (bits - 1);
2921 if bits > 1 {
2922 offset |= dec.literal(bits - 1);
2923 }
2924 }
2925 GROUP_START[group] + offset as usize
2926}
2927
2928/// One transform block's levels, the inverse of [`crate::tile`]'s
2929/// `write_coeffs`, returned as a `side * side` grid in raster order, along
2930/// with the transform type that grid was coded under (`DCT_DCT` when the
2931/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
2932/// 64-point transforms, which never code anything else).
2933///
2934/// # Errors
2935/// Returns an error if the `tx_type` symbol decodes to a value outside its
2936/// CDF's own set (a corrupt or unsupported bitstream) — every value the
2937/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
2938/// produce dispatches to a real inverse transform.
2939/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
2940/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
2941/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
2942/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
2943/// the plane's own predicted mode instead. Every entry this table can
2944/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
2945/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
2946/// table ever names), so unlike the CDF-coded luma path there is no
2947/// ext-tx-set membership check to fall back from here.
2948fn default_intra_tx_type(mode: u8) -> TxType {
2949 use crate::intra::{
2950 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
2951 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
2952 };
2953 match mode {
2954 DC_PRED | D45_PRED => TxType::DctDct,
2955 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
2956 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
2957 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
2958 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
2959 }
2960}
2961
2962/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
2963/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
2964/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
2965fn is_smooth_mode(mode: usize) -> bool {
2966 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
2967}
2968
2969fn read_coeffs(
2970 dec: &mut SymbolDecoder,
2971 coding: &mut TxbTables,
2972 scan: &[u16],
2973 skip_ctx: usize,
2974 sign_ctx: usize,
2975 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
2976 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
2977 // nothing at all; `DctDct` for every luma call and every chroma call at
2978 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
2979 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
2980 default_tx_type: TxType,
2981 // `Some((w, h))` with `w != h` when this read is a superblock-level
2982 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
2983 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
2984 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
2985 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
2986 // caller's block genuinely is `side` x `side`.
2987 rect_shape: Option<(usize, usize)>,
2988) -> Result<(Vec<i32>, TxType)> {
2989 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2990 let side = coding.side;
2991 let mut grid = vec![0i32; side * side];
2992 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2993 let (range, value) = dec.debug_state();
2994 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
2995 }
2996 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
2997 if std::env::var_os("EC_TRACE_COEFF").is_some() {
2998 let (rng, _) = dec.debug_state();
2999 eprintln!(
3000 "EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero={} rng={rng}",
3001 all_zero as i32
3002 );
3003 }
3004 if std::env::var_os("EC_AV1_TELL").is_some() {
3005 eprintln!(
3006 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
3007 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
3008 );
3009 }
3010 if trace {
3011 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
3012 }
3013 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
3014 let (range, value) = dec.debug_state();
3015 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
3016 }
3017 if all_zero {
3018 return Ok((grid, TxType::DctDct));
3019 }
3020 let mut tx_type = default_tx_type;
3021 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
3022 // The CDF row's own width names its set (lane-cdffwd2: extended
3023 // past the original two-way intra split once wider `reduced_tx_set
3024 // == 0` inter sets joined the table): 17 slots (16 symbols) is
3025 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
3026 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
3027 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
3028 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
3029 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
3030 let len = tx_type_cdf.len();
3031 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
3032 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
3033 }
3034 let t = dec.symbol(tx_type_cdf);
3035 if std::env::var_os("EC_TRACE_COEFF").is_some() {
3036 let (rng, _) = dec.debug_state();
3037 eprintln!("EC_COEFF_STEP tag=tx_type rng={rng}");
3038 }
3039 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
3040 let (range, value) = dec.debug_state();
3041 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
3042 }
3043 if trace {
3044 eprintln!("TRACE tx_type value={t} len={len}");
3045 }
3046 tx_type = match len {
3047 17 => TxType::from_symbol_all16(t),
3048 13 => TxType::from_symbol_set2_12(t),
3049 8 => TxType::from_symbol_set1(t),
3050 _ => TxType::from_symbol(t),
3051 }
3052 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
3053 }
3054
3055 let class = TxClass::of(tx_type);
3056 if class != TxClass::TwoD {
3057 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3058 RECT_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3059 }
3060 let eob = read_eob(dec, coding, class);
3061 if trace {
3062 eprintln!("TRACE eob value={eob}");
3063 }
3064 let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some();
3065 if ec_trace_coeff {
3066 let (rng, _) = dec.debug_state();
3067 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
3068 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
3069 }
3070 let class_scan;
3071 let scan: &[u16] = if class == TxClass::TwoD {
3072 scan
3073 } else {
3074 class_scan = class_scan_table(side, class);
3075 &class_scan
3076 };
3077 let mut levels = vec![0i32; side * side];
3078 for scan_idx in (0..eob).rev() {
3079 let pos = scan[scan_idx] as usize;
3080 let (row, col) = (pos / side, pos % side);
3081 let level = if scan_idx == eob - 1 {
3082 let ctx = eob_coeff_ctx(scan_idx, side * side);
3083 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
3084 if trace {
3085 eprintln!(
3086 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
3087 );
3088 }
3089 v
3090 } else {
3091 let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
3092 let v = dec.symbol(&mut coding.base[ctx]) as i32;
3093 if ec_trace_coeff {
3094 let (rng, _) = dec.debug_state();
3095 // `pos` in libaom's column-major `coeff_idx` convention, so
3096 // the ladder lines up with instrumented `aomdec`.
3097 let apos = col * side + row;
3098 eprintln!(
3099 "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"
3100 );
3101 }
3102 if trace {
3103 eprintln!(
3104 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
3105 );
3106 }
3107 v
3108 };
3109 let level = if level > NUM_BASE_LEVELS {
3110 let ctx = br_ctx(&levels, side, row, col, class);
3111 let mut level = level;
3112 let mut sent = 0;
3113 loop {
3114 let k = dec.symbol(&mut coding.br[ctx]) as i32;
3115 if trace {
3116 eprintln!(
3117 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
3118 );
3119 }
3120 level += k;
3121 sent += BR_STEP;
3122 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
3123 break;
3124 }
3125 }
3126 level
3127 } else {
3128 level
3129 };
3130 if ec_trace_coeff && scan_idx == eob - 1 {
3131 let (rng, _) = dec.debug_state();
3132 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
3133 }
3134 levels[pos] = level;
3135 }
3136 if ec_trace_coeff {
3137 let (rng, _) = dec.debug_state();
3138 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
3139 }
3140
3141 for (c, &pos) in scan[..eob].iter().enumerate() {
3142 let level = levels[pos as usize];
3143 if level == 0 {
3144 continue;
3145 }
3146 let negative = if pos == 0 {
3147 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
3148 if trace {
3149 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
3150 }
3151 v
3152 } else {
3153 dec.literal(1) == 1
3154 };
3155 if ec_trace_coeff {
3156 let (rng, _) = dec.debug_state();
3157 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
3158 }
3159 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
3160 let g = read_golomb(dec)?;
3161 if trace {
3162 eprintln!("TRACE golomb pos={pos} value={g}");
3163 }
3164 level + g as i32
3165 } else {
3166 level
3167 };
3168 if ec_trace_coeff {
3169 let (rng, _) = dec.debug_state();
3170 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
3171 }
3172 grid[pos as usize] = if negative { -level } else { level };
3173 }
3174 Ok((grid, tx_type))
3175}
3176
3177/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
3178/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
3179/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
3180/// can ever produce, since every `tx_type` this decoder's rect sets can read
3181/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
3182/// rather than guess-decode if a non-2D class ever shows up here, since
3183/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
3184/// form for those.
3185fn read_coeffs_rect(
3186 dec: &mut SymbolDecoder,
3187 coding: &mut TxbTables,
3188 scan: &[u16],
3189 w: usize,
3190 h: usize,
3191 skip_ctx: usize,
3192 sign_ctx: usize,
3193 default_tx_type: TxType,
3194) -> Result<(Vec<i32>, TxType)> {
3195 let rect_trace = std::env::var_os("EC_TRACE_COEFF").is_some();
3196 let mut grid = vec![0i32; w * h];
3197 let entry_rng = dec.debug_state().0;
3198 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
3199 if rect_trace {
3200 eprintln!(
3201 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} all_zero={} rng={}",
3202 all_zero as i32,
3203 dec.debug_state().0
3204 );
3205 }
3206 if all_zero {
3207 return Ok((grid, TxType::DctDct));
3208 }
3209 RECT_COEFF_TU_HITS.with(|c| c.set(c.get() + 1));
3210 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
3211 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
3212 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
3213 // context offsets -- both of which now have rect forms
3214 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
3215 // The rect sets that carry no symbol at all still pass `None` here.
3216 let mut tx_type = default_tx_type;
3217 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
3218 let len = tx_type_cdf.len();
3219 let t = dec.symbol(tx_type_cdf);
3220 tx_type = match len {
3221 17 => TxType::from_symbol_all16(t),
3222 13 => TxType::from_symbol_set2_12(t),
3223 8 => TxType::from_symbol_set1(t),
3224 _ => TxType::from_symbol(t),
3225 }
3226 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
3227 if rect_trace {
3228 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
3229 }
3230 }
3231 let class = TxClass::of(tx_type);
3232 if class != TxClass::TwoD {
3233 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3234 }
3235 let eob = read_eob(dec, coding, class);
3236 if rect_trace {
3237 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
3238 }
3239 let class_scan;
3240 let scan: &[u16] = if class == TxClass::TwoD {
3241 scan
3242 } else {
3243 class_scan = class_scan_table_wh(w, h, class);
3244 &class_scan
3245 };
3246 let mut levels = vec![0i32; w * h];
3247 for scan_idx in (0..eob).rev() {
3248 let pos = scan[scan_idx] as usize;
3249 let (row, col) = (pos / w, pos % w);
3250 // libaom's column-major `coeff_idx`, for ladder comparison.
3251 let apos = col * h + row;
3252 let level = if scan_idx == eob - 1 {
3253 let ctx = eob_coeff_ctx(scan_idx, w * h);
3254 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
3255 if rect_trace {
3256 eprintln!(
3257 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
3258 dec.debug_state().0
3259 );
3260 }
3261 v
3262 } else {
3263 let ctx = base_ctx_rect(&levels, w, h, row, col, class);
3264 let v = dec.symbol(&mut coding.base[ctx]) as i32;
3265 if rect_trace {
3266 eprintln!(
3267 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
3268 dec.debug_state().0
3269 );
3270 }
3271 v
3272 };
3273 let level = if level > NUM_BASE_LEVELS {
3274 let ctx = br_ctx_rect(&levels, w, h, row, col, class);
3275 let mut level = level;
3276 let mut sent = 0;
3277 loop {
3278 let k = dec.symbol(&mut coding.br[ctx]) as i32;
3279 if rect_trace {
3280 eprintln!(
3281 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
3282 dec.debug_state().0
3283 );
3284 }
3285 level += k;
3286 sent += BR_STEP;
3287 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
3288 break;
3289 }
3290 }
3291 level
3292 } else {
3293 level
3294 };
3295 levels[pos] = level;
3296 if rect_trace {
3297 let (rng, _) = dec.debug_state();
3298 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
3299 }
3300 }
3301 if rect_trace {
3302 let (rng, _) = dec.debug_state();
3303 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
3304 }
3305 for &pos in &scan[..eob] {
3306 let level = levels[pos as usize];
3307 if level == 0 {
3308 continue;
3309 }
3310 let negative = if pos == 0 {
3311 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
3312 } else {
3313 dec.literal(1) == 1
3314 };
3315 if rect_trace {
3316 let (rng, _) = dec.debug_state();
3317 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} rng={rng}", u8::from(negative));
3318 }
3319 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
3320 let g = read_golomb(dec)?;
3321 level + g as i32
3322 } else {
3323 level
3324 };
3325 grid[pos as usize] = if negative { -level } else { level };
3326 }
3327 Ok((grid, tx_type))
3328}
3329
3330/// What one coded block leaves behind for the blocks that read it as a
3331/// neighbour: whether it coded anything at all, and the sign of its DC —
3332/// [`crate::tile`]'s own private `Neighbour`.
3333#[derive(Clone, Copy, Default)]
3334struct Neighbour {
3335 /// The transform unit's cumulative coefficient level (spec `cul_level`,
3336 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
3337 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
3338 /// boolean (`level != 0`) is enough for every context this decoder read
3339 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
3340 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
3341 /// needs the actual magnitude tier of its above/left neighbours, not
3342 /// just whether they coded anything.
3343 level: u8,
3344 dc: Option<bool>,
3345}
3346
3347fn neighbour_state(grid: &[i32]) -> Neighbour {
3348 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
3349 Neighbour {
3350 level: cul.min(7) as u8,
3351 dc: (grid[0] != 0).then_some(grid[0] < 0),
3352 }
3353}
3354
3355/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
3356/// transform unit smaller than the block it sits in): `top`/`left` are the
3357/// above/left neighbours' magnitude tiers, each already clamped to 4.
3358const SKIP_CONTEXTS: [[usize; 5]; 5] = [
3359 [1, 2, 2, 2, 3],
3360 [2, 4, 4, 4, 5],
3361 [2, 4, 4, 4, 5],
3362 [2, 4, 4, 4, 5],
3363 [3, 5, 5, 5, 6],
3364];
3365
3366/// The neighbour state a block's contexts are read from — a duplicate of
3367/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
3368/// territory this round), kept at the same two granularities the real writer
3369/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
3370/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
3371/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
3372/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
3373/// chroma transform straddling the true, odd-sized frame edge see its
3374/// neighbour's state clamped at its own subsampled edge rather than luma's.
3375struct Neighbours {
3376 above: Vec<[Neighbour; 3]>,
3377 left: Vec<[Neighbour; 3]>,
3378 above_mode: Vec<usize>,
3379 left_mode: Vec<usize>,
3380 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
3381 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
3382 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
3383 /// luma one -- the same block can (and often does) code a different
3384 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
3385 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
3386 /// within-block neighbour finer than this grid) is luma-only -- a known,
3387 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
3388 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
3389 above_uv_mode: Vec<usize>,
3390 left_uv_mode: Vec<usize>,
3391 above_side: Vec<usize>,
3392 left_side: Vec<usize>,
3393 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
3394 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
3395 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
3396 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
3397 /// array cannot tell the second leaf's partition symbol that the first
3398 /// one was coded at 8x8.
3399 above_side_mi: Vec<usize>,
3400 left_side_mi: Vec<usize>,
3401 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
3402 /// / row, with the mi position it was written at
3403 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
3404 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
3405 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
3406 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
3407 /// leaf whose neighbour is another split group needs that group's leaf 3
3408 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
3409 /// and read only by [`decode_leaf_split4`]; the position guard makes it
3410 /// fall back to the coarse slot whenever the real neighbour was a block
3411 /// of 8x8 or larger (whose one mode is correct for every row it spans).
3412 sub8_mode_col: Vec<(usize, usize)>,
3413 sub8_mode_row: Vec<(usize, usize)>,
3414 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
3415 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
3416 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
3417 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
3418 /// the leaf above writes the same row slot the block to the left owns.
3419 uv_mode_col: Vec<(usize, usize)>,
3420 uv_mode_row: Vec<(usize, usize)>,
3421 /// Whether the block above/left of this column/row was coded `skip` --
3422 /// an inter frame's own `skip` context (spec `SkipContext`), which the
3423 /// key-frame writer never tracks (its skip context is always zero); a
3424 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
3425 /// `left_skip`.
3426 above_skip: Vec<bool>,
3427 left_skip: Vec<bool>,
3428 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
3429 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
3430 /// pixels last written over each unit by `set_txfm_ctxs`/
3431 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
3432 /// symbol reads its context from (lane-txselect, spec 5.11.17).
3433 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
3434 /// array is exactly libaom's per-superblock-row reset, since each mi row
3435 /// is only ever visited inside one superblock row.
3436 above_txfm: Vec<u8>,
3437 left_txfm: Vec<u8>,
3438 /// Whether the block above/left of this column/row coded `skip_mode`
3439 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
3440 /// lane-av1comp round 14.
3441 above_skip_mode: Vec<bool>,
3442 left_skip_mode: Vec<bool>,
3443 /// Whether the block above/left was coded inter -- the `is_inter`
3444 /// context (spec `av1_get_intra_inter_context`), a duplicate of
3445 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
3446 above_inter: Vec<bool>,
3447 left_inter: Vec<bool>,
3448 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
3449 /// alphabet) the block above/left of this column/row coded, or `-1` for
3450 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
3451 /// functions (`mvstack::ref_ctx` family) need the real reference, not
3452 /// just "was it inter" (lane-av1refs: every inter block used to be
3453 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
3454 /// enough).
3455 above_ref: Vec<i8>,
3456 left_ref: Vec<i8>,
3457 /// The block above/left's *second* reference frame when it was coded
3458 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
3459 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
3460 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
3461 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
3462 /// (no decode path here ever produces a compound block yet).
3463 above_ref1: Vec<Option<i8>>,
3464 left_ref1: Vec<Option<i8>>,
3465 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
3466 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
3467 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
3468 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
3469 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
3470 above_comp_group_idx: Vec<u8>,
3471 left_comp_group_idx: Vec<u8>,
3472 above_compound_idx: Vec<u8>,
3473 left_compound_idx: Vec<u8>,
3474 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
3475 /// `3` = "no info": an intra neighbour or the frame's own border) of the
3476 /// block above/left of this column/row -- spec
3477 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
3478 above_filter: Vec<[u8; 2]>,
3479 left_filter: Vec<[u8; 2]>,
3480 mi_cols: usize,
3481 mi_rows: usize,
3482 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
3483 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
3484 /// 7.15) never filters an 8x8 luma block whose covering coded block read
3485 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
3486 /// grain [`Self::record_mi`] already writes at), read back at 8x8
3487 /// granularity by [`apply_cdef`] since `skip` is constant across every
3488 /// mi cell one coded block covers.
3489 skip_grid: Vec<bool>,
3490 skip_grid_cols_mi: usize,
3491 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
3492 /// never splits a coded block's transform below its own size (round 2:
3493 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
3494 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
3495 /// edge-length lookup (`apply_deblock`).
3496 tx_grid: Vec<u8>,
3497 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
3498 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
3499 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
3500 tx_h_grid: Vec<u8>,
3501 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
3502 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
3503 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
3504 /// does NOT follow luma's `tx_depth` split, so deriving it as
3505 /// `tx_grid / 2` invented chroma transform edges the deblocker then
3506 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
3507 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
3508 /// every caller routes through.
3509 uv_tx_grid: Vec<u8>,
3510 uv_tx_h_grid: Vec<u8>,
3511 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
3512 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
3513 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
3514 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
3515 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
3516 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
3517 /// reference onto `LAST_FRAME`'s own delta).
3518 ref_grid: Vec<i8>,
3519 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
3520 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
3521 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
3522 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
3523 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
3524 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
3525 /// to know which mode produced the value.
3526 delta_lf_grid: Vec<[i8; 4]>,
3527 /// The block above/left's own palette-Y size (0 = not a palette block)
3528 /// and its base colours -- `av1_get_palette_mode_ctx`/
3529 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
3530 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
3531 above_palette_size: Vec<usize>,
3532 left_palette_size: Vec<usize>,
3533 above_palette_colors: Vec<[u16; 8]>,
3534 left_palette_colors: Vec<[u16; 8]>,
3535 /// As the four fields above, for the neighbour's own chroma (U-channel
3536 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
3537 /// palette size/colours (lane-palette2 r1).
3538 above_palette_uv_size: Vec<usize>,
3539 left_palette_uv_size: Vec<usize>,
3540 above_palette_uv_colors: Vec<[u16; 8]>,
3541 left_palette_uv_colors: Vec<[u16; 8]>,
3542 /// This tile's own top-left corner, in 4x4 mode-info units (spec
3543 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
3544 /// neighbour" check compares against this instead of literal `0`, since a
3545 /// block at the tile's own top/left edge has no usable neighbour even
3546 /// though a decoded block sits there in the picture (spec `decode_tile`'s
3547 /// per-tile `clear_above_context`/`left_available`/`up_available`).
3548 /// `0` for a single-tile frame, matching every existing caller exactly.
3549 tile_row0_mi: usize,
3550 tile_col0_mi: usize,
3551}
3552
3553impl Neighbours {
3554 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
3555 /// true (unpadded) size in 4x4 mode-info units.
3556 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
3557 Self {
3558 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
3559 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
3560 above_mode: vec![DC_PRED; cols],
3561 left_mode: vec![DC_PRED; rows],
3562 above_uv_mode: vec![DC_PRED; cols],
3563 left_uv_mode: vec![DC_PRED; rows],
3564 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
3565 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
3566 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
3567 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
3568 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3569 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3570 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3571 uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3572 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
3573 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
3574 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
3575 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
3576 // 16x16 block beside it, which a SUB-grid slot cannot name
3577 // (class context-read-from-one-cell).
3578 above_skip: vec![false; cols * (SUB / MI)],
3579 left_skip: vec![false; rows * (SUB / MI)],
3580 above_skip_mode: vec![false; cols * (SUB / MI)],
3581 left_skip_mode: vec![false; rows * (SUB / MI)],
3582 above_inter: vec![false; cols * (SUB / MI)],
3583 left_inter: vec![false; rows * (SUB / MI)],
3584 above_ref: vec![-1; cols * (SUB / MI)],
3585 left_ref: vec![-1; rows * (SUB / MI)],
3586 above_ref1: vec![None; cols * (SUB / MI)],
3587 left_ref1: vec![None; rows * (SUB / MI)],
3588 above_comp_group_idx: vec![0; cols * (SUB / MI)],
3589 left_comp_group_idx: vec![0; rows * (SUB / MI)],
3590 above_compound_idx: vec![0; cols * (SUB / MI)],
3591 left_compound_idx: vec![0; rows * (SUB / MI)],
3592 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
3593 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
3594 mi_cols,
3595 mi_rows,
3596 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
3597 skip_grid_cols_mi: cols * (SUB / MI),
3598 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3599 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3600 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3601 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3602 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
3603 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
3604 above_palette_size: vec![0; cols],
3605 left_palette_size: vec![0; rows],
3606 above_palette_colors: vec![[0u16; 8]; cols],
3607 left_palette_colors: vec![[0u16; 8]; rows],
3608 above_palette_uv_size: vec![0; cols],
3609 left_palette_uv_size: vec![0; rows],
3610 above_palette_uv_colors: vec![[0u16; 8]; cols],
3611 left_palette_uv_colors: vec![[0u16; 8]; rows],
3612 tile_row0_mi: 0,
3613 tile_col0_mi: 0,
3614 }
3615 }
3616
3617 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
3618 /// tile's own column span (`col1_mi` exclusive), plus recording
3619 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
3620 /// availability check below. Left context resets every superblock row
3621 /// regardless of tile ([`Self::start_row`], already called once per SB
3622 /// row by every caller) so it needs no tile-specific reset here.
3623 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
3624 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
3625 // are tile-relative, same as every other neighbour lookup here.
3626 SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
3627 self.tile_row0_mi = row0_mi;
3628 self.tile_col0_mi = col0_mi;
3629 let end = col1_mi.min(self.above.len());
3630 for i in col0_mi.min(end)..end {
3631 self.above[i] = Default::default();
3632 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE;
3633 }
3634 let (sc0, sc1) = (
3635 col0_mi / (SUB / MI),
3636 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
3637 );
3638 for i in sc0.min(sc1)..sc1 {
3639 self.above_mode[i] = DC_PRED;
3640 self.above_side[i] = NO_NEIGHBOUR_SIDE;
3641 }
3642 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
3643 // the tile's own mi column span directly.
3644 let mend = col1_mi.min(self.above_skip.len());
3645 for i in col0_mi.min(mend)..mend {
3646 self.above_skip[i] = false;
3647 self.above_skip_mode[i] = false;
3648 self.above_inter[i] = false;
3649 self.above_ref[i] = -1;
3650 self.above_ref1[i] = None;
3651 self.above_comp_group_idx[i] = 0;
3652 self.above_compound_idx[i] = 0;
3653 self.above_filter[i] = [3u8; 2];
3654 }
3655 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
3656 // stale `(row, mode)` from the tile to the LEFT names an mi row this
3657 // tile's first block would read as its own above neighbour.
3658 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
3659 for i in col0_mi.min(mcol_end)..mcol_end {
3660 self.sub8_mode_col[i] = (usize::MAX, 0);
3661 self.uv_mode_col[i] = (usize::MAX, 0);
3662 }
3663 }
3664
3665 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
3666 /// for a non-palette block, clearing any stale neighbour state) into every
3667 /// [`SUB`]-grid cell it covers on both the above and left edges --
3668 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
3669 /// call sites are all square blocks).
3670 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3671 self.record_palette_y_rect(at, side, side, size, colors);
3672 }
3673
3674 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
3675 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
3676 /// [`Self::record`]): a true rect strip's above/left neighbour spans
3677 /// differ.
3678 fn record_palette_y_rect(
3679 &mut self,
3680 at: (usize, usize),
3681 w: usize,
3682 h: usize,
3683 size: usize,
3684 colors: [u16; 8],
3685 ) {
3686 let (r, c) = at;
3687 // `.max(1)`: a below-16px span covers no whole SUB cell, so the plain
3688 // `w / SUB` loop was a NO-OP for every 16x8/8x16/8x8/4x4 leaf and the
3689 // next block read a long-dead palette out of the above/left arrays
3690 // (class [[cdf-row-held-constant]], lane-palette2 r8). libaom keeps
3691 // `palette_size` per 4px mi cell; corner-cut: our grid is 16px, so a
3692 // sub-16 leaf stamps its whole containing cell -- safe today because
3693 // every sub-16 leaf path refuses palette outright (so it can only
3694 // ever stamp `size == 0`, and its cell holds no palette sibling).
3695 // Upgrade path: widen the palette arrays to mi granularity.
3696 for cell in 0..(w / SUB).max(1) {
3697 self.above_palette_size[c + cell] = size;
3698 self.above_palette_colors[c + cell] = colors;
3699 }
3700 for cell in 0..(h / SUB).max(1) {
3701 self.left_palette_size[r + cell] = size;
3702 self.left_palette_colors[r + cell] = colors;
3703 }
3704 }
3705
3706 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
3707 /// neighbours that are themselves a palette-Y block, plus
3708 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
3709 /// cache (pred_common.c:73).
3710 ///
3711 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
3712 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
3713 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
3714 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
3715 /// the ctx too made every superblock in the frame's second SB row read
3716 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
3717 /// palette block decoded as "no palette" and the tile desynced from
3718 /// there (class [[cdf-row-held-constant]]).
3719 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
3720 let (r, c) = at;
3721 let above_ok = r % 4 != 0;
3722 // `xd->above_mbmi` exists for every row but the tile's own first.
3723 let above_is_palette =
3724 r * (SUB / MI) > self.tile_row0_mi && self.above_palette_size[c] > 0;
3725 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
3726 (self.above_palette_size[c], self.above_palette_colors[c])
3727 } else {
3728 (0, [0u16; 8])
3729 };
3730 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
3731 // is NULL whenever the block sits at its TILE's own left column
3732 // (`left_available`), not the frame's -- without this guard a second
3733 // tile column reads the previous tile's palette colours into its cache
3734 // and its `palette_y_mode` ctx.
3735 let left_ok = c > self.tile_col0_mi / (SUB / MI);
3736 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
3737 (self.left_palette_size[r], self.left_palette_colors[r])
3738 } else {
3739 (0, [0u16; 8])
3740 };
3741 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
3742 let mut cache = Vec::with_capacity(16);
3743 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3744 if cache.last() != Some(&v) {
3745 cache.push(v);
3746 }
3747 };
3748 let (mut ai, mut li) = (0usize, 0usize);
3749 while ai < above_n && li < left_n {
3750 let (va, vl) = (above_colors[ai], left_colors[li]);
3751 if vl < va {
3752 push_dedup(&mut cache, vl);
3753 li += 1;
3754 } else {
3755 push_dedup(&mut cache, va);
3756 ai += 1;
3757 if vl == va {
3758 li += 1;
3759 }
3760 }
3761 }
3762 while ai < above_n {
3763 push_dedup(&mut cache, above_colors[ai]);
3764 ai += 1;
3765 }
3766 while li < left_n {
3767 push_dedup(&mut cache, left_colors[li]);
3768 li += 1;
3769 }
3770 (ctx, cache)
3771 }
3772
3773 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
3774 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
3775 /// same way (lane-palette2 r1).
3776 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3777 self.record_palette_uv_rect(at, side, side, size, colors);
3778 }
3779
3780 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
3781 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
3782 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
3783 /// luma resolution regardless of which plane the recorded state is for).
3784 fn record_palette_uv_rect(
3785 &mut self,
3786 at: (usize, usize),
3787 w: usize,
3788 h: usize,
3789 size: usize,
3790 colors: [u16; 8],
3791 ) {
3792 let (r, c) = at;
3793 // See [`Self::record_palette_y_rect`] for the `.max(1)`.
3794 for cell in 0..(w / SUB).max(1) {
3795 self.above_palette_uv_size[c + cell] = size;
3796 self.above_palette_uv_colors[c + cell] = colors;
3797 }
3798 for cell in 0..(h / SUB).max(1) {
3799 self.left_palette_uv_size[r + cell] = size;
3800 self.left_palette_uv_colors[r + cell] = colors;
3801 }
3802 }
3803
3804 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
3805 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
3806 /// no neighbour lookup at all (it is this block's own just-decided Y
3807 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
3808 /// so only the cache is wanted here.
3809 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
3810 let (r, c) = at;
3811 let above_ok = r % 4 != 0;
3812 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
3813 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
3814 } else {
3815 (0, [0u16; 8])
3816 };
3817 // Same tile-relative left availability as the luma cache above.
3818 let left_ok = c > self.tile_col0_mi / (SUB / MI);
3819 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
3820 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
3821 } else {
3822 (0, [0u16; 8])
3823 };
3824 let mut cache = Vec::with_capacity(16);
3825 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3826 if cache.last() != Some(&v) {
3827 cache.push(v);
3828 }
3829 };
3830 let (mut ai, mut li) = (0usize, 0usize);
3831 while ai < above_n && li < left_n {
3832 let (va, vl) = (above_colors[ai], left_colors[li]);
3833 if vl < va {
3834 push_dedup(&mut cache, vl);
3835 li += 1;
3836 } else {
3837 push_dedup(&mut cache, va);
3838 ai += 1;
3839 if vl == va {
3840 li += 1;
3841 }
3842 }
3843 }
3844 while ai < above_n {
3845 push_dedup(&mut cache, above_colors[ai]);
3846 ai += 1;
3847 }
3848 while li < left_n {
3849 push_dedup(&mut cache, left_colors[li]);
3850 li += 1;
3851 }
3852 cache
3853 }
3854
3855 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
3856 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
3857 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
3858 /// units as [`Self::fill_skip_grid`].
3859 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
3860 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
3861 }
3862
3863 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
3864 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
3865 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
3866 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
3867 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
3868 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
3869 fn fill_lf_grid_rect(
3870 &mut self,
3871 at_mi: (usize, usize),
3872 w_mi: usize,
3873 h_mi: usize,
3874 tx_px: u8,
3875 tx_h_px: u8,
3876 ref_frame: i8,
3877 ) {
3878 let (mi_r, mi_c) = at_mi;
3879 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
3880 // half its luma one (min 4 px, the smallest transform), capped at
3881 // TX_32X32 -- independent of this block's luma `tx_depth`.
3882 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
3883 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
3884 let cur = CURRENT_DELTA_LF.with(|c| c.get());
3885 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
3886 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
3887 } else {
3888 [cur[0].clamp(-63, 63) as i8; 4]
3889 };
3890 for rr in 0..h_mi {
3891 for cc in 0..w_mi {
3892 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
3893 if let Some(cell) = self.tx_grid.get_mut(idx) {
3894 *cell = tx_px;
3895 }
3896 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
3897 *cell = tx_h_px;
3898 }
3899 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
3900 *cell = uv_tx_w;
3901 }
3902 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
3903 *cell = uv_tx_h;
3904 }
3905 if let Some(cell) = self.ref_grid.get_mut(idx) {
3906 *cell = ref_frame;
3907 }
3908 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
3909 *cell = snapshot;
3910 }
3911 }
3912 }
3913 }
3914
3915 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
3916 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
3917 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
3918 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
3919 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
3920 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
3921 }
3922
3923 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
3924 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
3925 let (mi_r, mi_c) = at_mi;
3926 for rr in 0..h_mi {
3927 for cc in 0..w_mi {
3928 if let Some(cell) = self
3929 .skip_grid
3930 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
3931 {
3932 *cell = skip;
3933 }
3934 }
3935 }
3936 }
3937
3938 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
3939 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
3940 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
3941 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
3942 /// straddle the region with a mix of skip/non-skip blocks).
3943 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
3944 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
3945 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
3946 /// filtered edge's two sides are each exactly one coded block wide.
3947 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
3948 self.skip_grid
3949 .get(mi_r * self.skip_grid_cols_mi + mi_c)
3950 .copied()
3951 .unwrap_or(false)
3952 }
3953
3954 /// The `skip_txfm` context of a block whose top-left mi cell is
3955 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
3956 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
3957 /// with an absent neighbour contributing 0. The mi grid is per tile, so
3958 /// row/column 0 is a tile edge and has no neighbour on that axis.
3959 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
3960 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
3961 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
3962 }
3963
3964 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
3965 (0..2).all(|rr| {
3966 (0..2).all(|cc| {
3967 self.skip_grid
3968 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
3969 .copied()
3970 .unwrap_or(false)
3971 })
3972 })
3973 }
3974
3975 fn start_row(&mut self) {
3976 self.left.iter_mut().for_each(|l| *l = Default::default());
3977 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
3978 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
3979 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3980 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3981 self.left_skip.iter_mut().for_each(|s| *s = false);
3982 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
3983 self.left_inter.iter_mut().for_each(|i| *i = false);
3984 self.left_ref.iter_mut().for_each(|r| *r = -1);
3985 self.left_ref1.iter_mut().for_each(|r| *r = None);
3986 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
3987 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
3988 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
3989 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
3990 // context (a tile/SB-row boundary has no left neighbour).
3991 self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
3992 self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
3993 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
3994 // are per-mi maps like every other one here, so they reset with the
3995 // row too -- the left guard above is what actually stops a cross-tile
3996 // read, this keeps a stale colour out of the arrays at all.
3997 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
3998 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
3999 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
4000 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
4001 }
4002
4003 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
4004 /// block that reads it as a neighbour -- [`crate::tile`]'s
4005 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
4006 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
4007 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
4008 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
4009 /// the real value, not just `is_inter`).
4010 fn record_inter(
4011 &mut self,
4012 at: (usize, usize),
4013 side: usize,
4014 skip: bool,
4015 is_inter: bool,
4016 ref_frame: i8,
4017 filter: [u8; 2],
4018 skip_mode: bool,
4019 ) {
4020 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
4021 }
4022
4023 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
4024 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
4025 /// r1: a true rectangular strip's above-context span (its own width) and
4026 /// left-context span (its own height) differ, unlike every caller before
4027 /// this round (class neighbour-votes-all-its-fields).
4028 #[allow(clippy::too_many_arguments)]
4029 fn record_inter_rect(
4030 &mut self,
4031 at: (usize, usize),
4032 w_sub: usize,
4033 h_sub: usize,
4034 skip: bool,
4035 is_inter: bool,
4036 ref_frame: i8,
4037 filter: [u8; 2],
4038 skip_mode: bool,
4039 ) {
4040 let (r, c) = at;
4041 self.record_inter_rect_mi(
4042 (r * (SUB / MI), c * (SUB / MI)),
4043 w_sub / MI,
4044 h_sub / MI,
4045 skip,
4046 is_inter,
4047 ref_frame,
4048 filter,
4049 skip_mode,
4050 );
4051 }
4052
4053 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
4054 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
4055 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
4056 /// routes through the wrapper above.
4057 #[allow(clippy::too_many_arguments)]
4058 fn record_inter_rect_mi(
4059 &mut self,
4060 at_mi: (usize, usize),
4061 w_mi: usize,
4062 h_mi: usize,
4063 skip: bool,
4064 is_inter: bool,
4065 ref_frame: i8,
4066 filter: [u8; 2],
4067 skip_mode: bool,
4068 ) {
4069 let (r, c) = at_mi;
4070 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
4071 for cell in 0..w_mi {
4072 self.above_skip[c + cell] = skip;
4073 self.above_skip_mode[c + cell] = skip_mode;
4074 self.above_inter[c + cell] = is_inter;
4075 self.above_ref[c + cell] = ref_frame;
4076 // lane-av1comp: no caller of `record_inter` ever decodes a
4077 // compound block yet (see [`Self::above_ref1`]'s doc); the
4078 // parameter this becomes lands with `read_ref_frames`.
4079 self.above_ref1[c + cell] = None;
4080 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
4081 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
4082 // as `3`/`1` even though this block has no second reference.
4083 // `record_compound_ctx` overwrites this with the real bit for an
4084 // actual compound block's cells, called right after this one.
4085 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
4086 self.above_compound_idx[c + cell] = u8::from(altref);
4087 self.above_filter[c + cell] = filter;
4088 }
4089 for cell in 0..h_mi {
4090 self.left_skip[r + cell] = skip;
4091 self.left_skip_mode[r + cell] = skip_mode;
4092 self.left_inter[r + cell] = is_inter;
4093 self.left_ref[r + cell] = ref_frame;
4094 self.left_ref1[r + cell] = None;
4095 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
4096 self.left_compound_idx[r + cell] = u8::from(altref);
4097 self.left_filter[r + cell] = filter;
4098 }
4099 }
4100
4101 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
4102 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
4103 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
4104 /// `get_comp_index_context`) -- called right after `record_inter` for
4105 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
4106 /// stamps `above_ref1`/`left_ref1` with the block's real second
4107 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
4108 /// this is the one caller that actually knows it) -- so the next block's
4109 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
4110 /// neighbour instead of `record_inter`'s single-ref default.
4111 fn record_compound_ctx(
4112 &mut self,
4113 at: (usize, usize),
4114 side: usize,
4115 ref1: i8,
4116 comp_group_idx: u8,
4117 compound_idx: u8,
4118 ) {
4119 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
4120 }
4121
4122 /// [`Self::record_compound_ctx`] with independent above/left extents,
4123 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
4124 #[allow(clippy::too_many_arguments)]
4125 fn record_compound_ctx_rect(
4126 &mut self,
4127 at: (usize, usize),
4128 w_sub: usize,
4129 h_sub: usize,
4130 ref1: i8,
4131 comp_group_idx: u8,
4132 compound_idx: u8,
4133 ) {
4134 let (r, c) = at;
4135 self.record_compound_ctx_rect_mi(
4136 (r * (SUB / MI), c * (SUB / MI)),
4137 w_sub / MI,
4138 h_sub / MI,
4139 ref1,
4140 comp_group_idx,
4141 compound_idx,
4142 );
4143 }
4144
4145 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
4146 /// [`Self::record_inter_rect_mi`]).
4147 fn record_compound_ctx_rect_mi(
4148 &mut self,
4149 at_mi: (usize, usize),
4150 w_mi: usize,
4151 h_mi: usize,
4152 ref1: i8,
4153 comp_group_idx: u8,
4154 compound_idx: u8,
4155 ) {
4156 let (r, c) = at_mi;
4157 for cell in 0..w_mi {
4158 self.above_ref1[c + cell] = Some(ref1);
4159 self.above_comp_group_idx[c + cell] = comp_group_idx;
4160 self.above_compound_idx[c + cell] = compound_idx;
4161 }
4162 for cell in 0..h_mi {
4163 self.left_ref1[r + cell] = Some(ref1);
4164 self.left_comp_group_idx[r + cell] = comp_group_idx;
4165 self.left_compound_idx[r + cell] = compound_idx;
4166 }
4167 }
4168
4169 /// The context of a block's partition symbol: delegates to the mi-precise
4170 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
4171 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
4172 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
4173 /// only touches the finer mi arrays -- leaves them stale for the *next*
4174 /// sibling's own partition symbol.
4175 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
4176 let (r, c) = at;
4177 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
4178 }
4179
4180 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
4181 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
4182 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
4183 /// than the enclosing 16x16 slot's stale, shared state.
4184 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
4185 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
4186 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
4187 }
4188
4189 /// The gathered coded/DC-sign state of the blocks above and to the left
4190 /// of a block `side` samples across, per plane.
4191 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
4192 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
4193 }
4194
4195 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
4196 /// units, for the same reason [`Self::record_mi`] does.
4197 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
4198 let side_mi = side / MI;
4199 std::array::from_fn(|plane| {
4200 let mut above_coded = false;
4201 let mut left_coded = false;
4202 let mut vote = 0;
4203 for cell in 0..side_mi {
4204 let above = &self.above[mi_c + cell][plane];
4205 let left = &self.left[mi_r + cell][plane];
4206 above_coded |= above.level != 0;
4207 left_coded |= left.level != 0;
4208 vote += dc_vote(above.dc) + dc_vote(left.dc);
4209 }
4210 (above_coded, left_coded, vote)
4211 })
4212 }
4213
4214 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
4215 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
4216 /// extent pattern for a true rectangular strip's own coefficient context.
4217 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
4218 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
4219 }
4220
4221 /// [`Self::around_rect`] taking the block's position directly in 4x4
4222 /// mode-info units, mirroring [`Self::around_mi`].
4223 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
4224 let (w_mi, h_mi) = (w / MI, h / MI);
4225 std::array::from_fn(|plane| {
4226 let mut above_coded = false;
4227 let mut left_coded = false;
4228 let mut vote = 0;
4229 for cell in 0..w_mi {
4230 let above = &self.above[mi_c + cell][plane];
4231 above_coded |= above.level != 0;
4232 vote += dc_vote(above.dc);
4233 }
4234 for cell in 0..h_mi {
4235 let left = &self.left[mi_r + cell][plane];
4236 left_coded |= left.level != 0;
4237 vote += dc_vote(left.dc);
4238 }
4239 (above_coded, left_coded, vote)
4240 })
4241 }
4242
4243 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
4244 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
4245 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
4246 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
4247 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
4248 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
4249 /// is always 0, spec's `plane_bsize == tx_size` branch).
4250 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
4251 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
4252 }
4253
4254 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
4255 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
4256 /// context over `tx_size_wide` and the left one over `tx_size_high`.
4257 fn luma_skip_ctx_rect(
4258 &self,
4259 (mi_r, mi_c): (usize, usize),
4260 w_mi: usize,
4261 h_mi: usize,
4262 ) -> usize {
4263 let side_mi = w_mi;
4264 let mut top = 0u8;
4265 let mut left = 0u8;
4266 for cell in 0..w_mi {
4267 top |= self.above[mi_c + cell][0].level;
4268 }
4269 for cell in 0..h_mi {
4270 left |= self.left[mi_r + cell][0].level;
4271 }
4272 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
4273 if std::env::var_os("EC_AV1_TRACE").is_some() {
4274 eprintln!(
4275 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
4276 );
4277 }
4278 ctx
4279 }
4280
4281 /// Writes one coded block into every cell it covers, on both grids: the
4282 /// mode/side arrays up to `side`'s own width, and the coefficient-context
4283 /// arrays up to the true frame edge — the units past it are left at their
4284 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
4285 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
4286 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
4287 /// not from this block's own side).
4288 fn record(
4289 &mut self,
4290 at: (usize, usize),
4291 side: usize,
4292 mode: usize,
4293 uv_mode: usize,
4294 grids: &[Vec<i32>; 3],
4295 ) {
4296 self.record_rect(at, side, side, mode, uv_mode, grids);
4297 }
4298
4299 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
4300 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
4301 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
4302 /// spec's per-edge partition-context rule, so a true rectangular block
4303 /// naturally wants two different values here rather than one.
4304 /// Writes this block's luma `mode` into the mi-granular
4305 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
4306 /// position a *later* neighbour would read it from: the block's LAST mi
4307 /// row for every column it spans (what the block below reads via
4308 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
4309 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
4310 /// read these back, and only when the recorded position is exactly their
4311 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
4312 fn record_mode_mi(
4313 &mut self,
4314 mi_r: usize,
4315 mi_c: usize,
4316 mi_w: usize,
4317 mi_h: usize,
4318 mode: usize,
4319 ) {
4320 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
4321 for cell in 0..mi_w {
4322 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
4323 *slot = (last_r, mode);
4324 }
4325 }
4326 for cell in 0..mi_h {
4327 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
4328 *slot = (last_c, mode);
4329 }
4330 }
4331 }
4332
4333 /// The mi-exact above/left neighbour luma mode for a block whose top-left
4334 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
4335 /// mi position (then the coarse [`SUB`]-grid slot is right by
4336 /// construction). See [`Self::record_mode_mi`].
4337 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
4338 match self.sub8_mode_col.get(mi_c) {
4339 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m),
4340 _ => None,
4341 }
4342 }
4343
4344 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
4345 match self.sub8_mode_row.get(mi_r) {
4346 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m),
4347 _ => None,
4348 }
4349 }
4350
4351 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
4352 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
4353 fn record_uv_mode_mi(
4354 &mut self,
4355 mi_r: usize,
4356 mi_c: usize,
4357 mi_w: usize,
4358 mi_h: usize,
4359 uv_mode: usize,
4360 ) {
4361 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
4362 for cell in 0..mi_w {
4363 if let Some(slot) = self.uv_mode_col.get_mut(mi_c + cell) {
4364 *slot = (last_r, uv_mode);
4365 }
4366 }
4367 for cell in 0..mi_h {
4368 if let Some(slot) = self.uv_mode_row.get_mut(mi_r + cell) {
4369 *slot = (last_c, uv_mode);
4370 }
4371 }
4372 }
4373
4374 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
4375 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
4376 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
4377 /// block has recorded the exact neighbouring mi.
4378 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
4379 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
4380 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
4381 // array that `start_tile` does not clear, so a block on a tile's first
4382 // mi row used to read the uv_mode of the block above it in the tile
4383 // ABOVE and filter its chroma edge at that neighbour's strength
4384 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
4385 // at chroma (120, 32), the top-right tile's first block).
4386 let have_above = mi_r > self.tile_row0_mi;
4387 let have_left = mi_c > self.tile_col0_mi;
4388 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
4389 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
4390 {
4391 UV_TILE_EDGE_SUPPRESSED_HITS.with(|h| h.set(h.get() + 1));
4392 }
4393 let above = match self.uv_mode_col.get(mi_c) {
4394 Some(&(row, m)) if have_above && row == mi_r - 1 => m,
4395 _ if have_above => self.above_uv_mode[c],
4396 _ => DC_PRED,
4397 };
4398 let left = match self.uv_mode_row.get(mi_r) {
4399 Some(&(col, m)) if have_left && col == mi_c - 1 => m,
4400 _ if have_left => self.left_uv_mode[r],
4401 _ => DC_PRED,
4402 };
4403 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
4404 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
4405 // have been filtered at the wrong strength by the coarse map alone.
4406 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
4407 UV_MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
4408 }
4409 is_smooth_mode(above) || is_smooth_mode(left)
4410 }
4411
4412 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
4413 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
4414 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
4415 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
4416 /// holding an OLDER, larger block's mode -- it only ever recorded into the
4417 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
4418 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
4419 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
4420 /// a different CDF for the same mode value).
4421 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
4422 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
4423 /// only when `up_available` and `left_mbmi` only when `left_available`;
4424 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
4425 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
4426 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
4427 /// strip's mode as its "left neighbour" (measured on the band fixture at
4428 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
4429 fn modes_above_left_mi(
4430 &self,
4431 mi_r: usize,
4432 mi_c: usize,
4433 fallback: (usize, usize),
4434 ) -> (usize, usize) {
4435 let above = if mi_r > self.tile_row0_mi {
4436 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
4437 } else {
4438 DC_PRED
4439 };
4440 let left = if mi_c > self.tile_col0_mi {
4441 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
4442 } else {
4443 DC_PRED
4444 };
4445 (above, left)
4446 }
4447
4448 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
4449 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
4450 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
4451 /// per superblock row and never per tile, so the first block column of
4452 /// tile 2..N read the previous tile's mode as its left neighbour, and the
4453 /// above band survives across a tile ROW boundary the same way lane-mtfix's
4454 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
4455 /// `up_available`/`left_available` and uses DC_PRED otherwise
4456 /// ([`Self::modes_above_left_mi`]).
4457 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
4458 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4459 let (above, left) =
4460 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
4461 if above != self.above_mode[c] || left != self.left_mode[r] {
4462 MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
4463 }
4464 // A neighbour the coarse band offered where the tile edge makes it
4465 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
4466 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
4467 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
4468 {
4469 MODE_TILE_EDGE_COARSE_LEAKS.with(|h| h.set(h.get() + 1));
4470 }
4471 (above, left)
4472 }
4473
4474 fn record_rect(
4475 &mut self,
4476 at: (usize, usize),
4477 w: usize,
4478 h: usize,
4479 mode: usize,
4480 uv_mode: usize,
4481 grids: &[Vec<i32>; 3],
4482 ) {
4483 let (r, c) = at;
4484 for cell in 0..w / SUB {
4485 self.above_mode[c + cell] = mode;
4486 self.above_uv_mode[c + cell] = uv_mode;
4487 self.above_side[c + cell] = w;
4488 }
4489 for cell in 0..h / SUB {
4490 self.left_mode[r + cell] = mode;
4491 self.left_uv_mode[r + cell] = uv_mode;
4492 self.left_side[r + cell] = h;
4493 }
4494 self.record_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, mode);
4495 self.record_uv_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, uv_mode);
4496 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
4497 }
4498
4499 /// The coefficient-context half of [`Self::record`], taking the block's
4500 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
4501 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
4502 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
4503 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
4504 self.record_mi_rect(at_mi, side, side, grids);
4505 }
4506
4507 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
4508 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
4509 fn record_mi_rect(
4510 &mut self,
4511 at_mi: (usize, usize),
4512 w: usize,
4513 h: usize,
4514 grids: &[Vec<i32>; 3],
4515 ) {
4516 let (mi_r, mi_c) = at_mi;
4517 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
4518 let (w_mi, h_mi) = (w / MI, h / MI);
4519 for cell in 0..h_mi {
4520 self.left_side_mi[mi_r + cell] = h;
4521 }
4522 for cell in 0..w_mi {
4523 self.above_side_mi[mi_c + cell] = w;
4524 }
4525 // A chroma 4x4 unit straddling the true luma edge is still whole in
4526 // chroma's own halved grid, so libaom rounds the luma bound up to the
4527 // plane's own 4x4 unit before clamping a subsampled plane
4528 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
4529 let round_up_even = |n: usize| n.div_ceil(2) * 2;
4530 let bound_h = [
4531 self.mi_rows,
4532 round_up_even(self.mi_rows),
4533 round_up_even(self.mi_rows),
4534 ];
4535 let bound_w = [
4536 self.mi_cols,
4537 round_up_even(self.mi_cols),
4538 round_up_even(self.mi_cols),
4539 ];
4540 for cell in 0..h_mi {
4541 self.left[mi_r + cell] = std::array::from_fn(|plane| {
4542 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
4543 states[plane]
4544 } else {
4545 Default::default()
4546 }
4547 });
4548 }
4549 for cell in 0..w_mi {
4550 self.above[mi_c + cell] = std::array::from_fn(|plane| {
4551 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
4552 states[plane]
4553 } else {
4554 Default::default()
4555 }
4556 });
4557 }
4558 }
4559
4560 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
4561 /// inside a coded block whose luma transform is smaller than its own
4562 /// side (`TxMode::Select`): the real per-transform-unit coefficient
4563 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
4564 /// coarse per-block `tx_grid`/`fill_lf_grid` state
4565 /// [`Self::record_split_luma`] still writes once for the whole block.
4566 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
4567 /// the caller's own [`Self::record_split_luma`] call sets those once,
4568 /// at the block's own true side, not this TU's.
4569 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
4570 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
4571 }
4572
4573 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
4574 /// r1): the above context spans the unit's width, the left context its
4575 /// height, which for a square unit is the same loop it always was.
4576 fn record_mi_luma_rect(
4577 &mut self,
4578 (mi_r, mi_c): (usize, usize),
4579 w_px: usize,
4580 h_px: usize,
4581 grid: &[i32],
4582 ) {
4583 let state = neighbour_state(grid);
4584 for cell in 0..h_px / MI {
4585 if mi_r + cell < self.mi_rows {
4586 self.left[mi_r + cell][0] = state;
4587 }
4588 }
4589 for cell in 0..w_px / MI {
4590 if mi_c + cell < self.mi_cols {
4591 self.above[mi_c + cell][0] = state;
4592 }
4593 }
4594 }
4595
4596 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
4597 /// block whose luma was decoded as several transform units through
4598 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
4599 /// whole-block luma write -- everything [`Self::record`] does except
4600 /// plane 0, which is already correct per-TU by the time this runs.
4601 fn record_split_luma(
4602 &mut self,
4603 at: (usize, usize),
4604 side: usize,
4605 mode: usize,
4606 uv_mode: usize,
4607 chroma_grids: [&[i32]; 2],
4608 ) {
4609 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
4610 }
4611
4612 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
4613 /// extents in pixels (lane-rectsplit r1), the same relationship
4614 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
4615 /// luma transform split into several square units needs exactly this
4616 /// bookkeeping, at its own true rectangular extents.
4617 fn record_split_luma_rect(
4618 &mut self,
4619 at: (usize, usize),
4620 w: usize,
4621 h: usize,
4622 mode: usize,
4623 uv_mode: usize,
4624 chroma_grids: [&[i32]; 2],
4625 ) {
4626 let (r, c) = at;
4627 self.record_split_luma_rect_mi(
4628 (r * (SUB / MI), c * (SUB / MI)),
4629 w,
4630 h,
4631 mode,
4632 uv_mode,
4633 chroma_grids,
4634 );
4635 }
4636
4637 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
4638 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
4639 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
4640 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
4641 /// convention [`decode_block_rect4`] already established for 1:4 strips.
4642 fn record_split_luma_rect_mi(
4643 &mut self,
4644 at_mi: (usize, usize),
4645 w: usize,
4646 h: usize,
4647 mode: usize,
4648 uv_mode: usize,
4649 chroma_grids: [&[i32]; 2],
4650 ) {
4651 let (mi_r, mi_c) = at_mi;
4652 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
4653 for cell in 0..w.div_ceil(SUB) {
4654 self.above_mode[c + cell] = mode;
4655 self.above_uv_mode[c + cell] = uv_mode;
4656 self.above_side[c + cell] = w;
4657 }
4658 for cell in 0..h.div_ceil(SUB) {
4659 self.left_mode[r + cell] = mode;
4660 self.left_uv_mode[r + cell] = uv_mode;
4661 self.left_side[r + cell] = h;
4662 }
4663 let (w_mi, h_mi) = (w / MI, h / MI);
4664 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
4665 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
4666 for cell in 0..h_mi {
4667 self.left_side_mi[mi_r + cell] = h;
4668 }
4669 for cell in 0..w_mi {
4670 self.above_side_mi[mi_c + cell] = w;
4671 }
4672 let round_up_even = |n: usize| n.div_ceil(2) * 2;
4673 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
4674 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
4675 let plane = plane_idx + 1;
4676 let state = neighbour_state(grid);
4677 for cell in 0..h_mi {
4678 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
4679 self.left[mi_r + cell][plane] = state;
4680 }
4681 }
4682 for cell in 0..w_mi {
4683 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
4684 self.above[mi_c + cell][plane] = state;
4685 }
4686 }
4687 }
4688 }
4689}
4690
4691/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
4692/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
4693/// exactly — including its skip context, which the real key-frame writer
4694/// always writes at a fixed context of zero (it never tracks a neighbour-based
4695/// one for intra blocks; that is the inter-frame writer's rule instead).
4696/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
4697/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
4698/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
4699/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
4700/// plain DC chroma.
4701/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
4702/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
4703/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
4704/// instead (the defect commit 1a89ed9 fixed at the square sites).
4705fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
4706 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
4707 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
4708}
4709
4710/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
4711/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
4712/// bound (spec `filter_intra_mode_info` never reads a symbol there).
4713fn filter_intra_size_class(side: usize) -> Option<usize> {
4714 match side {
4715 4 => Some(0),
4716 8 => Some(1),
4717 16 => Some(2),
4718 32 => Some(3),
4719 _ => None,
4720 }
4721}
4722
4723/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
4724/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
4725/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
4726/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
4727fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
4728 match (bw, bh) {
4729 (32, 16) => Some(4),
4730 (16, 32) => Some(5),
4731 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
4732 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
4733 // here dropped that symbol on every DC_PRED strip of that size and
4734 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
4735 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
4736 (16, 8) => Some(6),
4737 (8, 16) => Some(7),
4738 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
4739 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
4740 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
4741 (4, 8) => Some(8),
4742 (8, 4) => Some(9),
4743 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
4744 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
4745 // `use_filter_intra` symbol on those strips although aomenc writes
4746 // one for every DC_PRED block of that shape with
4747 // `--enable-filter-intra=1` (its default), silently desyncing the
4748 // tile (class symbol-consumption-gap).
4749 (32, 8) => Some(10),
4750 (8, 32) => Some(11),
4751 _ if bw == bh => filter_intra_size_class(bw),
4752 _ => None,
4753 }
4754}
4755
4756/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
4757/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
4758/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
4759/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
4760/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
4761fn palette_bsize_ctx(side: usize) -> Option<usize> {
4762 palette_bsize_ctx_wh(side, side)
4763}
4764
4765/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
4766/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
4767/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
4768/// for ANY bsize, not just the square ones a hand-picked table happened to
4769/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
4770/// row breaks the moment its indexing field moves off the diagonal, and a
4771/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
4772/// block dimension is a power of two, so `bw*bh` always is too and
4773/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
4774/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
4775fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
4776 if !(8..=64).contains(&bw) || !(8..=64).contains(&bh) {
4777 return None;
4778 }
4779 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
4780}
4781
4782/// A just-decoded palette-Y block's own size, base colours (only the first
4783/// `size` entries are real), and per-pixel colour-index map (`side*side`,
4784/// row-major, each entry `< size`).
4785struct PaletteY {
4786 size: usize,
4787 colors: [u16; 8],
4788 map: Vec<u8>,
4789}
4790
4791/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
4792/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
4793/// shared between U and V, both co-located after 4:2:0 subsampling) plus
4794/// each plane's own base colours.
4795struct PaletteUv {
4796 size: usize,
4797 u_colors: [u16; 8],
4798 v_colors: [u16; 8],
4799 map: Vec<u8>,
4800}
4801
4802/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
4803/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
4804/// `get_unsigned_bits`, which is the same formula): smallest `n` with
4805/// `2^n >= x`, `0` for `x <= 1`.
4806fn ceil_log2(x: u32) -> u32 {
4807 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
4808}
4809
4810/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
4811/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
4812fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
4813 let l = ceil_log2(n as u32);
4814 let m = (1usize << l) - n;
4815 let v = dec.literal(l - 1) as usize;
4816 if v < m {
4817 v
4818 } else {
4819 (v << 1) - m + dec.literal(1) as usize
4820 }
4821}
4822
4823/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
4824/// colours (already-known, from the above/left neighbours) with the
4825/// ascending `transmitted` ones (delta-coded off the wire) back into one
4826/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
4827/// value picks the cached copy first, matching the C `<=`.
4828fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
4829 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
4830 let (mut ci, mut ti) = (0, 0);
4831 while ci < cached.len() && ti < transmitted.len() {
4832 if cached[ci] <= transmitted[ti] {
4833 out.push(cached[ci]);
4834 ci += 1;
4835 } else {
4836 out.push(transmitted[ti]);
4837 ti += 1;
4838 }
4839 }
4840 out.extend_from_slice(&cached[ci..]);
4841 out.extend_from_slice(&transmitted[ti..]);
4842 out
4843}
4844
4845/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this
4846/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
4847/// (one flag bit each, in cache order), then delta-codes the remainder
4848/// (first value raw, each following delta `>= 1` off a shrinking bit width),
4849/// and merges the two ascending lists back together.
4850fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
4851 let mut cached = Vec::with_capacity(n);
4852 for &c in cache {
4853 if cached.len() >= n {
4854 break;
4855 }
4856 if dec.literal(1) == 1 {
4857 cached.push(c);
4858 }
4859 }
4860 let mut colors = [0u16; 8];
4861 let n_cached = cached.len();
4862 if n_cached < n {
4863 let mut transmitted = Vec::with_capacity(n - n_cached);
4864 let first = dec.literal(8) as u16;
4865 transmitted.push(first);
4866 if n_cached + 1 < n {
4867 let min_bits = 8u32 - 3;
4868 let mut bits = min_bits + dec.literal(2);
4869 let mut range = 255i32 - i32::from(first) - 1;
4870 for _ in (n_cached + 1)..n {
4871 let delta = dec.literal(bits) as i32 + 1;
4872 let prev = *transmitted.last().unwrap();
4873 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
4874 range -= i32::from(val) - i32::from(prev);
4875 bits = bits.min(ceil_log2(range.max(0) as u32));
4876 transmitted.push(val);
4877 }
4878 }
4879 let merged = merge_colors(&transmitted, &cached);
4880 colors[..n].copy_from_slice(&merged);
4881 } else {
4882 colors[..n].copy_from_slice(&cached[..n]);
4883 }
4884 colors
4885}
4886
4887/// `read_palette_colors_uv` (decodemv.c:509), bit_depth fixed at 8: U reads
4888/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
4889/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
4890/// unbiased by `+1` -- both differences from Y's own reader, matching the C
4891/// side by side). V never uses a cache: a leading bit picks either `n` raw
4892/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
4893/// rather than clamp.
4894fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
4895 let mut cached = Vec::with_capacity(n);
4896 for &c in cache {
4897 if cached.len() >= n {
4898 break;
4899 }
4900 if dec.literal(1) == 1 {
4901 cached.push(c);
4902 }
4903 }
4904 let mut u_colors = [0u16; 8];
4905 let n_cached = cached.len();
4906 if n_cached < n {
4907 let mut transmitted = Vec::with_capacity(n - n_cached);
4908 let first = dec.literal(8) as u16;
4909 transmitted.push(first);
4910 if n_cached + 1 < n {
4911 let min_bits = 8u32 - 3;
4912 let mut bits = min_bits + dec.literal(2);
4913 let mut range = 255i32 - i32::from(first);
4914 for _ in (n_cached + 1)..n {
4915 let delta = dec.literal(bits) as i32;
4916 let prev = *transmitted.last().unwrap();
4917 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
4918 range -= i32::from(val) - i32::from(prev);
4919 bits = bits.min(ceil_log2(range.max(0) as u32));
4920 transmitted.push(val);
4921 }
4922 }
4923 let merged = merge_colors(&transmitted, &cached);
4924 u_colors[..n].copy_from_slice(&merged);
4925 } else {
4926 u_colors[..n].copy_from_slice(&cached[..n]);
4927 }
4928 let mut v_colors = [0u16; 8];
4929 if dec.literal(1) == 1 {
4930 let min_bits_v = 8u32 - 4;
4931 let bits = min_bits_v + dec.literal(2);
4932 v_colors[0] = dec.literal(8) as u16;
4933 for i in 1..n {
4934 let mut delta = dec.literal(bits) as i32;
4935 if delta != 0 && dec.literal(1) == 1 {
4936 delta = -delta;
4937 }
4938 let mut val = i32::from(v_colors[i - 1]) + delta;
4939 if val < 0 {
4940 val += 256;
4941 }
4942 if val >= 256 {
4943 val -= 256;
4944 }
4945 v_colors[i] = val as u16;
4946 }
4947 } else {
4948 for i in 0..n {
4949 v_colors[i] = dec.literal(8) as u16;
4950 }
4951 }
4952 (u_colors, v_colors)
4953}
4954
4955/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
4956/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
4957/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
4958const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
4959
4960/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
4961/// map's own per-pixel context and colour-order permutation, from the
4962/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
4963/// selection sort). `map`'s stride is `side` (this decoder never crops a
4964/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
4965/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
4966/// actual colour index to store.
4967fn palette_color_index_context(
4968 map: &[u8],
4969 side: usize,
4970 row: usize,
4971 col: usize,
4972 n: usize,
4973) -> (usize, [u8; 8]) {
4974 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
4975 let up_left = if col >= 1 && row >= 1 {
4976 Some(map[(row - 1) * side + col - 1])
4977 } else {
4978 None
4979 };
4980 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
4981 let mut scores = [0i32; 8];
4982 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
4983 if let Some(v) = neighbour {
4984 scores[v as usize] += weight;
4985 }
4986 }
4987 let mut color_order = [0u8; 8];
4988 for i in 0..8 {
4989 color_order[i] = i as u8;
4990 }
4991 for i in 0..3 {
4992 let mut max = scores[i];
4993 let mut max_idx = i;
4994 for j in (i + 1)..n {
4995 if scores[j] > max {
4996 max = scores[j];
4997 max_idx = j;
4998 }
4999 }
5000 if max_idx != i {
5001 let max_score = scores[max_idx];
5002 let max_color = color_order[max_idx];
5003 for k in (i + 1..=max_idx).rev() {
5004 scores[k] = scores[k - 1];
5005 color_order[k] = color_order[k - 1];
5006 }
5007 scores[i] = max_score;
5008 color_order[i] = max_color;
5009 }
5010 }
5011 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
5012 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
5013 (ctx as usize, color_order)
5014}
5015
5016/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
5017/// map's wavefront decode over a `side x side` grid -- this decoder's
5018/// palette blocks are always square and never straddle the frame's true
5019/// (possibly odd) edge without already allocating the full `side*side`
5020/// region (every other skip/residual path here does the same), so no
5021/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
5022/// libaom's own non-block-aligned split.
5023fn decode_color_index_map(
5024 dec: &mut SymbolDecoder,
5025 cdfs: &mut Cdfs,
5026 n: usize,
5027 side: usize,
5028 uv: bool,
5029) -> Vec<u8> {
5030 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
5031}
5032
5033/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
5034/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
5035/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
5036/// independently rather than one shared `side` -- the square call above is
5037/// just `bw == bh`.
5038fn decode_color_index_map_wh(
5039 dec: &mut SymbolDecoder,
5040 cdfs: &mut Cdfs,
5041 n: usize,
5042 bw: usize,
5043 bh: usize,
5044 uv: bool,
5045) -> Vec<u8> {
5046 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
5047 let mut map = vec![0u8; bw * bh];
5048 if trace {
5049 let (rng, _) = dec.debug_state();
5050 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
5051 }
5052 map[0] = read_uniform(dec, n) as u8;
5053 if trace {
5054 let (rng, _) = dec.debug_state();
5055 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
5056 }
5057 for i in 1..(bw + bh - 1) {
5058 let j_hi = i.min(bw - 1);
5059 let j_lo = i.saturating_sub(bh - 1);
5060 for j in (j_lo..=j_hi).rev() {
5061 let row = i - j;
5062 let col = j;
5063 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
5064 if trace {
5065 let (rng, _) = dec.debug_state();
5066 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
5067 }
5068 let symbol = if uv {
5069 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
5070 } else {
5071 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
5072 };
5073 map[row * bw + col] = color_order[symbol];
5074 if trace {
5075 let (rng, _) = dec.debug_state();
5076 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
5077 }
5078 }
5079 }
5080 map
5081}
5082
5083/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
5084/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
5085/// size class comes from [`filter_intra_size_class_rect`] instead of the
5086/// square-only [`filter_intra_size_class`], and the palette read (when
5087/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
5088/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
5089/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
5090/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
5091#[allow(clippy::too_many_arguments)]
5092fn read_intra_mode_rect(
5093 dec: &mut SymbolDecoder,
5094 cdfs: &mut Cdfs,
5095 above_mode: usize,
5096 left_mode: usize,
5097 cfl: bool,
5098 bw: usize,
5099 bh: usize,
5100 enable_filter_intra: bool,
5101 skip_ctx: usize,
5102 allow_screen_content_tools: bool,
5103 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
5104 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
5105 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
5106 palette: Option<(usize, &[u16])>,
5107 palette_uv_cache: &[u16],
5108 mi_r: usize,
5109 mi_c: usize,
5110) -> Result<(
5111 bool,
5112 usize,
5113 i32,
5114 usize,
5115 i32,
5116 Option<(i32, i32)>,
5117 Option<usize>,
5118 Option<PaletteY>,
5119 Option<PaletteUv>,
5120)> {
5121 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
5122 macro_rules! istep {
5123 ($name:literal, $val:expr) => {
5124 if ec_istep {
5125 let (rng, _) = dec.debug_state();
5126 eprintln!(
5127 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
5128 $name, $val
5129 );
5130 }
5131 };
5132 }
5133 // Same `intra_segment_id` placement as the square reader above.
5134 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
5135 if seg_id_pre_skip() {
5136 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
5137 }
5138 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
5139 istep!("skip", skip as i32);
5140 if !seg_id_pre_skip() {
5141 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
5142 }
5143 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
5144 istep!("cdef", 0);
5145 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
5146 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
5147 // `false`.
5148 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
5149 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
5150 istep!("dq", 0);
5151 let above_ctx = INTRA_MODE_CTX[above_mode];
5152 let left_ctx = INTRA_MODE_CTX[left_mode];
5153 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
5154 istep!("mode", mode as i32);
5155 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
5156 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
5157 } else {
5158 0
5159 };
5160 istep!("angle_y", angle_delta_y);
5161 let uv_mode = if cfl {
5162 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
5163 } else {
5164 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
5165 };
5166 istep!("uv_mode", uv_mode as i32);
5167 let alpha = if cfl && uv_mode == UV_CFL_PRED {
5168 Some(read_cfl_alphas(dec, cdfs))
5169 } else {
5170 None
5171 };
5172 if (9..=12).contains(&uv_mode) {
5173 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
5174 }
5175 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
5176 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
5177 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
5178 } else {
5179 0
5180 };
5181 istep!("angle_uv", angle_delta_uv);
5182 if angle_delta_uv != 0 {
5183 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
5184 }
5185 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
5186 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
5187 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
5188 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
5189 // colours only here, the colour-index maps deferred past `filter_intra`
5190 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
5191 // runs from the caller, after the whole mode-info read).
5192 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
5193 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
5194 if allow_screen_content_tools
5195 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
5196 {
5197 // r6: this is the exact site the removed blanket refusal used to
5198 // guard -- reached for EVERY rect strip in a screen-content frame,
5199 // independent of whether the block ends up using a palette.
5200 RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1));
5201 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
5202 let use_palette_y =
5203 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
5204 if use_palette_y {
5205 if palette.is_none() {
5206 return Err(unsupported(
5207 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
5208 ));
5209 }
5210 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
5211 let colors = read_palette_colors_y(dec, n, cache);
5212 palette_y_pending = Some((n, colors));
5213 }
5214 let palette_uv_mode_ctx = usize::from(use_palette_y);
5215 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
5216 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
5217 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
5218 palette_uv_pending = Some((n, u_colors, v_colors));
5219 }
5220 }
5221 let mut filter_intra = None;
5222 if std::env::var_os("EC_AV1_TRACE").is_some() {
5223 let (rng, _) = dec.debug_state();
5224 eprintln!(
5225 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
5226 class={:?} rng={rng}",
5227 enable_filter_intra as i32,
5228 filter_intra_size_class_rect(bw, bh)
5229 );
5230 }
5231 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
5232 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
5233 if mode == DC_PRED
5234 && enable_filter_intra
5235 && palette_y_pending.is_none()
5236 && let Some(class) = filter_intra_size_class_rect(bw, bh)
5237 {
5238 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
5239 if std::env::var_os("EC_AV1_TRACE").is_some() {
5240 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
5241 }
5242 if use_filter_intra {
5243 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
5244 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
5245 filter_intra = Some(fi_mode);
5246 }
5247 }
5248 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
5249 // same order as [`read_intra_mode`]'s own square path.
5250 let palette_y = palette_y_pending.map(|(n, colors)| {
5251 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
5252 PALETTE_HITS.with(|c| c.set(c.get() + 1));
5253 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
5254 PaletteY { size: n, colors, map }
5255 });
5256 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
5257 let map = decode_color_index_map_wh(dec, cdfs, n, bw / 2, bh / 2, true);
5258 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
5259 PaletteUv { size: n, u_colors, v_colors, map }
5260 });
5261 Ok((
5262 skip,
5263 mode,
5264 angle_delta_y,
5265 uv_mode,
5266 angle_delta_uv,
5267 alpha,
5268 filter_intra,
5269 palette_y,
5270 palette_uv,
5271 ))
5272}
5273
5274/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
5275/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
5276/// above against this block's own *width* and the neighbour to the left
5277/// against its own *height* -- for a square block those are the same value,
5278/// which is why the square-only version can get away with one `own_side`.
5279fn tx_size_context_rect(
5280 n: &Neighbours,
5281 (mi_r, mi_c): (usize, usize),
5282 own_w: usize,
5283 own_h: usize,
5284) -> usize {
5285 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
5286 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
5287 usize::from(above) + usize::from(left)
5288}
5289
5290/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
5291fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
5292 let (cw, ch) = (bw / 2, bh / 2);
5293 let mut ac = vec![0i32; cw * ch];
5294 let mut sum = 0i32;
5295 for cy in 0..ch {
5296 for cx in 0..cw {
5297 let (lx, ly) = (px + cx * 2, py + cy * 2);
5298 let q3 = (i32::from(y.data[ly * y.width + lx])
5299 + i32::from(y.data[ly * y.width + lx + 1])
5300 + i32::from(y.data[(ly + 1) * y.width + lx])
5301 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
5302 << 1;
5303 ac[cy * cw + cx] = q3;
5304 sum += q3;
5305 }
5306 }
5307 let num_pel = (cw * ch) as i32;
5308 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
5309 ac.iter_mut().for_each(|v| *v -= avg);
5310 ac
5311}
5312
5313/// Everything a rect strip already read out of the stream before its luma
5314/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
5315/// (nine values that would otherwise be nine more parameters).
5316struct RectStripModes {
5317 skip: bool,
5318 mode: usize,
5319 angle_delta_y: i32,
5320 uv_predict_mode: usize,
5321 angle_delta_uv: i32,
5322 alpha: Option<(i32, i32)>,
5323 filter_intra: Option<usize>,
5324 smooth_neighbor: bool,
5325 smooth_neighbor_uv: bool,
5326 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
5327 /// mapped through the colour table), sliced per transform unit below --
5328 /// palette prediction reads no edge pixels, so a unit's slice of the
5329 /// whole-block map IS its prediction. Without this a palette strip whose
5330 /// transform splits predicted DC and came out flat grey while the entropy
5331 /// stream stayed in sync (the coefficients are read either way).
5332 palette_y: Option<Vec<u16>>,
5333 /// As `palette_y`, for the un-split chroma transform (U, V).
5334 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
5335}
5336
5337/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
5338/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
5339/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
5340/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
5341/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
5342/// TX_32X16`) and only the second reaches a square -- the reason
5343/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
5344/// already square) mis-tiled 1:4 strips.
5345fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) {
5346 let (mut w, mut h) = (bw.min(64), bh.min(64));
5347 for _ in 0..depth {
5348 match w.cmp(&h) {
5349 std::cmp::Ordering::Greater => w /= 2,
5350 std::cmp::Ordering::Less => h /= 2,
5351 std::cmp::Ordering::Equal => {
5352 w /= 2;
5353 h /= 2;
5354 }
5355 }
5356 }
5357 (w, h)
5358}
5359
5360/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
5361/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
5362/// rect path here refused by name until now ("per-unit rect prediction is not
5363/// ported").
5364///
5365/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
5366/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
5367/// strip the very first step already lands on a SQUARE transform
5368/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
5369/// every further step halves a square) -- so each unit is square and reads
5370/// through the ordinary square [`read_plane`]. What is genuinely rectangular
5371/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
5372/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
5373/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
5374/// split by luma's depth.
5375///
5376/// Each unit predicts off whatever the earlier units of this same block
5377/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
5378/// inside `av1_foreach_transformed_block`, raster order), which is exactly
5379/// what predicting the whole strip in one shot got wrong.
5380#[allow(clippy::too_many_arguments)]
5381fn decode_rect_split(
5382 dec: &mut SymbolDecoder,
5383 cdfs: &mut Cdfs,
5384 neighbours: &mut Neighbours,
5385 at_mi: (usize, usize),
5386 bw: usize,
5387 bh: usize,
5388 // The transform unit's own width and height in pixels. Square for every
5389 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
5390 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
5391 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
5392 tx_w: usize,
5393 tx_h: usize,
5394 m: &RectStripModes,
5395 y: &mut PlaneBuf,
5396 u: &mut PlaneBuf,
5397 v: &mut PlaneBuf,
5398 base_q_idx: u8,
5399 reduced_tx_set: bool,
5400) -> Result<()> {
5401 let (mi_r, mi_c) = at_mi;
5402 let (px, py) = (mi_c * MI, mi_r * MI);
5403 let (cpx, cpy) = (px / 2, py / 2);
5404 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5405 // The chroma transform is picked before any symbol is read, so an
5406 // unsupported chroma shape refuses before this strip desyncs the tile.
5407 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
5408 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
5409 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
5410 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
5411 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
5412 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
5413 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
5414 // squares a rect transform down to a CDF set by
5415 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
5416 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
5417 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
5418 // paths already prove for these same shapes.
5419 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
5420 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
5421 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
5422 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
5423 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
5424 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
5425 _ => None,
5426 };
5427 if !m.skip {
5428 if let Some(i) = match (chroma_w, chroma_h) {
5429 (32, 8) => Some(0),
5430 (8, 32) => Some(1),
5431 (8, 4) => Some(2),
5432 (4, 8) => Some(3),
5433 _ => None,
5434 } {
5435 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
5436 let mut hits = c.get();
5437 hits[i] += 1;
5438 c.set(hits);
5439 });
5440 }
5441 if chroma.is_none() {
5442 // Diagnostic for the next caller that lands here (class
5443 // refusal-names-a-correlate: the message names the tool, not the
5444 // shape); the refusal below keeps its inventory-pinned wording.
5445 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
5446 }
5447 }
5448 // lane-rectsplit r2 (verifier finding): with both callers wired
5449 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
5450 // 64x32/32x64) every shape that reaches here has a table above, so this
5451 // arm is UNREACHABLE today. It stays as the shape guard for the next
5452 // caller -- a new strip size would otherwise hit the `expect` below and
5453 // panic instead of refusing by name -- and so stays in
5454 // `refusal_inventory::REFUSALS`.
5455 if !m.skip && chroma.is_none() {
5456 return Err(unsupported(
5457 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
5458 ));
5459 }
5460 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
5461 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
5462 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1));
5463 }
5464 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
5465 // A square unit reads through the ordinary square [`read_plane`]; a rect
5466 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
5467 // the very tables the unsplit 16x8/32x16 paths use.
5468 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
5469 (w, h) if w == h => None,
5470 (16, 8) | (8, 16) => Some((
5471 if reduced_tx_set {
5472 TxbSet::LumaRect16x8
5473 } else {
5474 TxbSet::LumaRect16x8Set1
5475 },
5476 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
5477 )),
5478 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
5479 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
5480 _ => {
5481 return Err(unsupported(format!(
5482 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
5483 coefficient tables for that shape here)"
5484 )))
5485 }
5486 };
5487 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
5488 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
5489 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
5490 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
5491 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
5492 // per-unit rect walk stay wired above/below; the round that finds that
5493 // defect deletes this refusal and nothing else.
5494 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
5495 let luma_scan = default_scan(tx_w.min(tx_h));
5496 let zero_tu = vec![0i32; tx_w * tx_h];
5497 // The strip's OWN edge availability, the fallback for a transform unit
5498 // whose top-right/bottom-left pixels fall outside the strip.
5499 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5500 for tu_row in 0..bh / tx_h {
5501 for tu_col in 0..bw / tx_w {
5502 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
5503 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
5504 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
5505 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
5506 // transform unit INSIDE a block, which is a different rule from
5507 // the standalone-block table [`Reach::of`] applies -- and the
5508 // reason a depth-2 superblock strip came out one sample off
5509 // before this: `Reach::of(tx, ..)` answered as if the unit were
5510 // its own block at that superblock position.
5511 // * top-right: if the unit's right neighbour is still inside the
5512 // strip the pixels are already reconstructed (`col_off +
5513 // tx_wide < plane_bw`); otherwise only the strip's own top row
5514 // of units can reach past it, through the block-level answer.
5515 // * bottom-left: a unit that is not in the strip's left column
5516 // has none (`col_off > 0` returns 0); inside the strip
5517 // (`row_off + tx_high < plane_bh`) they are the left
5518 // neighbour's, already reconstructed; the last row falls back
5519 // to the block-level answer.
5520 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
5521 // The unit's own window on the block's palette prediction.
5522 if let Some(buf) = &m.palette_y {
5523 let tu_buf: Vec<u16> = (0..tx_h)
5524 .flat_map(|i| {
5525 let base = (row_off + i) * bw + col_off;
5526 buf[base..base + tx_w].iter().copied()
5527 })
5528 .collect();
5529 set_palette_pred(tu_buf);
5530 }
5531 if m.skip {
5532 y.reconstruct_rect(
5533 tu_px,
5534 tu_py,
5535 tx_w,
5536 tx_h,
5537 m.mode,
5538 m.angle_delta_y,
5539 tu_reach,
5540 &zero_tu,
5541 None,
5542 m.filter_intra,
5543 m.smooth_neighbor,
5544 );
5545 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
5546 } else if let Some((rect_set, rect_scan)) = luma_rect {
5547 // The rect-unit twin of the square arm below: same contexts,
5548 // same order, through the rect coefficient reader. The
5549 // `tx_type` CDF row of a filter-intra block is
5550 // `fimode_to_intradir[filter_intra_mode]`, never the block's
5551 // own (always DC_PRED) mode -- [`read_plane`] applies that
5552 // for the square arm, so this one must too.
5553 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
5554 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
5555 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
5556 let (tu_grid, tu_tx_type) = read_coeffs_rect(
5557 dec,
5558 &mut coding,
5559 rect_scan,
5560 tx_w,
5561 tx_h,
5562 tu_skip_ctx,
5563 dc_sign_ctx(tu_around.2),
5564 TxType::DctDct,
5565 )?;
5566 let residual = dequant_and_inverse_typed_wh(
5567 &tu_grid,
5568 tx_w,
5569 tx_h,
5570 crate::decode::bit_depth(),
5571 block_q_idx(),
5572 plane_q_delta(0).0,
5573 plane_q_delta(0).1,
5574 tu_tx_type,
5575 );
5576 y.reconstruct_rect(
5577 tu_px,
5578 tu_py,
5579 tx_w,
5580 tx_h,
5581 m.mode,
5582 m.angle_delta_y,
5583 tu_reach,
5584 &residual,
5585 None,
5586 m.filter_intra,
5587 m.smooth_neighbor,
5588 );
5589 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
5590 } else {
5591 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
5592 // This unit is smaller than the block it sits in, so
5593 // `txb_skip_ctx` is the neighbour-magnitude table, not the
5594 // lone-TU 0 (spec `get_txb_ctx_general`).
5595 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
5596 let tu_grid = read_plane(
5597 dec,
5598 cdfs,
5599 luma_set,
5600 &luma_scan,
5601 0,
5602 tu_around,
5603 m.mode,
5604 m.mode,
5605 m.angle_delta_y,
5606 tu_reach,
5607 y,
5608 tu_px,
5609 tu_py,
5610 tx_w,
5611 tx_w,
5612 base_q_idx,
5613 None,
5614 m.filter_intra,
5615 Some(tu_skip_ctx),
5616 m.smooth_neighbor,
5617 )?;
5618 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
5619 }
5620 }
5621 }
5622 // CHROMA: one un-split rect transform for the whole strip.
5623 let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5624 let reach = block_reach;
5625 let (u_grid, v_grid) = if m.skip {
5626 let zero = vec![0i32; chroma_w * chroma_h];
5627 if let Some((ub, _)) = &m.palette_uv {
5628 set_palette_pred(ub.clone());
5629 }
5630 u.reconstruct_rect(
5631 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
5632 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
5633 );
5634 if let Some((_, vb)) = &m.palette_uv {
5635 set_palette_pred(vb.clone());
5636 }
5637 v.reconstruct_rect(
5638 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
5639 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
5640 );
5641 (zero.clone(), zero)
5642 } else {
5643 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
5644 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
5645 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
5646 // so only the 16x8/8x16 pair takes the mode-indexed default.
5647 let default_tx = if chroma_w.max(chroma_h) >= 32 {
5648 TxType::DctDct
5649 } else {
5650 default_intra_tx_type(m.uv_predict_mode as u8)
5651 };
5652 let around = neighbours.around_mi_rect(at_mi, bw, bh);
5653 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
5654 for plane_idx in 1..=2 {
5655 let skip_ctx =
5656 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
5657 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
5658 let (levels, tx_type) = read_coeffs_rect(
5659 dec,
5660 &mut coding,
5661 chroma_scan,
5662 chroma_w,
5663 chroma_h,
5664 skip_ctx,
5665 dc_sign_ctx(around[plane_idx].2),
5666 default_tx,
5667 )?;
5668 // The same delta_q proof the unsplit rect64 path records
5669 // (lane-rectsplit r4: lifting the split-transform refusal moved
5670 // superblock strips onto this path, so only counting there would
5671 // leave the delta_q gate's counter silent for them).
5672 if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) {
5673 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
5674 }
5675 let residual = dequant_and_inverse_typed_wh(
5676 &levels,
5677 chroma_w,
5678 chroma_h,
5679 crate::decode::bit_depth(),
5680 CURRENT_Q_IDX.with(|c| c.get()),
5681 plane_q_delta(plane_idx).0,
5682 plane_q_delta(plane_idx).1,
5683 tx_type,
5684 );
5685 let cfl = m
5686 .alpha
5687 .zip(ac.as_deref())
5688 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
5689 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
5690 if let Some((ub, vb)) = &m.palette_uv {
5691 let buf = if plane_idx == 1 { ub } else { vb };
5692 set_palette_pred(buf.clone());
5693 }
5694 plane.reconstruct_rect(
5695 cpx,
5696 cpy,
5697 chroma_w,
5698 chroma_h,
5699 m.uv_predict_mode,
5700 m.angle_delta_uv,
5701 reach,
5702 &residual,
5703 cfl,
5704 None,
5705 m.smooth_neighbor_uv,
5706 );
5707 grids.push(levels);
5708 }
5709 let mut it = grids.into_iter();
5710 (it.next().unwrap(), it.next().unwrap())
5711 };
5712 neighbours.record_split_luma_rect_mi(
5713 at_mi,
5714 bw,
5715 bh,
5716 m.mode,
5717 m.uv_predict_mode,
5718 [&u_grid, &v_grid],
5719 );
5720 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
5721 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
5722 if std::env::var_os("EC_AV1_TRACE").is_some() {
5723 let (rng, _) = dec.debug_state();
5724 eprintln!(
5725 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
5726 tx={tx_w}x{tx_h} rng={rng}"
5727 );
5728 }
5729 Ok(())
5730}
5731
5732/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
5733/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
5734/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
5735/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
5736/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
5737/// has no rectangular-transform coefficient reader, and a chroma plane here
5738/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
5739/// with no depth-based square-tiling escape the way luma's own resolved
5740/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
5741/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
5742#[allow(clippy::too_many_arguments)]
5743fn decode_block_rect(
5744 dec: &mut SymbolDecoder,
5745 cdfs: &mut Cdfs,
5746 neighbours: &mut Neighbours,
5747 at: (usize, usize),
5748 bw: usize,
5749 bh: usize,
5750 y: &mut PlaneBuf,
5751 u: &mut PlaneBuf,
5752 v: &mut PlaneBuf,
5753 enable_filter_intra: bool,
5754 allow_screen_content_tools: bool,
5755 base_q_idx: u8,
5756 tx_select: bool,
5757 reduced_tx_set: bool,
5758) -> Result<()> {
5759 let (r, c) = at;
5760 let (px, py) = (c * SUB, r * SUB);
5761 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
5762 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
5763 let palette_uv_cache = neighbours.palette_uv_cache(at);
5764 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
5765 read_intra_mode_rect(
5766 dec,
5767 cdfs,
5768 nb_above_mode,
5769 nb_left_mode,
5770 true,
5771 bw,
5772 bh,
5773 enable_filter_intra,
5774 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
5775 allow_screen_content_tools,
5776 Some((palette_ctx, &palette_cache)),
5777 &palette_uv_cache,
5778 r * (SUB / MI),
5779 c * (SUB / MI),
5780 )?;
5781 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
5782 if smooth_neighbor {
5783 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5784 }
5785 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
5786 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
5787 // `uv_mode`, not the luma one.
5788 let smooth_neighbor_uv =
5789 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
5790 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
5791 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
5792 // rectangle just as happily), so a `use_filter_intra` strip at this level
5793 // predicts instead of refusing. The below-16x16 leaf arm
5794 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
5795 if filter_intra.is_some() {
5796 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
5797 }
5798 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
5799 DC_PRED
5800 } else {
5801 uv_mode
5802 };
5803 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5804 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
5805 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
5806 // one did not, so with `--enable-tx-size-search=0` -- which several gate
5807 // recipes use -- the decoder consumed a symbol the encoder never wrote and
5808 // desynced the tile from that point on. That is why both strips of the
5809 // pinned HORZ quadrant were wrong from their very first pixel, and why our
5810 // range after the read equalled the oracle's range for the whole block.
5811 let depth = if tx_select {
5812 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
5813 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
5814 } else {
5815 0
5816 };
5817 if depth != 0 {
5818 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
5819 // lane-rectsplit r1: a split transform is predicted and reconstructed
5820 // per transform unit, each unit taking its edges from the previous
5821 // unit's reconstruction inside this same strip (spec 5.11.36) --
5822 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
5823 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
5824 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
5825 eprintln!(
5826 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
5827 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
5828 angle_y={angle_delta_y}"
5829 );
5830 }
5831 let modes = RectStripModes {
5832 skip,
5833 mode,
5834 angle_delta_y,
5835 uv_predict_mode,
5836 angle_delta_uv,
5837 alpha,
5838 filter_intra,
5839 smooth_neighbor,
5840 smooth_neighbor_uv,
5841 palette_y: palette_y
5842 .as_ref()
5843 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
5844 palette_uv: palette_uv.as_ref().map(|p| {
5845 (
5846 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
5847 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
5848 )
5849 }),
5850 };
5851 if palette_y.is_some() || palette_uv.is_some() {
5852 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
5853 }
5854 decode_rect_split(
5855 dec,
5856 cdfs,
5857 neighbours,
5858 (mi_r, mi_c),
5859 bw,
5860 bh,
5861 tx_w,
5862 tx_h,
5863 &modes,
5864 y,
5865 u,
5866 v,
5867 base_q_idx,
5868 reduced_tx_set,
5869 )?;
5870 // This early return skips this fn's own tail, so the palette
5871 // neighbour state has to be stamped HERE too: without it a split-tx
5872 // strip left the above/left palette arrays holding a DEAD block's
5873 // colours, and the next block's colour cache
5874 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
5875 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
5876 // and only those pixels were wrong (lane-palette2 r10).
5877 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
5878 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
5879 let (puv_size, puv_colors) =
5880 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
5881 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
5882 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
5883 return Ok(());
5884 }
5885 let (tx_w, tx_h) = (bw, bh);
5886 let (cpx, cpy) = (px / 2, py / 2);
5887 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5888 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5889 if std::env::var_os("EC_AV1_TRACE").is_some() {
5890 let (rng, _) = dec.debug_state();
5891 eprintln!(
5892 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
5893 skip={} tx={depth} rng={rng}",
5894 skip as i32
5895 );
5896 }
5897 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
5898 // block's prediction is the reconstructed colour-index map, set fresh
5899 // right before each `reconstruct_rect` call below (lane-palette2 r4).
5900 if let Some(ref pyv) = palette_y {
5901 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
5902 set_palette_pred(buf);
5903 }
5904 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
5905 (
5906 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
5907 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
5908 )
5909 });
5910 if skip {
5911 y.reconstruct_rect(
5912 px,
5913 py,
5914 bw,
5915 bh,
5916 mode,
5917 angle_delta_y,
5918 reach,
5919 &vec![0i32; bw * bh],
5920 None,
5921 filter_intra,
5922 smooth_neighbor,
5923 );
5924 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5925 if let Some((ub, _)) = &palette_uv_bufs {
5926 set_palette_pred(ub.clone());
5927 }
5928 u.reconstruct_rect(
5929 cpx,
5930 cpy,
5931 chroma_w,
5932 chroma_h,
5933 uv_predict_mode,
5934 angle_delta_uv,
5935 reach,
5936 &vec![0i32; chroma_w * chroma_h],
5937 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5938 None,
5939 smooth_neighbor_uv,
5940 );
5941 if let Some((_, vb)) = &palette_uv_bufs {
5942 set_palette_pred(vb.clone());
5943 }
5944 v.reconstruct_rect(
5945 cpx,
5946 cpy,
5947 chroma_w,
5948 chroma_h,
5949 uv_predict_mode,
5950 angle_delta_uv,
5951 reach,
5952 &vec![0i32; chroma_w * chroma_h],
5953 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5954 None,
5955 smooth_neighbor_uv,
5956 );
5957 neighbours.record_rect(
5958 at,
5959 bw,
5960 bh,
5961 mode,
5962 uv_predict_mode,
5963 &[
5964 vec![0i32; bw * bh],
5965 vec![0i32; chroma_w * chroma_h],
5966 vec![0i32; chroma_w * chroma_h],
5967 ],
5968 );
5969 } else {
5970 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
5971 // reduces both size pairs to their square-up CDF sets
5972 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
5973 // doc comments); the scan order and 2D context tables are the real
5974 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
5975 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
5976 (&SCAN_32X16, &SCAN_16X8)
5977 } else {
5978 (&SCAN_16X32, &SCAN_8X16)
5979 };
5980 // lane-rectwire r3: real coefficients desync a pixel-exact gate
5981 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
5982 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
5983 // pixel (not a subtle context-table off-by-one), while the sibling
5984 // non-rect quadrants of the same frame match. Range-ladder bisection
5985 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
5986 // but the intra key-frame path has no traced symbol between the
5987 // partition read and the first coefficient block (mode/skip/tx_depth
5988 // reads are all untraced in libaom's decodeframe.c intra path, unlike
5989 // the inter EC_TRACE_MODE this round added), so a same-length range
5990 // comparison wasn't reachable within budget -- see
5991 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
5992 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
5993 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
5994 // libaom and match). lane-rectwire r4: range-ladder against the
5995 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
5996 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
5997 // both confirmed in sync -- rng=58692 on both sides right after
5998 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
5999 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
6000 // immediately after: ours moves rng 58692 -> 43570, which cannot be
6001 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
6002 // its own tx_size read) unless oracle's tx symbol is a near-certainty
6003 // CDF that barely narrows the range -- i.e. this decoder's
6004 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
6005 // a 32x16/16x32 strip is the first diverging symbol, not the
6006 // coefficient-context math r3 already cleared. Not confirmed byte-
6007 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
6008 // `read_tx_size`'s own rng, not attempted this round -- budget), so
6009 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
6010 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
6011 // it unconditionally where both square paths gate on `tx_select`. With
6012 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
6013 // decoder consumed one that was never there.
6014 {
6015 let around = neighbours.around_rect(at, bw, bh);
6016 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
6017 let (luma_levels, luma_tx_type) = read_coeffs_rect(
6018 dec,
6019 &mut luma_coding,
6020 luma_scan,
6021 bw,
6022 bh,
6023 0,
6024 dc_sign_ctx(around[0].2),
6025 TxType::DctDct,
6026 )?;
6027 if std::env::var_os("EC_AV1_TRACE").is_some() {
6028 let (rng, _) = dec.debug_state();
6029 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
6030 }
6031 let luma_residual = dequant_and_inverse_typed_wh(
6032 &luma_levels,
6033 bw,
6034 bh,
6035 crate::decode::bit_depth(),
6036 block_q_idx(),
6037 plane_q_delta(0).0,
6038 plane_q_delta(0).1,
6039 luma_tx_type,
6040 );
6041 y.reconstruct_rect(
6042 px,
6043 py,
6044 bw,
6045 bh,
6046 mode,
6047 angle_delta_y,
6048 reach,
6049 &luma_residual,
6050 None,
6051 filter_intra,
6052 smooth_neighbor,
6053 );
6054 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6055 if let Some((ub, _)) = &palette_uv_bufs {
6056 set_palette_pred(ub.clone());
6057 }
6058 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
6059 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
6060 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
6061 let (u_levels, u_tx_type) = read_coeffs_rect(
6062 dec,
6063 &mut u_coding,
6064 chroma_scan,
6065 chroma_w,
6066 chroma_h,
6067 u_skip_ctx,
6068 dc_sign_ctx(around[1].2),
6069 u_default_tx,
6070 )?;
6071 if std::env::var_os("EC_AV1_TRACE").is_some() {
6072 let (rng, _) = dec.debug_state();
6073 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
6074 }
6075 let u_residual = dequant_and_inverse_typed_wh(
6076 &u_levels,
6077 chroma_w,
6078 chroma_h,
6079 crate::decode::bit_depth(),
6080 block_q_idx(),
6081 plane_q_delta(1).0,
6082 plane_q_delta(1).1,
6083 u_tx_type,
6084 );
6085 u.reconstruct_rect(
6086 cpx,
6087 cpy,
6088 chroma_w,
6089 chroma_h,
6090 uv_predict_mode,
6091 angle_delta_uv,
6092 reach,
6093 &u_residual,
6094 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6095 None,
6096 smooth_neighbor_uv,
6097 );
6098 if let Some((_, vb)) = &palette_uv_bufs {
6099 set_palette_pred(vb.clone());
6100 }
6101 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
6102 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
6103 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
6104 let (v_levels, v_tx_type) = read_coeffs_rect(
6105 dec,
6106 &mut v_coding,
6107 chroma_scan,
6108 chroma_w,
6109 chroma_h,
6110 v_skip_ctx,
6111 dc_sign_ctx(around[2].2),
6112 v_default_tx,
6113 )?;
6114 if std::env::var_os("EC_AV1_TRACE").is_some() {
6115 let (rng, _) = dec.debug_state();
6116 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
6117 }
6118 let v_residual = dequant_and_inverse_typed_wh(
6119 &v_levels,
6120 chroma_w,
6121 chroma_h,
6122 crate::decode::bit_depth(),
6123 block_q_idx(),
6124 plane_q_delta(2).0,
6125 plane_q_delta(2).1,
6126 v_tx_type,
6127 );
6128 v.reconstruct_rect(
6129 cpx,
6130 cpy,
6131 chroma_w,
6132 chroma_h,
6133 uv_predict_mode,
6134 angle_delta_uv,
6135 reach,
6136 &v_residual,
6137 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6138 None,
6139 smooth_neighbor_uv,
6140 );
6141 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
6142 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
6143 }
6144 }
6145 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
6146 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
6147 let (puv_size, puv_colors) =
6148 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
6149 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
6150 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
6151 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
6152 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
6153 if std::env::var_os("EC_AV1_TRACE").is_some() {
6154 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
6155 }
6156 Ok(())
6157}
6158
6159/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
6160/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
6161/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
6162/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
6163/// the second strip of a HORZ/VERT split sits offset by half the 16x16
6164/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
6165/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
6166/// previous strip is directly above (same column, `mi_h` rows up) or
6167/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
6168/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
6169/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
6170/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
6171/// this strip's real position, never the coarse `record_rect` (which the
6172/// caller uses once, after both strips, exactly like the `VERT_B` arm next
6173/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
6174/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
6175/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
6176/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
6177#[allow(clippy::too_many_arguments)]
6178fn decode_leaf_rect(
6179 dec: &mut SymbolDecoder,
6180 cdfs: &mut Cdfs,
6181 neighbours: &mut Neighbours,
6182 outer_at: (usize, usize),
6183 leaf_mi: (usize, usize),
6184 bw: usize,
6185 bh: usize,
6186 prev_leaf: Option<((usize, usize), usize)>,
6187 y: &mut PlaneBuf,
6188 u: &mut PlaneBuf,
6189 v: &mut PlaneBuf,
6190 enable_filter_intra: bool,
6191 allow_screen_content_tools: bool,
6192 base_q_idx: u8,
6193 tx_select: bool,
6194 reduced_tx_set: bool,
6195) -> Result<usize> {
6196 let _ = base_q_idx;
6197 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
6198 eprintln!(
6199 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
6200 dec.debug_state().0
6201 );
6202 }
6203 let (r, c) = outer_at;
6204 let mut above_mode = neighbours.above_mode[c];
6205 let mut left_mode = neighbours.left_mode[r];
6206 let (mi_w, mi_h) = (bw / MI, bh / MI);
6207 if let Some(((pr, pc), pmode)) = prev_leaf {
6208 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
6209 above_mode = pmode;
6210 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
6211 left_mode = pmode;
6212 }
6213 }
6214 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
6215 // cannot hold the modes a split (or a pair of strips) leaves behind, so
6216 // when the map holds the block at exactly this strip's above/left mi it
6217 // is the neighbour libaom's `above_mi`/`left_mi` reads.
6218 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
6219 // availability-correct -- four 16x8 strips share one coarse 16x16
6220 // `left_mode` cell too, so the fallback must not stand in for an absent
6221 // tile-edge neighbour.
6222 let (above_mode, left_mode) =
6223 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
6224 let smooth_neighbor =
6225 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
6226 if smooth_neighbor {
6227 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6228 }
6229 // The palette-Y mode CDF row is picked by the neighbours' palette use
6230 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
6231 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
6232 // a palette narrows the wrong interval and desyncs the tile even when the
6233 // decoded bit is the same. The cell is the 16px-SUB cell containing the
6234 // leaf (the palette neighbour arrays have no finer granularity).
6235 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
6236 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(pal_at);
6237 let palette_uv_cache = neighbours.palette_uv_cache(pal_at);
6238 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
6239 read_intra_mode_rect(
6240 dec,
6241 cdfs,
6242 above_mode,
6243 left_mode,
6244 true,
6245 bw,
6246 bh,
6247 enable_filter_intra,
6248 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
6249 allow_screen_content_tools,
6250 Some((palette_ctx, &palette_cache)),
6251 &palette_uv_cache,
6252 leaf_mi.0,
6253 leaf_mi.1,
6254 )?;
6255 if palette_y.is_some() || palette_uv.is_some() {
6256 // Symbols (mode/size/colours/index map) are all read above, so the
6257 // tile stays in sync; only the *pixel* reconstruction of a palette on
6258 // a below-16x16 strip is unported and ungated (lane-palette2 r7).
6259 return Err(unsupported(
6260 "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)",
6261 ));
6262 }
6263 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
6264 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
6265 }
6266 if filter_intra.is_some() {
6267 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
6268 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
6269 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
6270 // below already makes; this refusal was square-only prose.
6271 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
6272 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.set(c.get() + 1));
6273 }
6274 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
6275 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
6276 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
6277 // a constant `false`.
6278 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
6279 let depth = if tx_select {
6280 let ctx = tx_size_context_rect(neighbours, leaf_mi, bw, bh);
6281 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
6282 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
6283 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
6284 // count (3), different CDF row: a wrong-table read of a real symbol,
6285 // the class that cost lane-rectsplit r1 its 64x32 depth.
6286 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
6287 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
6288 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
6289 // function also decodes) sit at depth 2, so they read
6290 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
6291 // while `tx_size_cat2` belongs to the 32-level shapes
6292 // ([`decode_block_rect`]). Both tables carry three symbols, so the
6293 // wrong one decodes a plausible depth from the wrong probabilities:
6294 // the range diverges silently at the first such leaf and every later
6295 // symbol in the tile is read from the wrong place (class
6296 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
6297 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
6298 } else {
6299 0
6300 };
6301 if depth != 0 {
6302 // The same per-transform-unit walk the bigger strips take
6303 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
6304 // depth 2), addressed at this leaf's own mi position.
6305 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
6306 SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
6307 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
6308 let modes = RectStripModes {
6309 skip,
6310 mode,
6311 angle_delta_y,
6312 uv_predict_mode,
6313 angle_delta_uv,
6314 alpha,
6315 filter_intra,
6316 smooth_neighbor,
6317 // lane-rectsplitx r3: the split arm hard-coded `false` here while
6318 // the unsplit arm below passes the real neighbour answer -- chroma
6319 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
6320 smooth_neighbor_uv,
6321 // Both callers refuse a palette on this shape above (pixel
6322 // reconstruction is unported here), so the split units carry none.
6323 palette_y: None,
6324 palette_uv: None,
6325 };
6326 decode_rect_split(
6327 dec,
6328 cdfs,
6329 neighbours,
6330 leaf_mi,
6331 bw,
6332 bh,
6333 tx_w,
6334 tx_h,
6335 &modes,
6336 y,
6337 u,
6338 v,
6339 base_q_idx,
6340 reduced_tx_set,
6341 )?;
6342 return Ok(mode);
6343 }
6344 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
6345 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6346 let (cpx, cpy) = (px / 2, py / 2);
6347 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
6348 let (luma_levels, u_levels, v_levels);
6349 if skip {
6350 luma_levels = vec![0i32; bw * bh];
6351 u_levels = vec![0i32; chroma_w * chroma_h];
6352 v_levels = vec![0i32; chroma_w * chroma_h];
6353 y.reconstruct_rect(
6354 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
6355 smooth_neighbor,
6356 );
6357 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6358 u.reconstruct_rect(
6359 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
6360 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
6361 );
6362 v.reconstruct_rect(
6363 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
6364 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
6365 );
6366 } else {
6367 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
6368 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
6369 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
6370 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
6371 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
6372 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
6373 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
6374 (&SCAN_16X8, &SCAN_8X4)
6375 } else {
6376 (&SCAN_8X16, &SCAN_4X8)
6377 };
6378 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
6379 let luma_set = if reduced_tx_set {
6380 TxbSet::LumaRect16x8
6381 } else {
6382 TxbSet::LumaRect16x8Set1
6383 };
6384 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
6385 let (l_levels, luma_tx_type) = read_coeffs_rect(
6386 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
6387 )?;
6388 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
6389 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
6390 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
6391 }
6392 luma_levels = l_levels;
6393 let luma_residual = dequant_and_inverse_typed_wh(
6394 &luma_levels, bw, bh, crate::decode::bit_depth(),
6395 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,
6396 );
6397 y.reconstruct_rect(
6398 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
6399 smooth_neighbor,
6400 );
6401 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6402 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
6403 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
6404 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
6405 let (u_l, u_tx_type) = read_coeffs_rect(
6406 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
6407 dc_sign_ctx(around[1].2), u_default_tx,
6408 )?;
6409 u_levels = u_l;
6410 let u_residual = dequant_and_inverse_typed_wh(
6411 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
6412 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,
6413 );
6414 u.reconstruct_rect(
6415 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
6416 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
6417 );
6418 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
6419 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
6420 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
6421 let (v_l, v_tx_type) = read_coeffs_rect(
6422 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
6423 dc_sign_ctx(around[2].2), v_default_tx,
6424 )?;
6425 v_levels = v_l;
6426 let v_residual = dequant_and_inverse_typed_wh(
6427 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
6428 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,
6429 );
6430 v.reconstruct_rect(
6431 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
6432 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
6433 );
6434 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
6435 }
6436 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
6437 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
6438 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
6439 // This leaf is necessarily non-palette (a palette one refused above), so
6440 // it must CLEAR the above/left palette state over its own span -- without
6441 // this the next block's `palette_y_mode` ctx and colour cache were read
6442 // off whatever block last covered the cell (lane-palette2 r8).
6443 neighbours.record_palette_y_rect(pal_at, bw, bh, 0, [0u16; 8]);
6444 neighbours.record_palette_uv_rect(pal_at, bw, bh, 0, [0u16; 8]);
6445 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
6446 // rows -- record the whole span, not one cell.
6447 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
6448 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
6449 Ok(mode)
6450}
6451
6452/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
6453/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
6454/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
6455/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
6456/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
6457/// strip's mode so this one's mode context sees its true above/left
6458/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
6459///
6460/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
6461/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
6462/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
6463/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
6464/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
6465/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
6466/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
6467///
6468/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
6469/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
6470/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
6471/// unexamined.
6472#[allow(clippy::too_many_arguments)]
6473fn decode_block_rect4(
6474 dec: &mut SymbolDecoder,
6475 cdfs: &mut Cdfs,
6476 neighbours: &mut Neighbours,
6477 strip_mi: (usize, usize),
6478 bw: usize,
6479 bh: usize,
6480 prev_strip: Option<((usize, usize), usize)>,
6481 y: &mut PlaneBuf,
6482 u: &mut PlaneBuf,
6483 v: &mut PlaneBuf,
6484 enable_filter_intra: bool,
6485 allow_screen_content_tools: bool,
6486 base_q_idx: u8,
6487 tx_select: bool,
6488) -> Result<(usize, usize)> {
6489 let _ = base_q_idx;
6490 let (mi_r, mi_c) = strip_mi;
6491 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
6492 let (mi_w, mi_h) = (bw / MI, bh / MI);
6493 let mut above_mode = neighbours.above_mode[c];
6494 let mut left_mode = neighbours.left_mode[r];
6495 if let Some(((pr, pc), pmode)) = prev_strip {
6496 if pc == mi_c && mi_r == pr + mi_h {
6497 above_mode = pmode;
6498 } else if pr == mi_r && mi_c == pc + mi_w {
6499 left_mode = pmode;
6500 }
6501 }
6502 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
6503 // availability-correct neighbour modes (see
6504 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
6505 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
6506 let (above_mode, left_mode) =
6507 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
6508 let (
6509 skip,
6510 mode,
6511 angle_delta_y,
6512 uv_mode,
6513 angle_delta_uv,
6514 alpha,
6515 filter_intra,
6516 palette_y,
6517 palette_uv,
6518 ) = read_intra_mode_rect(
6519 dec,
6520 cdfs,
6521 above_mode,
6522 left_mode,
6523 true,
6524 bw,
6525 bh,
6526 enable_filter_intra,
6527 neighbours.skip_txfm_ctx(mi_r, mi_c),
6528 allow_screen_content_tools,
6529 None,
6530 &[],
6531 mi_r,
6532 mi_c,
6533 )?;
6534 // Merge of lane-palette2: `read_intra_mode_rect` now reads the palette
6535 // syntax for every rect strip, but this 1:4 decoder has no palette
6536 // reconstruction path (its caller never passes a cache). The symbols are
6537 // still read, so the stream stays in sync; a strip that ACTUALLY uses a
6538 // palette is refused rather than reconstructed wrong.
6539 if palette_y.is_some() || palette_uv.is_some() {
6540 return Err(unsupported(
6541 "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)",
6542 ));
6543 }
6544 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
6545 if smooth_neighbor {
6546 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6547 }
6548 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
6549 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
6550 // `r * (SUB / MI)` names a different mi column and the chroma
6551 // edge-filter strength was read from the wrong neighbour (measured:
6552 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
6553 // with luma bit-exact).
6554 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
6555 if filter_intra.is_some() {
6556 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
6557 if bw > bh {
6558 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1));
6559 } else {
6560 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1));
6561 }
6562 }
6563 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
6564 DC_PRED
6565 } else {
6566 uv_mode
6567 };
6568 let depth = if tx_select {
6569 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
6570 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
6571 } else {
6572 0
6573 };
6574 if depth != 0 {
6575 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
6576 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
6577 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
6578 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
6579 // both interleave in every real stream.
6580 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
6581 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
6582 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
6583 // predicted -- depth 1 fires FIRST in every attempt that splits at
6584 // all, so a depth-2-only lift could never be gated. The r1 mismatch
6585 // was never the rect unit: it was the neighbour MODE the strip reads
6586 // (see `modes_above_left_mi`).
6587 let which = if depth == 1 {
6588 &RECT4_SPLIT_DEPTH1_HITS
6589 } else {
6590 &RECT4_SPLIT_DEPTH2_HITS
6591 };
6592 which.with(|c| c.set(c.get() + 1));
6593 let modes = RectStripModes {
6594 skip,
6595 mode,
6596 angle_delta_y,
6597 uv_predict_mode,
6598 angle_delta_uv,
6599 alpha,
6600 filter_intra,
6601 smooth_neighbor,
6602 smooth_neighbor_uv,
6603 // Both callers refuse a palette on this shape above (pixel
6604 // reconstruction is unported here), so the split units carry none.
6605 palette_y: None,
6606 palette_uv: None,
6607 };
6608 decode_rect_split(
6609 dec,
6610 cdfs,
6611 neighbours,
6612 (mi_r, mi_c),
6613 bw,
6614 bh,
6615 tx_w,
6616 tx_h,
6617 &modes,
6618 y,
6619 u,
6620 v,
6621 base_q_idx,
6622 false,
6623 )?;
6624 if bw > bh {
6625 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
6626 } else {
6627 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
6628 }
6629 if !skip {
6630 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
6631 }
6632 return Ok((mode, uv_predict_mode));
6633 }
6634 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
6635 // that is 8 px tall, so each strip stamps every cell it touches and the
6636 // LAST strip wins -- which is the right answer for the block below/right
6637 // of the 32x32, the only reader outside it. Written after this strip's
6638 // own context read above, never before.
6639 for cell in 0..bw.div_ceil(SUB) {
6640 neighbours.above_mode[c + cell] = mode;
6641 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
6642 neighbours.above_side[c + cell] = bw;
6643 }
6644 for cell in 0..bh.div_ceil(SUB) {
6645 neighbours.left_mode[r + cell] = mode;
6646 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
6647 neighbours.left_side[r + cell] = bh;
6648 }
6649 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
6650 // [`decode_leaf_rect`] does (the split arm above records these through
6651 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
6652 // `sub8_mode_row` holding the previous block, and the next 32x32's
6653 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
6654 // fixture).
6655 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
6656 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
6657 let (px, py) = (mi_c * MI, mi_r * MI);
6658 let (cpx, cpy) = (px / 2, py / 2);
6659 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
6660 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6661 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
6662 (&SCAN_32X8, &SCAN_16X4)
6663 } else {
6664 (&SCAN_8X32, &SCAN_4X16)
6665 };
6666 let (luma_levels, u_levels, v_levels) = if skip {
6667 (
6668 vec![0i32; bw * bh],
6669 vec![0i32; chroma_w * chroma_h],
6670 vec![0i32; chroma_w * chroma_h],
6671 )
6672 } else {
6673 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
6674 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
6675 let (luma_levels, luma_tx_type) = read_coeffs_rect(
6676 dec,
6677 &mut luma_coding,
6678 luma_scan,
6679 bw,
6680 bh,
6681 0,
6682 dc_sign_ctx(around[0].2),
6683 TxType::DctDct,
6684 )?;
6685 let mut planes = Vec::with_capacity(2);
6686 for plane in 1..3 {
6687 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
6688 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
6689 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
6690 let (levels, tx_type) = read_coeffs_rect(
6691 dec,
6692 &mut coding,
6693 chroma_scan,
6694 chroma_w,
6695 chroma_h,
6696 skip_ctx,
6697 dc_sign_ctx(around[plane].2),
6698 default_tx,
6699 )?;
6700 planes.push((levels, tx_type));
6701 }
6702 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
6703 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
6704 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
6705 let luma_residual = dequant_and_inverse_typed_wh(
6706 &luma_levels,
6707 bw,
6708 bh,
6709 crate::decode::bit_depth(),
6710 block_q_idx(),
6711 plane_q_delta(0).0,
6712 plane_q_delta(0).1,
6713 luma_tx_type,
6714 );
6715 y.reconstruct_rect(
6716 px,
6717 py,
6718 bw,
6719 bh,
6720 mode,
6721 angle_delta_y,
6722 reach,
6723 &luma_residual,
6724 None,
6725 filter_intra,
6726 smooth_neighbor,
6727 );
6728 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6729 for (plane, buf, levels, tx_type) in [
6730 (1usize, &mut *u, &u_levels, u_tx_type),
6731 (2, &mut *v, &v_levels, v_tx_type),
6732 ] {
6733 let residual = dequant_and_inverse_typed_wh(
6734 levels,
6735 chroma_w,
6736 chroma_h,
6737 crate::decode::bit_depth(),
6738 block_q_idx(),
6739 plane_q_delta(plane).0,
6740 plane_q_delta(plane).1,
6741 tx_type,
6742 );
6743 buf.reconstruct_rect(
6744 cpx,
6745 cpy,
6746 chroma_w,
6747 chroma_h,
6748 uv_predict_mode,
6749 angle_delta_uv,
6750 reach,
6751 &residual,
6752 alpha
6753 .zip(ac.as_deref())
6754 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
6755 None,
6756 smooth_neighbor_uv,
6757 );
6758 }
6759 neighbours.record_mi_rect(
6760 (mi_r, mi_c),
6761 bw,
6762 bh,
6763 &[luma_levels, u_levels, v_levels],
6764 );
6765 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
6766 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
6767 if bw > bh {
6768 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
6769 } else {
6770 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
6771 }
6772 return Ok((mode, uv_predict_mode));
6773 };
6774 y.reconstruct_rect(
6775 px,
6776 py,
6777 bw,
6778 bh,
6779 mode,
6780 angle_delta_y,
6781 reach,
6782 &luma_levels,
6783 None,
6784 filter_intra,
6785 smooth_neighbor,
6786 );
6787 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6788 u.reconstruct_rect(
6789 cpx,
6790 cpy,
6791 chroma_w,
6792 chroma_h,
6793 uv_predict_mode,
6794 angle_delta_uv,
6795 reach,
6796 &u_levels,
6797 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6798 None,
6799 smooth_neighbor_uv,
6800 );
6801 v.reconstruct_rect(
6802 cpx,
6803 cpy,
6804 chroma_w,
6805 chroma_h,
6806 uv_predict_mode,
6807 angle_delta_uv,
6808 reach,
6809 &v_levels,
6810 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6811 None,
6812 smooth_neighbor_uv,
6813 );
6814 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
6815 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
6816 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
6817 if bw > bh {
6818 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
6819 } else {
6820 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
6821 }
6822 Ok((mode, uv_predict_mode))
6823}
6824
6825/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
6826/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
6827/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
6828/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
6829/// cap, so LUMA needs the same corner truncation [`decode_block`] already
6830/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
6831/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
6832/// this function's own charter/report), so both strips read a real 32x32
6833/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
6834/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
6835/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
6836/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
6837/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
6838/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
6839/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
6840/// that function, only the single-transform-unit (`tx_depth == 0`) case is
6841/// supported: a split transform refuses by name rather than guess-decode.
6842#[allow(clippy::too_many_arguments)]
6843fn decode_block_rect64(
6844 dec: &mut SymbolDecoder,
6845 cdfs: &mut Cdfs,
6846 neighbours: &mut Neighbours,
6847 at: (usize, usize),
6848 bw: usize,
6849 bh: usize,
6850 y: &mut PlaneBuf,
6851 u: &mut PlaneBuf,
6852 v: &mut PlaneBuf,
6853 enable_filter_intra: bool,
6854 allow_screen_content_tools: bool,
6855 base_q_idx: u8,
6856 tx_select: bool,
6857 reduced_tx_set: bool,
6858) -> Result<()> {
6859 let (r, c) = at;
6860 let (px, py) = (c * SUB, r * SUB);
6861 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
6862 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
6863 let palette_uv_cache = neighbours.palette_uv_cache(at);
6864 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
6865 read_intra_mode_rect(
6866 dec,
6867 cdfs,
6868 nb_above_mode,
6869 nb_left_mode,
6870 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
6871 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
6872 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
6873 // correct), CFL must never be offered here -- passing `true`
6874 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
6875 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
6876 // from this block's very first symbol (lane-sbpart r3 bisect).
6877 false,
6878 bw,
6879 bh,
6880 enable_filter_intra,
6881 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
6882 allow_screen_content_tools,
6883 Some((palette_ctx, &palette_cache)),
6884 &palette_uv_cache,
6885 r * (SUB / MI),
6886 c * (SUB / MI),
6887 )?;
6888 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
6889 // The luma coefficient path here is the corner-cropped 32x32 real
6890 // transform embedded in a 64x32/32x64 grid ([`decode_block_rect64`]'s
6891 // own doc comment) -- a real (non-skip) palette block's residual
6892 // needs the plain, uncropped rect reader [`decode_block_rect`] already
6893 // has, not this one's truncation. `skip` (no residual at all) is
6894 // still supported below (lane-palette2 r4).
6895 return Err(unsupported(
6896 "a palette block with a real transform on a superblock-level HORZ/VERT \
6897 strip (corner-cropped luma coefficients not ported for palette)",
6898 ));
6899 }
6900 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
6901 if smooth_neighbor {
6902 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6903 }
6904 let smooth_neighbor_uv =
6905 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
6906 if filter_intra.is_some() {
6907 // `filter_intra_size_class_rect` already returns `None` for both
6908 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
6909 // 32 on both axes), so this symbol is never read at this level --
6910 // kept only as the same defensive refusal [`decode_block_rect`] has.
6911 return Err(unsupported(
6912 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
6913 av1_filter_intra_allowed_bsize caps at 32x32)",
6914 ));
6915 }
6916 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
6917 DC_PRED
6918 } else {
6919 uv_mode
6920 };
6921 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
6922 let depth = if tx_select {
6923 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
6924 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
6925 // counts `sub_tx_size_map` steps from the block's own max rect
6926 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
6927 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
6928 // steps, so this level's category is 3 (the same one a 64x64 square
6929 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
6930 // here was a wrong-table read of a real symbol.
6931 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
6932 } else {
6933 0
6934 };
6935 if depth != 0 {
6936 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
6937 // lane-rectsplit r1/r4: the superblock-level strip splits its
6938 // transform through the very same per-unit path as its 32x32-level
6939 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
6940 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
6941 // measured the old square formula mis-tiling exactly that strip).
6942 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
6943 if bw.max(bh) / bw.min(bh) == 4 {
6944 let which = if depth == 1 {
6945 &RECT4_SPLIT_DEPTH1_HITS
6946 } else {
6947 &RECT4_SPLIT_DEPTH2_HITS
6948 };
6949 which.with(|c| c.set(c.get() + 1));
6950 }
6951 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
6952 eprintln!(
6953 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
6954 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
6955 angle_y={angle_delta_y}"
6956 );
6957 }
6958 let modes = RectStripModes {
6959 skip,
6960 mode,
6961 angle_delta_y,
6962 uv_predict_mode,
6963 angle_delta_uv,
6964 alpha,
6965 filter_intra,
6966 smooth_neighbor,
6967 smooth_neighbor_uv,
6968 palette_y: palette_y
6969 .as_ref()
6970 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
6971 palette_uv: palette_uv.as_ref().map(|p| {
6972 (
6973 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
6974 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
6975 )
6976 }),
6977 };
6978 if palette_y.is_some() || palette_uv.is_some() {
6979 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
6980 }
6981 decode_rect_split(
6982 dec,
6983 cdfs,
6984 neighbours,
6985 (mi_r, mi_c),
6986 bw,
6987 bh,
6988 tx_w,
6989 tx_h,
6990 &modes,
6991 y,
6992 u,
6993 v,
6994 base_q_idx,
6995 reduced_tx_set,
6996 )?;
6997 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
6998 // (lane-palette2 r10): this return skips the fn's own tail, so a
6999 // split-tx superblock strip would otherwise leave the above/left
7000 // palette arrays holding a dead block's colours.
7001 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
7002 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
7003 let (puv_size, puv_colors) =
7004 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7005 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
7006 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
7007 return Ok(());
7008 }
7009 let (tx_w, tx_h) = (bw, bh);
7010 let (cpx, cpy) = (px / 2, py / 2);
7011 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
7012 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
7013 if let Some(ref pyv) = palette_y {
7014 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
7015 set_palette_pred(buf);
7016 }
7017 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
7018 (
7019 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
7020 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
7021 )
7022 });
7023 if skip {
7024 y.reconstruct_rect(
7025 px,
7026 py,
7027 bw,
7028 bh,
7029 mode,
7030 angle_delta_y,
7031 reach,
7032 &vec![0i32; bw * bh],
7033 None,
7034 filter_intra,
7035 smooth_neighbor,
7036 );
7037 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7038 if let Some((ub, _)) = &palette_uv_bufs {
7039 set_palette_pred(ub.clone());
7040 }
7041 u.reconstruct_rect(
7042 cpx,
7043 cpy,
7044 chroma_w,
7045 chroma_h,
7046 uv_predict_mode,
7047 angle_delta_uv,
7048 reach,
7049 &vec![0i32; chroma_w * chroma_h],
7050 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7051 None,
7052 smooth_neighbor_uv,
7053 );
7054 if let Some((_, vb)) = &palette_uv_bufs {
7055 set_palette_pred(vb.clone());
7056 }
7057 v.reconstruct_rect(
7058 cpx,
7059 cpy,
7060 chroma_w,
7061 chroma_h,
7062 uv_predict_mode,
7063 angle_delta_uv,
7064 reach,
7065 &vec![0i32; chroma_w * chroma_h],
7066 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7067 None,
7068 smooth_neighbor_uv,
7069 );
7070 neighbours.record_rect(
7071 at,
7072 bw,
7073 bh,
7074 mode,
7075 uv_predict_mode,
7076 &[
7077 vec![0i32; bw * bh],
7078 vec![0i32; chroma_w * chroma_h],
7079 vec![0i32; chroma_w * chroma_h],
7080 ],
7081 );
7082 } else {
7083 let around = neighbours.around_rect(at, bw, bh);
7084 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
7085 // (see this function's own doc comment). A 64-length axis codes only
7086 // its low 32 coefficients, so the corner is `min(bw, 32)` x
7087 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
7088 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
7089 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
7090 let scan32 = default_scan(TX32);
7091 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7092 let (rng, _) = dec.debug_state();
7093 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
7094 }
7095 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
7096 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
7097 read_coeffs(
7098 dec,
7099 &mut luma_coding,
7100 &scan32,
7101 0,
7102 dc_sign_ctx(around[0].2),
7103 TxType::DctDct,
7104 Some((bw, bh)),
7105 )?
7106 } else {
7107 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
7108 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
7109 // (`scan.c`) gives both the very same `default_scan_32x16` /
7110 // `default_scan_16x32` the 2:1 sizes use ("Half of the
7111 // coefficients of tx64 at higher frequencies are set to zeros. So
7112 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
7113 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
7114 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
7115 // 512-position eob group) -- BOTH identical to TX_32X16, so the
7116 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
7117 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
7118 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
7119 // what `base_ctx_rect` computes at (32, 16).
7120 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
7121 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
7122 read_coeffs_rect(
7123 dec,
7124 &mut luma_coding,
7125 luma_scan,
7126 luma_cw,
7127 luma_ch,
7128 0,
7129 dc_sign_ctx(around[0].2),
7130 TxType::DctDct,
7131 )?
7132 };
7133 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7134 let (rng, _) = dec.debug_state();
7135 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
7136 }
7137 let mut luma_levels = vec![0i32; bw * bh];
7138 for row in 0..luma_ch {
7139 luma_levels[row * bw..][..luma_cw]
7140 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
7141 }
7142 {
7143 let cur = block_q_idx();
7144 if cur != i32::from(base_q_idx) {
7145 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
7146 }
7147 if std::env::var_os("EC_AV1_TRACE").is_some() {
7148 eprintln!(
7149 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
7150 );
7151 }
7152 }
7153 let luma_residual = dequant_and_inverse_typed_wh(
7154 &luma_levels,
7155 bw,
7156 bh,
7157 crate::decode::bit_depth(),
7158 block_q_idx(),
7159 plane_q_delta(0).0,
7160 plane_q_delta(0).1,
7161 luma_tx_type,
7162 );
7163 y.reconstruct_rect(
7164 px,
7165 py,
7166 bw,
7167 bh,
7168 mode,
7169 angle_delta_y,
7170 reach,
7171 &luma_residual,
7172 None,
7173 filter_intra,
7174 smooth_neighbor,
7175 );
7176 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
7177 let leftcol: Vec<u16> = if px > 0 {
7178 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
7179 } else {
7180 vec![]
7181 };
7182 eprintln!(
7183 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
7184 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
7185 luma_corner.iter().any(|&v| v != 0),
7186 &y.data[py * y.width + px..][..bw],
7187 leftcol,
7188 );
7189 }
7190 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
7191 // corner crop needed (see doc comment).
7192 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7193 // The chroma plane is never truncated (both axes <= 32 after
7194 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
7195 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
7196 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
7197 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
7198 // set, and only the scan is new (lane-tx64x16).
7199 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
7200 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
7201 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
7202 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
7203 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
7204 };
7205 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
7206 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
7207 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7208 let (rng, _) = dec.debug_state();
7209 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
7210 }
7211 let (u_levels, u_tx_type) = read_coeffs_rect(
7212 dec,
7213 &mut u_coding,
7214 chroma_scan,
7215 chroma_w,
7216 chroma_h,
7217 u_skip_ctx,
7218 dc_sign_ctx(around[1].2),
7219 TxType::DctDct,
7220 )?;
7221 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7222 let (rng, _) = dec.debug_state();
7223 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
7224 }
7225 {
7226 let cur = block_q_idx();
7227 if cur != i32::from(base_q_idx) {
7228 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
7229 }
7230 if std::env::var_os("EC_AV1_TRACE").is_some() {
7231 eprintln!(
7232 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
7233 );
7234 }
7235 }
7236 let u_residual = dequant_and_inverse_typed_wh(
7237 &u_levels,
7238 chroma_w,
7239 chroma_h,
7240 crate::decode::bit_depth(),
7241 block_q_idx(),
7242 plane_q_delta(1).0,
7243 plane_q_delta(1).1,
7244 u_tx_type,
7245 );
7246 u.reconstruct_rect(
7247 cpx,
7248 cpy,
7249 chroma_w,
7250 chroma_h,
7251 uv_predict_mode,
7252 angle_delta_uv,
7253 reach,
7254 &u_residual,
7255 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7256 None,
7257 smooth_neighbor_uv,
7258 );
7259 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
7260 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
7261 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7262 let (rng, _) = dec.debug_state();
7263 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
7264 }
7265 let (v_levels, v_tx_type) = read_coeffs_rect(
7266 dec,
7267 &mut v_coding,
7268 chroma_scan,
7269 chroma_w,
7270 chroma_h,
7271 v_skip_ctx,
7272 dc_sign_ctx(around[2].2),
7273 TxType::DctDct,
7274 )?;
7275 if std::env::var_os("EC_TRACE_COEFF").is_some() {
7276 let (rng, _) = dec.debug_state();
7277 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
7278 }
7279 {
7280 let cur = block_q_idx();
7281 if cur != i32::from(base_q_idx) {
7282 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
7283 }
7284 if std::env::var_os("EC_AV1_TRACE").is_some() {
7285 eprintln!(
7286 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
7287 );
7288 }
7289 }
7290 let v_residual = dequant_and_inverse_typed_wh(
7291 &v_levels,
7292 chroma_w,
7293 chroma_h,
7294 crate::decode::bit_depth(),
7295 block_q_idx(),
7296 plane_q_delta(2).0,
7297 plane_q_delta(2).1,
7298 v_tx_type,
7299 );
7300 v.reconstruct_rect(
7301 cpx,
7302 cpy,
7303 chroma_w,
7304 chroma_h,
7305 uv_predict_mode,
7306 angle_delta_uv,
7307 reach,
7308 &v_residual,
7309 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7310 None,
7311 smooth_neighbor_uv,
7312 );
7313 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
7314 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
7315 }
7316 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
7317 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
7318 let (puv_size, puv_colors) =
7319 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7320 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
7321 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
7322 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
7323 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
7324 match (bw, bh) {
7325 (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)),
7326 (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)),
7327 _ => {}
7328 }
7329 if std::env::var_os("EC_AV1_TRACE").is_some() {
7330 let (rng, _) = dec.debug_state();
7331 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
7332 }
7333 Ok(())
7334}
7335
7336/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
7337/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
7338/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
7339/// it lands away from zero, for gate tests to prove a real stream fired one.
7340fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
7341 let symbol = dec.symbol(cdf);
7342 if symbol != ANGLE_DELTA_ZERO {
7343 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
7344 }
7345 symbol as i32 - ANGLE_DELTA_ZERO as i32
7346}
7347
7348#[allow(clippy::too_many_arguments)]
7349fn read_intra_mode(
7350 dec: &mut SymbolDecoder,
7351 cdfs: &mut Cdfs,
7352 above_mode: usize,
7353 left_mode: usize,
7354 cfl: bool,
7355 side: usize,
7356 enable_filter_intra: bool,
7357 skip_ctx: usize,
7358 allow_screen_content_tools: bool,
7359 allow_intrabc: bool,
7360 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
7361 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
7362 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
7363 // `None` at the excluded call sites (the 8x8-leaf path), which still read
7364 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
7365 // decoder reads either way -- but refuse by name the moment it fires,
7366 // exactly the old behaviour.
7367 palette: Option<(usize, &[u16])>,
7368 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
7369 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
7370 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
7371 // `use_palette_y`, not a neighbour lookup).
7372 palette_uv_cache: &[u16],
7373 mi_r: usize,
7374 mi_c: usize,
7375) -> Result<(
7376 bool,
7377 usize,
7378 i32,
7379 usize,
7380 i32,
7381 Option<(i32, i32)>,
7382 Option<usize>,
7383 Option<PaletteY>,
7384 Option<PaletteUv>,
7385)> {
7386 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
7387 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
7388 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
7389 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
7390 // line against the instrumented aomdec, not just `tell()`.
7391 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
7392 macro_rules! istep {
7393 ($name:literal, $val:expr) => {
7394 if ec_istep {
7395 let (rng, _) = dec.debug_state();
7396 eprintln!(
7397 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
7398 $name, $val
7399 );
7400 }
7401 };
7402 }
7403 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
7404 // `skip` when `SegIdPreSkip`, and after it otherwise.
7405 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
7406 if seg_id_pre_skip() {
7407 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
7408 }
7409 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
7410 if trace {
7411 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
7412 }
7413 istep!("skip", skip as i32);
7414 if !seg_id_pre_skip() {
7415 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
7416 }
7417 // spec order (see the comment below on `read_intrabc_info`): `skip`,
7418 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
7419 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
7420 istep!("cdef", 0);
7421 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
7422 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
7423 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
7424 let whole_sb = side == sb_mi_cur() as usize * 4;
7425 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip);
7426 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip);
7427 istep!("dq", 0);
7428 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
7429 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
7430 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
7431 // intra frame whose header set `allow_intrabc`. Actual intra block copy
7432 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
7433 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
7434 // draws the line at consuming this one flag symbol and refusing by name
7435 // when it fires, so the arithmetic decoder still resyncs for a stream
7436 // that merely allows (but never uses) intrabc.
7437 if allow_intrabc {
7438 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
7439 if trace {
7440 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
7441 }
7442 if use_intrabc {
7443 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
7444 if trace {
7445 eprintln!("TRACE intrabc dv={dv:?}");
7446 }
7447 INTRABC_DV.with(|c| c.set(Some(dv)));
7448 INTRABC_HITS.with(|c| c.set(c.get() + 1));
7449 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
7450 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
7451 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
7452 // `DC_PRED` (which is also what the neighbour mode contexts and
7453 // the loop filter then see).
7454 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
7455 }
7456 }
7457 let above_ctx = INTRA_MODE_CTX[above_mode];
7458 let left_ctx = INTRA_MODE_CTX[left_mode];
7459 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
7460 if trace {
7461 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
7462 }
7463 istep!("mode", mode as i32);
7464 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
7465 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
7466 if trace {
7467 eprintln!(
7468 "TRACE angle_delta value={}",
7469 delta + ANGLE_DELTA_ZERO as i32
7470 );
7471 }
7472 delta
7473 } else {
7474 0
7475 };
7476 istep!("angle_y", angle_delta_y);
7477 let uv_mode = if cfl {
7478 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
7479 } else {
7480 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
7481 };
7482 if trace {
7483 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
7484 }
7485 istep!("uv_mode", uv_mode as i32);
7486 let alpha = if cfl && uv_mode == UV_CFL_PRED {
7487 Some(read_cfl_alphas(dec, cdfs))
7488 } else {
7489 None
7490 };
7491 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
7492 // from this lane's directional chroma: a corner block with neither
7493 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
7494 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
7495 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
7496 // bug in that fallback this lane's own scope does not cover. Keep it
7497 // refused here rather than ship a silently-wrong decode.
7498 if (9..=12).contains(&uv_mode) {
7499 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
7500 }
7501 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
7502 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
7503 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
7504 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
7505 // the `else` branch below and never reads one either way.
7506 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
7507 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
7508 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
7509 } else {
7510 0
7511 };
7512 istep!("angle_uv", angle_delta_uv);
7513 if angle_delta_uv != 0 {
7514 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
7515 }
7516 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
7517 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
7518 // gated by `av1_allow_palette` (blockd.h -- size bound only,
7519 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
7520 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
7521 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
7522 // read the same CDF row whenever every neighbour really is non-palette).
7523 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
7524 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
7525 // neighbour lookup at all), so it is exact even at the excluded call
7526 // sites once Y decodes real syntax there too.
7527 //
7528 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
7529 // inline from `read_palette_mode_info` -- it runs later, from
7530 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
7531 // after the WHOLE mode-info read for the block, including UV palette
7532 // mode_info (`read_palette_mode_info`'s own second half, right below)
7533 // and `read_filter_intra_mode_info`. So this branch now only reads
7534 // mode/size/colours for both planes (deferring the two colour-index-map
7535 // decodes to after `filter_intra`, below) -- r6's range trace pinned
7536 // this exact ordering bug (`compare-range-not-tell`: ranges matched
7537 // bit-for-bit through the Y colours, diverged only at the old inline
7538 // `decode_color_index_map` call).
7539 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
7540 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
7541 if allow_screen_content_tools
7542 && let Some(bsize_ctx) = palette_bsize_ctx(side)
7543 {
7544 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
7545 if mode == DC_PRED {
7546 if trace {
7547 let (rng, _) = dec.debug_state();
7548 eprintln!(
7549 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
7550 );
7551 }
7552 }
7553 let use_palette_y =
7554 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
7555 if mode == DC_PRED && trace {
7556 let (rng, _) = dec.debug_state();
7557 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
7558 }
7559 if use_palette_y {
7560 if palette.is_none() {
7561 return Err(unsupported(
7562 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
7563 ));
7564 }
7565 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
7566 if trace {
7567 let (rng, _) = dec.debug_state();
7568 eprintln!("TRACE palette_y_size n={n} rng={rng}");
7569 }
7570 let colors = read_palette_colors_y(dec, n, cache);
7571 if trace {
7572 let (rng, _) = dec.debug_state();
7573 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
7574 }
7575 palette_y_pending = Some((n, colors));
7576 }
7577 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
7578 // unconditionally at this bit position whenever `uv_mode ==
7579 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
7580 // scope always reconstructs chroma alongside luma (`decode_block`
7581 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
7582 // is always true here and does not need threading in.
7583 let palette_uv_mode_ctx = usize::from(use_palette_y);
7584 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
7585 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
7586 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
7587 palette_uv_pending = Some((n, u_colors, v_colors));
7588 }
7589 }
7590 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
7591 // `use_filter_intra` symbol this decoder never read at all until
7592 // lane-av1real r10 -- silently skipping it left every bit past a
7593 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
7594 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
7595 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
7596 // symbol's bits were never consumed).
7597 let mut filter_intra = None;
7598 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
7599 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
7600 // `use_filter_intra` symbol for a Y-palette block, and reading one here
7601 // desynced every screen-content stream from the first palette block on
7602 // (it surfaced as a bogus "partition below 8x8" refusal further down the
7603 // tile).
7604 if mode == DC_PRED
7605 && enable_filter_intra
7606 && palette_y_pending.is_none()
7607 && let Some(class) = filter_intra_size_class(side)
7608 {
7609 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
7610 if trace {
7611 eprintln!(
7612 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
7613 use_filter_intra as i32
7614 );
7615 }
7616 istep!("use_filter_intra", use_filter_intra as i32);
7617 if use_filter_intra {
7618 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
7619 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
7620 if trace {
7621 eprintln!("TRACE filter_intra_mode value={fi_mode}");
7622 }
7623 istep!("filter_intra_mode", fi_mode as i32);
7624 filter_intra = Some(fi_mode);
7625 }
7626 }
7627 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
7628 // shared U/V map) -- the same order libaom's own loop visits them in.
7629 let palette_y = palette_y_pending.map(|(n, colors)| {
7630 let map = decode_color_index_map(dec, cdfs, n, side, false);
7631 PALETTE_HITS.with(|c| c.set(c.get() + 1));
7632 if trace {
7633 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
7634 }
7635 PaletteY { size: n, colors, map }
7636 });
7637 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
7638 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
7639 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
7640 if trace {
7641 eprintln!(
7642 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
7643 &u_colors[..n],
7644 &v_colors[..n]
7645 );
7646 }
7647 PaletteUv { size: n, u_colors, v_colors, map }
7648 });
7649 Ok((
7650 skip,
7651 mode,
7652 angle_delta_y,
7653 uv_mode,
7654 angle_delta_uv,
7655 alpha,
7656 filter_intra,
7657 palette_y,
7658 palette_uv,
7659 ))
7660}
7661
7662/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
7663/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
7664/// intra modes.
7665const UV_CFL_PRED: usize = 13;
7666
7667/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
7668/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
7669/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
7670/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
7671/// joint sign the same way. Returns each plane's final signed `alpha_q3`
7672/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
7673fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
7674 CFL_BLOCK_HITS.with(|c| c.set(c.get() + 1));
7675 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
7676 let sign_u = ((joint_sign + 1) * 11) >> 5;
7677 let sign_v = (joint_sign + 1) - 3 * sign_u;
7678 let alpha_u = if sign_u == 0 {
7679 0
7680 } else {
7681 let ctx_u = (joint_sign + 1 - 3) as usize;
7682 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
7683 if sign_u == 2 { mag } else { -mag }
7684 };
7685 let alpha_v = if sign_v == 0 {
7686 0
7687 } else {
7688 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
7689 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
7690 if sign_v == 2 { mag } else { -mag }
7691 };
7692 (alpha_u, alpha_v)
7693}
7694
7695/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
7696/// the reconstructed luma samples under a `side`-square block, subsampled
7697/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
7698/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
7699/// to give the AC values [`cfl_scaled`] scales by alpha.
7700fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
7701 let cside = side / 2;
7702 let mut ac = vec![0i32; cside * cside];
7703 let mut sum = 0i32;
7704 for cy in 0..cside {
7705 for cx in 0..cside {
7706 let (lx, ly) = (px + cx * 2, py + cy * 2);
7707 let q3 = (i32::from(y.data[ly * y.width + lx])
7708 + i32::from(y.data[ly * y.width + lx + 1])
7709 + i32::from(y.data[(ly + 1) * y.width + lx])
7710 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
7711 << 1;
7712 ac[cy * cside + cx] = q3;
7713 sum += q3;
7714 }
7715 }
7716 let num_pel = (cside * cside) as i32;
7717 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
7718 ac.iter_mut().for_each(|v| *v -= avg);
7719 ac
7720}
7721
7722/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
7723/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
7724/// ties away from zero on the shifted-out sign).
7725fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
7726 let v = alpha_q3 * ac_q3;
7727 if v >= 0 {
7728 (v + 32) >> 6
7729 } else {
7730 -((-v + 32) >> 6)
7731 }
7732}
7733
7734/// One plane's reconstruction buffer, `width * height` samples, and the
7735/// prediction/residual reads and writes into it — the decode-side twin of
7736/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
7737/// (own-edge and reach clamps both), passing what it gathers straight to
7738/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
7739/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
7740/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
7741fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
7742 use std::io::Write;
7743 if let Ok(path) = std::env::var(var)
7744 && let Ok(mut f) = std::fs::File::create(format!("{path}.f0"))
7745 {
7746 for p in [y, u, v] {
7747 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
7748 let _ = f.write_all(&narrow);
7749 }
7750 }
7751}
7752
7753#[derive(Clone)]
7754struct PlaneBuf {
7755 data: Vec<u16>,
7756 width: usize,
7757 height: usize,
7758 /// The frame's true, decodable extent in this plane's own units — past
7759 /// this, samples are the padded coding surface's invented tail, never a
7760 /// real decoder's edge or reach reads.
7761 true_width: usize,
7762 true_height: usize,
7763 /// This plane's own tile's top-left pixel origin (spec: intra prediction
7764 /// never reaches across a tile boundary even though an earlier-decoded
7765 /// tile's real pixels sit right there in the shared buffer) — set via
7766 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
7767 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
7768 /// is threaded (the two-tile column-split stage 1 fixture's tile always
7769 /// ends at the frame's own right/bottom edge); a non-last tile's own
7770 /// right/bottom reach bound is still open, tracked in the report.
7771 tile_x0: usize,
7772 tile_y0: usize,
7773 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
7774 /// (exclusive) -- a non-last tile column/row's own reach must stop at
7775 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
7776 /// full padded extent) for the single-tile/last-tile case, matching the
7777 /// old unclipped behaviour exactly.
7778 tile_x1: usize,
7779 tile_y1: usize,
7780}
7781
7782/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
7783/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
7784/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
7785/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
7786/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
7787/// `ALTREF2`/`ALTREF`).
7788type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
7789
7790impl PlaneBuf {
7791 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
7792 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
7793 /// are already in this plane's own units (luma pixels for `y`, chroma
7794 /// pixels — halved — for `u`/`v`).
7795 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
7796 self.tile_x0 = x0;
7797 self.tile_y0 = y0;
7798 self.tile_x1 = x1;
7799 self.tile_y1 = y1;
7800 }
7801
7802 fn edges(
7803 &self,
7804 x: usize,
7805 y: usize,
7806 side: usize,
7807 reach: Reach,
7808 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
7809 let own_across = x + side.min(self.true_width.saturating_sub(x));
7810 let across = if reach.above_right {
7811 own_across + side.min(self.true_width.saturating_sub(own_across))
7812 } else {
7813 own_across
7814 }
7815 .min(self.width)
7816 .min(self.tile_x1);
7817 let own_down = y + side.min(self.true_height.saturating_sub(y));
7818 let down = if reach.below_left {
7819 own_down + side.min(self.true_height.saturating_sub(own_down))
7820 } else {
7821 own_down
7822 }
7823 .min(self.height)
7824 .min(self.tile_y1);
7825 let above = (y > self.tile_y0 && across > x)
7826 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
7827 let left = (x > self.tile_x0 && down > y).then(|| {
7828 (y..down)
7829 .map(|row| self.data[row * self.width + x - 1])
7830 .collect::<Vec<_>>()
7831 });
7832 let corner =
7833 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
7834 (above, left, corner)
7835 }
7836
7837 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
7838 /// the above/left reach each extend by their OWN axis (`bw` across,
7839 /// `bh` down), not one shared `side`.
7840 fn edges_rect(
7841 &self,
7842 x: usize,
7843 y: usize,
7844 bw: usize,
7845 bh: usize,
7846 reach: Reach,
7847 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
7848 let own_across = x + bw.min(self.true_width.saturating_sub(x));
7849 let across = if reach.above_right {
7850 own_across + bw.min(self.true_width.saturating_sub(own_across))
7851 } else {
7852 own_across
7853 }
7854 .min(self.width)
7855 .min(self.tile_x1);
7856 let own_down = y + bh.min(self.true_height.saturating_sub(y));
7857 let down = if reach.below_left {
7858 own_down + bh.min(self.true_height.saturating_sub(own_down))
7859 } else {
7860 own_down
7861 }
7862 .min(self.height)
7863 .min(self.tile_y1);
7864 let above = (y > self.tile_y0 && across > x)
7865 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
7866 let left = (x > self.tile_x0 && down > y).then(|| {
7867 (y..down)
7868 .map(|row| self.data[row * self.width + x - 1])
7869 .collect::<Vec<_>>()
7870 });
7871 let corner =
7872 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
7873 if matches!((bw, bh), (16, 8) | (8, 16)) {
7874 RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1));
7875 if across > own_across || down > own_down {
7876 RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1));
7877 }
7878 }
7879 (above, left, corner)
7880 }
7881
7882 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
7883 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
7884 /// already-rect-capable `(bw, bh)` pair.
7885 #[allow(clippy::too_many_arguments)]
7886 fn reconstruct_rect(
7887 &mut self,
7888 x: usize,
7889 y: usize,
7890 bw: usize,
7891 bh: usize,
7892 mode: usize,
7893 angle_delta: i32,
7894 reach: Reach,
7895 residual: &[i32],
7896 cfl: Option<(i32, &[i32])>,
7897 filter_intra: Option<usize>,
7898 smooth_neighbor: bool,
7899 ) {
7900 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
7901 // (lane-palette2 r4): a palette block's prediction is the
7902 // reconstructed colour-index map, needing no edge pixels at all.
7903 let prediction = if let Some(buf) = take_palette_pred() {
7904 buf
7905 } else {
7906 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
7907 if std::env::var_os("EC_DEBUG_EDGES").is_some() {
7908 eprintln!(
7909 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
7910 above.as_ref().map(|a| (a.len(), a[0])),
7911 left.as_ref().map(|l| l.len()),
7912 left.as_ref().map(|l| l[0]),
7913 self.tile_x0, self.tile_y0, self.true_width, self.true_height
7914 );
7915 }
7916 let mut prediction = vec![0u16; bw * bh];
7917 if let Some(fi_mode) = filter_intra {
7918 crate::intra::predict_filter_intra(
7919 fi_mode,
7920 above.as_deref(),
7921 left.as_deref(),
7922 corner,
7923 bw,
7924 bh,
7925 &mut prediction,
7926 );
7927 } else {
7928 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
7929 predict(
7930 mode as u8,
7931 angle_delta,
7932 above.as_deref(),
7933 left.as_deref(),
7934 corner,
7935 bw,
7936 bh,
7937 enable_edge_filter,
7938 smooth_neighbor,
7939 &mut prediction,
7940 );
7941 }
7942 prediction
7943 };
7944 for row in 0..bh {
7945 for col in 0..bw {
7946 let idx = row * bw + col;
7947 let mut base = i32::from(prediction[idx]);
7948 if let Some((alpha_q3, ac_q3)) = cfl {
7949 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
7950 }
7951 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
7952 self.data[(y + row) * self.width + x + col] = sample;
7953 }
7954 }
7955 }
7956
7957 /// Predicts under `mode` then adds `residual` (side*side, raster),
7958 /// writing the clamped reconstruction back into the plane at `(x, y)`.
7959 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
7960 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
7961 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
7962 /// order (cfl.c).
7963 fn reconstruct(
7964 &mut self,
7965 x: usize,
7966 y: usize,
7967 side: usize,
7968 mode: usize,
7969 angle_delta: i32,
7970 reach: Reach,
7971 residual: &[i32],
7972 cfl: Option<(i32, &[i32])>,
7973 filter_intra: Option<usize>,
7974 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
7975 // libaom `get_filt_type`): true when the block's above OR left
7976 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
7977 // Callers pass their own plane's neighbour-mode check
7978 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
7979 // callers until a smooth/paeth `uv_mode` can reach this call at all
7980 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
7981 // keeps `false` exact for chroma without this fn needing to know why.
7982 smooth_neighbor: bool,
7983 ) {
7984 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
7985 // takes priority over `predict()`/`predict_filter_intra` entirely --
7986 // palette prediction needs no edge pixels at all.
7987 let prediction = if let Some(buf) = take_palette_pred() {
7988 buf
7989 } else {
7990 let (above, left, corner) = self.edges(x, y, side, reach);
7991 let mut prediction = vec![0u16; side * side];
7992 if let Some(fi_mode) = filter_intra {
7993 crate::intra::predict_filter_intra(
7994 fi_mode,
7995 above.as_deref(),
7996 left.as_deref(),
7997 corner,
7998 side,
7999 side,
8000 &mut prediction,
8001 );
8002 } else {
8003 // `enable_intra_edge_filter` is the sequence header's own flag
8004 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
8005 // call, never per-block) -- threading it through every
8006 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
8007 // dozen sites for a value that never changes mid-decode, so it
8008 // rides a thread-local instead (this decoder is single-threaded
8009 // per stream).
8010 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
8011 predict(
8012 mode as u8,
8013 angle_delta,
8014 above.as_deref(),
8015 left.as_deref(),
8016 corner,
8017 side,
8018 side,
8019 enable_edge_filter,
8020 smooth_neighbor,
8021 &mut prediction,
8022 );
8023 }
8024 prediction
8025 };
8026 for row in 0..side {
8027 for col in 0..side {
8028 let idx = row * side + col;
8029 let mut base = i32::from(prediction[idx]);
8030 if let Some((alpha_q3, ac_q3)) = cfl {
8031 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
8032 }
8033 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
8034 self.data[(y + row) * self.width + x + col] = sample;
8035 }
8036 }
8037 }
8038}
8039
8040/// Reads one plane's transform block, reconstructs it into `plane` at
8041/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
8042#[allow(clippy::too_many_arguments)]
8043fn read_plane(
8044 dec: &mut SymbolDecoder,
8045 cdfs: &mut Cdfs,
8046 set: TxbSet,
8047 scan: &[u16],
8048 plane_idx: usize,
8049 around: (bool, bool, i32),
8050 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
8051 // it for every plane's `txb` lookup (it is what an intra transform type's
8052 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
8053 tx_mode: usize,
8054 predict_mode: usize,
8055 angle_delta: i32,
8056 reach: Reach,
8057 plane: &mut PlaneBuf,
8058 x: usize,
8059 y: usize,
8060 side: usize,
8061 tx_side: usize,
8062 base_q_idx: u8,
8063 cfl: Option<(i32, &[i32])>,
8064 filter_intra: Option<usize>,
8065 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
8066 // smaller than its own block (spec `get_txb_ctx_general`'s
8067 // `plane_bsize != tx_size` branch), carrying the already-looked-up
8068 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
8069 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
8070 // formula below.
8071 luma_skip_ctx: Option<usize>,
8072 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
8073 smooth_neighbor: bool,
8074) -> Result<Vec<i32>> {
8075 let skip_ctx = if plane_idx == 0 {
8076 luma_skip_ctx.unwrap_or(0)
8077 } else {
8078 usize::from(around.0) + usize::from(around.1)
8079 };
8080 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
8081 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
8082 // not by the block's ordinary `mode` (which is always DC_PRED whenever
8083 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
8084 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
8085 // filter-intra in AV1).
8086 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
8087 let mut coding = cdfs.txb(set, tx_mode);
8088 // Luma's `default_tx_type` is only a fallback for the sizes whose
8089 // `TxbSet` carries no symbol at all (32-point and up), which the spec
8090 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
8091 // *never* its own coded symbol (`coding.tx_type` is always `None` for
8092 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
8093 // the plane's own predicted mode (`default_intra_tx_type`) -- except
8094 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
8095 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
8096 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
8097 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
8098 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
8099 // narrows there — only `Chroma32` and up do).
8100 let default_tx_type = if plane_idx == 0 || side >= 32 {
8101 TxType::DctDct
8102 } else {
8103 default_intra_tx_type(predict_mode as u8)
8104 };
8105 let (grid, tx_type) = read_coeffs(
8106 dec,
8107 &mut coding,
8108 scan,
8109 skip_ctx,
8110 dc_sign_ctx(around.2),
8111 default_tx_type,
8112 None,
8113 )?;
8114 note_chroma_class1(plane_idx, tx_type);
8115 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
8116 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
8117 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
8118 // guard also assumes.
8119 let levels = if tx_side == side {
8120 grid
8121 } else {
8122 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
8123 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
8124 // keyed by that true size, not the coded corner's -- so the corner
8125 // goes into the top-left of a `side`-sized grid, not the reverse.
8126 let mut full = vec![0i32; side * side];
8127 for row in 0..tx_side {
8128 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
8129 }
8130 full
8131 };
8132 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
8133 let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
8134 if std::env::var_os("EC_AV1_TRACE").is_some() {
8135 eprintln!(
8136 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
8137 );
8138 }
8139 plane.reconstruct(
8140 x,
8141 y,
8142 side,
8143 predict_mode,
8144 angle_delta,
8145 reach,
8146 &residual,
8147 cfl,
8148 filter_intra,
8149 smooth_neighbor,
8150 );
8151 Ok(if tx_side == side {
8152 residual_grid_placeholder(&levels, side)
8153 } else {
8154 levels
8155 })
8156}
8157
8158/// `record`'s neighbour state only reads whether *the coded grid* (not the
8159/// residual) has nonzero entries, so the levels this function already built
8160/// are what it wants back; this helper exists only to name that clearly at
8161/// the one call site where `tx_side == side`.
8162fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
8163 levels.to_vec()
8164}
8165
8166/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
8167/// three planes, reconstructing them into `y`/`u`/`v` and updating
8168/// `neighbours`.
8169#[allow(clippy::too_many_arguments)]
8170fn decode_block(
8171 dec: &mut SymbolDecoder,
8172 cdfs: &mut Cdfs,
8173 neighbours: &mut Neighbours,
8174 at: (usize, usize),
8175 side: usize,
8176 luma_set: TxbSet,
8177 chroma_set: TxbSet,
8178 luma_tx: usize,
8179 chroma_tx: usize,
8180 scans: (&[u16], &[u16]),
8181 cfl: bool,
8182 y: &mut PlaneBuf,
8183 u: &mut PlaneBuf,
8184 v: &mut PlaneBuf,
8185 base_q_idx: u8,
8186 enable_filter_intra: bool,
8187 allow_screen_content_tools: bool,
8188 allow_intrabc: bool,
8189 scan32: &[u16],
8190 scan16: &[u16],
8191 scan8: &[u16],
8192 scan4: &[u16],
8193 tx_select: bool,
8194 reduced_tx_set: bool,
8195) -> Result<()> {
8196 let (r, c) = at;
8197 let (px, py) = (c * SUB, r * SUB);
8198 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
8199 let palette_uv_cache = neighbours.palette_uv_cache(at);
8200 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
8201 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
8202 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
8203 read_intra_mode(
8204 dec,
8205 cdfs,
8206 nb_above_mode,
8207 nb_left_mode,
8208 cfl,
8209 side,
8210 enable_filter_intra,
8211 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
8212 allow_screen_content_tools,
8213 allow_intrabc,
8214 Some((palette_ctx, &palette_cache)),
8215 &palette_uv_cache,
8216 r * (SUB / MI),
8217 c * (SUB / MI),
8218 )?;
8219 if at_tile_left && palette_y.is_some() {
8220 PALETTE_TILE_LEFT_HITS.with(|c| c.set(c.get() + 1));
8221 }
8222 let intrabc_dv = INTRABC_DV.with(|c| c.take());
8223 // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
8224 // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
8225 // partition tree (`read_var_tx_size`), a syntax element this decoder has
8226 // nowhere -- reading the intra `tx_depth` symbol instead would desync.
8227 if intrabc_dv.is_some() && tx_select && !skip {
8228 return Err(unsupported(
8229 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
8230 ));
8231 }
8232 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
8233 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
8234 // actual chroma-from-luma correlation, same as this decoder always did.
8235 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8236 DC_PRED
8237 } else {
8238 uv_mode
8239 };
8240 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
8241 if smooth_neighbor {
8242 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8243 }
8244 let smooth_neighbor_uv =
8245 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
8246 if std::env::var_os("EC_AV1_TRACE").is_some() {
8247 eprintln!(
8248 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
8249 angle_delta_uv={angle_delta_uv}"
8250 );
8251 }
8252 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8253 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
8254 // block, skipped or not. `logical_tx` is what the loop filter's edge
8255 // lookup and the next block's own `tx_size_context` want (the *nominal*
8256 // transform size -- 64 even for the 64x64 corner-scanned case, spec
8257 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
8258 // which only differs from it at that one corner case.
8259 let (logical_tx, coeff_tx_side) = if tx_select {
8260 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
8261 (resolved, if resolved == 64 { 32 } else { resolved })
8262 } else {
8263 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
8264 // TX_64X64, so a 128x128 block is always FOUR luma transform units
8265 // even with `tx_select` off -- the TU loop below, never the
8266 // single-unit path.
8267 (side.min(64), luma_tx)
8268 };
8269 if tx_select && logical_tx < side && uv_mode != DC_PRED {
8270 SQ_CHROMA_TX_HITS.with(|c| c.set(c.get() + 1));
8271 }
8272 let luma_set = if tx_select {
8273 txbset_for(logical_tx, reduced_tx_set)
8274 } else {
8275 luma_set
8276 };
8277 let luma_set = if intrabc_dv.is_some() {
8278 txbset_for_inter(logical_tx, reduced_tx_set)
8279 } else {
8280 luma_set
8281 };
8282 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
8283 let reach = Reach::of(side, px, py, y.width, y.height);
8284 let (cpx, cpy) = (px / 2, py / 2);
8285 let chroma_side = side / 2;
8286 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
8287 // frame's own pre-loop-filter reconstruction (all loop filters are off
8288 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
8289 // block vector, with the BILINEAR kernel libaom forces for intrabc --
8290 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
8291 // odd, which is exactly what the bilinear taps then interpolate.
8292 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
8293 let mut yb = vec![0u16; side * side];
8294 mc::predict_with_filter(
8295 &y.data, y.width, y.true_width, y.true_height,
8296 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
8297 side, side, mc::InterpFilterKind::Bilinear, &mut yb,
8298 );
8299 let mut ub = vec![0u16; chroma_side * chroma_side];
8300 mc::predict_with_filter(
8301 &u.data, u.width, u.true_width, u.true_height,
8302 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
8303 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
8304 );
8305 let mut vb = vec![0u16; chroma_side * chroma_side];
8306 mc::predict_with_filter(
8307 &v.data, v.width, v.true_width, v.true_height,
8308 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
8309 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
8310 );
8311 (yb, ub, vb)
8312 });
8313 if let Some((yb, _, _)) = &intrabc_bufs {
8314 set_palette_pred(yb.clone());
8315 }
8316 // A palette-Y block's own prediction is the reconstructed colour-index
8317 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
8318 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
8319 // parameter through this function's dozen `y.reconstruct`/`read_plane`
8320 // sites. A split luma transform (`tx_select && logical_tx != side`)
8321 // would need the map sliced per-TU -- untested against a real
8322 // `--enable-palette=1` stream this round, so refuse by name rather than
8323 // guess at the slicing (charter's own named-acceptable fallback).
8324 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
8325 py.map
8326 .iter()
8327 .map(|&idx| py.colors[idx as usize])
8328 .collect()
8329 });
8330 // With one luma transform unit the whole `side`x`side` map is the
8331 // prediction; with several (`logical_tx != side`) each unit takes its own
8332 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
8333 // below (lane-palette2 r7) -- setting the full-block buffer here would be
8334 // taken by the FIRST unit and indexed at the wrong stride.
8335 if let Some(buf) = &palette_y_buf
8336 && logical_tx == side
8337 {
8338 set_palette_pred(buf.clone());
8339 }
8340 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
8341 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
8342 // plane's own `reconstruct`/`read_plane` call below (never both planes at
8343 // once), since Y's own set-then-take already emptied the slot by the time
8344 // either of these run.
8345 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
8346 (
8347 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
8348 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
8349 )
8350 });
8351 // The chroma half of the intrabc prediction rides the same per-plane
8352 // override slot the UV-palette buffers do (set fresh before each plane's
8353 // own `reconstruct`/`read_plane` call below).
8354 let palette_uv_bufs = match &intrabc_bufs {
8355 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
8356 None => palette_uv_bufs,
8357 };
8358 if skip {
8359 // A skipped block codes no residual syntax at all (spec 5.11.34):
8360 // straight prediction, on every plane.
8361 y.reconstruct(
8362 px,
8363 py,
8364 side,
8365 mode,
8366 angle_delta_y,
8367 reach,
8368 &vec![0i32; side * side],
8369 None,
8370 filter_intra,
8371 smooth_neighbor,
8372 );
8373 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8374 if let Some((ub, _)) = &palette_uv_bufs {
8375 set_palette_pred(ub.clone());
8376 }
8377 u.reconstruct(
8378 cpx,
8379 cpy,
8380 chroma_side,
8381 uv_predict_mode,
8382 angle_delta_uv,
8383 reach,
8384 &vec![0i32; chroma_side * chroma_side],
8385 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8386 None,
8387 smooth_neighbor_uv,
8388 );
8389 if let Some((_, vb)) = &palette_uv_bufs {
8390 set_palette_pred(vb.clone());
8391 }
8392 v.reconstruct(
8393 cpx,
8394 cpy,
8395 chroma_side,
8396 uv_predict_mode,
8397 angle_delta_uv,
8398 reach,
8399 &vec![0i32; chroma_side * chroma_side],
8400 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8401 None,
8402 smooth_neighbor_uv,
8403 );
8404 let luma_grid = vec![0i32; side * side];
8405 let u_grid = vec![0i32; chroma_side * chroma_side];
8406 let v_grid = vec![0i32; chroma_side * chroma_side];
8407 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
8408 } else if logical_tx == side {
8409 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
8410 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
8411 // that arm was redundant -- and wrong at 128, where
8412 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
8413 // block is four units whether or not `tx_select` is on.
8414 // A single luma transform unit -- the old path, unchanged (including
8415 // the 64x64 corner case, `logical_tx == side == 64` with
8416 // `coeff_tx_side == 32`).
8417 let around = neighbours.around(at, side);
8418 let luma_grid = read_plane(
8419 dec,
8420 cdfs,
8421 luma_set,
8422 luma_scan,
8423 0,
8424 around[0],
8425 mode,
8426 mode,
8427 angle_delta_y,
8428 reach,
8429 y,
8430 px,
8431 py,
8432 side,
8433 coeff_tx_side,
8434 base_q_idx,
8435 None,
8436 filter_intra,
8437 None,
8438 smooth_neighbor,
8439 )?;
8440 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8441 if let Some((ub, _)) = &palette_uv_bufs {
8442 set_palette_pred(ub.clone());
8443 }
8444 let u_grid = read_plane(
8445 dec,
8446 cdfs,
8447 chroma_set,
8448 scans.1,
8449 1,
8450 around[1],
8451 mode,
8452 uv_predict_mode,
8453 angle_delta_uv,
8454 reach,
8455 u,
8456 cpx,
8457 cpy,
8458 chroma_side,
8459 chroma_tx,
8460 base_q_idx,
8461 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8462 None,
8463 None,
8464 smooth_neighbor_uv,
8465 )?;
8466 if std::env::var_os("EC_AV1_TRACE").is_some() {
8467 eprintln!(
8468 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
8469 &u.data[cpy * u.width + cpx..][..chroma_side]
8470 );
8471 }
8472 if let Some((_, vb)) = &palette_uv_bufs {
8473 set_palette_pred(vb.clone());
8474 }
8475 let v_grid = read_plane(
8476 dec,
8477 cdfs,
8478 chroma_set,
8479 scans.1,
8480 2,
8481 around[2],
8482 mode,
8483 uv_predict_mode,
8484 angle_delta_uv,
8485 reach,
8486 v,
8487 cpx,
8488 cpy,
8489 chroma_side,
8490 chroma_tx,
8491 base_q_idx,
8492 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8493 None,
8494 None,
8495 smooth_neighbor_uv,
8496 )?;
8497 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
8498 } else {
8499 // Several luma transform units, raster order (spec
8500 // `transform_block`'s loop): the block's resolved transform is
8501 // genuinely smaller than its own side, so each tile of it predicts
8502 // and codes independently, its own context read fresh off whatever
8503 // the earlier tiles in this same block already wrote -- the same
8504 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
8505 let n_axis = side / logical_tx;
8506 for tu_row in 0..n_axis {
8507 for tu_col in 0..n_axis {
8508 let tu_mi = (
8509 mi_r + tu_row * (logical_tx / MI),
8510 mi_c + tu_col * (logical_tx / MI),
8511 );
8512 let tu_px = px + tu_col * logical_tx;
8513 let tu_py = py + tu_row * logical_tx;
8514 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
8515 // A transform unit inside a block is NOT a block at that
8516 // position (lane-palette2 r12): `Reach::of` granted the
8517 // top-right 8x8 unit of a 16x16 D203 block bottom-left
8518 // pixels libaom refuses outright (`col_off > 0`), which is
8519 // the diagonal wedge seed 46 reconstructed wrong.
8520 let tu_reach = tu_reach(
8521 side,
8522 side,
8523 tu_col * logical_tx,
8524 tu_row * logical_tx,
8525 logical_tx,
8526 reach,
8527 px,
8528 py,
8529 y.width,
8530 y.height,
8531 );
8532 // This transform unit's own bsize (`logical_tx`) is smaller
8533 // than the block it sits in (`side`), so `txb_skip_ctx` is
8534 // the neighbour-magnitude table, not the lone-TU 0 (spec
8535 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
8536 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
8537 if let Some(buf) = &palette_y_buf {
8538 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8539 let mut window = vec![0u16; logical_tx * logical_tx];
8540 for row in 0..logical_tx {
8541 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
8542 window[row * logical_tx..][..logical_tx]
8543 .copy_from_slice(&buf[src..][..logical_tx]);
8544 }
8545 set_palette_pred(window);
8546 }
8547 let tu_grid = read_plane(
8548 dec,
8549 cdfs,
8550 luma_set,
8551 luma_scan,
8552 0,
8553 tu_around,
8554 mode,
8555 mode,
8556 angle_delta_y,
8557 tu_reach,
8558 y,
8559 tu_px,
8560 tu_py,
8561 logical_tx,
8562 // The unit's own COEFFICIENT grid, half its side at
8563 // TX_64X64 (a 64-point transform codes nothing past 32);
8564 // identical to `logical_tx` at every smaller size
8565 // (lane-sb128b r1).
8566 coeff_tx_side,
8567 base_q_idx,
8568 None,
8569 filter_intra,
8570 Some(tu_skip_ctx),
8571 smooth_neighbor,
8572 )?;
8573 if std::env::var_os("EC_AV1_TRACE").is_some() {
8574 eprintln!(
8575 "TRACE tu_bitpos mi=({},{}) tell={}",
8576 tu_mi.0,
8577 tu_mi.1,
8578 dec.debug_bitpos()
8579 );
8580 }
8581 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
8582 }
8583 }
8584 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8585 let chroma_around = neighbours.around(at, side);
8586 if let Some((ub, _)) = &palette_uv_bufs {
8587 set_palette_pred(ub.clone());
8588 }
8589 let u_grid = read_plane(
8590 dec,
8591 cdfs,
8592 chroma_set,
8593 scans.1,
8594 1,
8595 chroma_around[1],
8596 mode,
8597 uv_predict_mode,
8598 angle_delta_uv,
8599 reach,
8600 u,
8601 cpx,
8602 cpy,
8603 chroma_side,
8604 chroma_tx,
8605 base_q_idx,
8606 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8607 None,
8608 None,
8609 smooth_neighbor_uv,
8610 )?;
8611 if let Some((_, vb)) = &palette_uv_bufs {
8612 set_palette_pred(vb.clone());
8613 }
8614 let v_grid = read_plane(
8615 dec,
8616 cdfs,
8617 chroma_set,
8618 scans.1,
8619 2,
8620 chroma_around[2],
8621 mode,
8622 uv_predict_mode,
8623 angle_delta_uv,
8624 reach,
8625 v,
8626 cpx,
8627 cpy,
8628 chroma_side,
8629 chroma_tx,
8630 base_q_idx,
8631 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8632 None,
8633 None,
8634 smooth_neighbor_uv,
8635 )?;
8636 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]);
8637 }
8638 // Unconditional, `size == 0` for a non-palette block: clears any stale
8639 // neighbour palette state the same way [`Neighbours::record`] always
8640 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
8641 // (the split-luma-TU branch above always refuses before reaching here
8642 // when `palette_y` is `Some`, so it is never live for that branch).
8643 let (py_size, py_colors) = palette_y
8644 .as_ref()
8645 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8646 neighbours.record_palette_y(at, side, py_size, py_colors);
8647 let (puv_size, puv_colors) = palette_uv
8648 .as_ref()
8649 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8650 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
8651 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
8652 neighbours.fill_lf_grid(
8653 (r * (SUB / MI), c * (SUB / MI)),
8654 side / MI,
8655 logical_tx as u8,
8656 0,
8657 );
8658 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
8659 Ok(())
8660}
8661
8662/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
8663/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
8664/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
8665/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
8666/// just-decoded mode, not the enclosing slot's stale one, is the true
8667/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
8668/// units, which is what its coefficient context (finer than [`SUB`]) is read
8669/// at. Returns the mode this leaf decoded, for the caller's own
8670/// `prev_leaf`/final mode-writeback bookkeeping.
8671#[allow(clippy::too_many_arguments)]
8672/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
8673/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
8674/// `above_mode[col]`, and its true above neighbour is the mi directly above
8675/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
8676/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
8677/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
8678/// (bottom-right) into both, as this path did, is right only when all four
8679/// leaves happen to share a mode. `done` may be short at the true frame edge
8680/// (the straddle caller filters positions off the frame), so each side falls
8681/// back to the last leaf actually decoded.
8682fn write_back_split_modes(
8683 neighbours: &mut Neighbours,
8684 done: &[((usize, usize), usize)],
8685 parent_mi: (usize, usize),
8686 slot: (usize, usize),
8687) {
8688 let (sr, sc) = slot;
8689 let Some(&(_, last)) = done.last() else {
8690 return;
8691 };
8692 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
8693 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
8694 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
8695}
8696
8697fn decode_leaf8(
8698 dec: &mut SymbolDecoder,
8699 cdfs: &mut Cdfs,
8700 neighbours: &mut Neighbours,
8701 outer_at: (usize, usize),
8702 leaf_mi: (usize, usize),
8703 scans: (&[u16], &[u16]),
8704 prev_leaf: Option<((usize, usize), usize)>,
8705 y: &mut PlaneBuf,
8706 u: &mut PlaneBuf,
8707 v: &mut PlaneBuf,
8708 base_q_idx: u8,
8709 enable_filter_intra: bool,
8710 allow_screen_content_tools: bool,
8711 allow_intrabc: bool,
8712 tx_select: bool,
8713 reduced_tx_set: bool,
8714) -> Result<usize> {
8715 let (r, c) = outer_at;
8716 // lane-modectx r1: the group's own availability-correct fallback pair, not
8717 // the raw coarse bands (which leak across a tile edge -- see
8718 // `modes_above_left`).
8719 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
8720 if let Some(((pr, pc), pmode)) = prev_leaf {
8721 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
8722 above_mode = pmode;
8723 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
8724 left_mode = pmode;
8725 }
8726 }
8727 // The mi-exact neighbour wins over both the coarse 16x16 slot and
8728 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
8729 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
8730 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
8731 // lane-rectsplitx r2 swept this arm into
8732 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
8733 // "no neighbour" at a tile edge, where the coarse cell holds the block
8734 // above/left of it inside the same 16x16.
8735 let (above_mode, left_mode) =
8736 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
8737 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
8738 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
8739 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
8740 // this leaf's `smooth_neighbor` is built from -- passing `false` here
8741 // filtered a directional chroma block's edge at the wrong strength
8742 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
8743 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
8744 // with the coarse [`SUB`] slot as the fallback when no block recorded
8745 // that exact mi cell.
8746 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
8747 if smooth_neighbor {
8748 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8749 }
8750 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
8751 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
8752 // `decode_block` caller at 16x16 and up.
8753 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y, _palette_uv) =
8754 read_intra_mode(
8755 dec,
8756 cdfs,
8757 above_mode,
8758 left_mode,
8759 true,
8760 8,
8761 enable_filter_intra,
8762 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
8763 allow_screen_content_tools,
8764 allow_intrabc,
8765 None,
8766 &[],
8767 leaf_mi.0,
8768 leaf_mi.1,
8769 )?;
8770 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8771 DC_PRED
8772 } else {
8773 uv_mode
8774 };
8775 neighbours.above_uv_mode[c] = uv_predict_mode;
8776 neighbours.left_uv_mode[r] = uv_predict_mode;
8777 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
8778 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
8779 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
8780 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
8781 // transform units, same raster-order per-TU pattern `decode_block`'s
8782 // multi-TU branch runs).
8783 let resolved = if tx_select {
8784 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
8785 } else {
8786 8
8787 };
8788 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8789 let reach = Reach::of(8, px, py, y.width, y.height);
8790 let (cpx, cpy) = (px / 2, py / 2);
8791 let (luma_grid, u_grid, v_grid);
8792 if skip {
8793 y.reconstruct(
8794 px,
8795 py,
8796 8,
8797 mode,
8798 angle_delta_y,
8799 reach,
8800 &vec![0i32; 64],
8801 None,
8802 filter_intra,
8803 smooth_neighbor,
8804 );
8805 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8806 u.reconstruct(
8807 cpx,
8808 cpy,
8809 4,
8810 uv_predict_mode,
8811 angle_delta_uv,
8812 reach,
8813 &vec![0i32; 16],
8814 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8815 None,
8816 smooth_neighbor_uv,
8817 );
8818 v.reconstruct(
8819 cpx,
8820 cpy,
8821 4,
8822 uv_predict_mode,
8823 angle_delta_uv,
8824 reach,
8825 &vec![0i32; 16],
8826 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8827 None,
8828 smooth_neighbor_uv,
8829 );
8830 luma_grid = vec![0i32; 64];
8831 u_grid = vec![0i32; 16];
8832 v_grid = vec![0i32; 16];
8833 } else if resolved != 4 {
8834 let around = neighbours.around_mi(leaf_mi, 8);
8835 luma_grid = read_plane(
8836 dec,
8837 cdfs,
8838 if reduced_tx_set {
8839 TxbSet::Luma8
8840 } else {
8841 TxbSet::Luma8Set1
8842 },
8843 scans.0,
8844 0,
8845 around[0],
8846 mode,
8847 mode,
8848 angle_delta_y,
8849 reach,
8850 y,
8851 px,
8852 py,
8853 8,
8854 TX8,
8855 base_q_idx,
8856 None,
8857 filter_intra,
8858 None,
8859 smooth_neighbor,
8860 )?;
8861 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8862 u_grid = read_plane(
8863 dec,
8864 cdfs,
8865 TxbSet::Chroma4,
8866 scans.1,
8867 1,
8868 around[1],
8869 mode,
8870 uv_predict_mode,
8871 angle_delta_uv,
8872 reach,
8873 u,
8874 cpx,
8875 cpy,
8876 4,
8877 TX4,
8878 base_q_idx,
8879 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8880 None,
8881 None,
8882 smooth_neighbor_uv,
8883 )?;
8884 v_grid = read_plane(
8885 dec,
8886 cdfs,
8887 TxbSet::Chroma4,
8888 scans.1,
8889 2,
8890 around[2],
8891 mode,
8892 uv_predict_mode,
8893 angle_delta_uv,
8894 reach,
8895 v,
8896 cpx,
8897 cpy,
8898 4,
8899 TX4,
8900 base_q_idx,
8901 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8902 None,
8903 None,
8904 smooth_neighbor_uv,
8905 )?;
8906 } else {
8907 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
8908 // grid of 4x4 transform units, each predicted from the leaf's own
8909 // 8x8 `mode` and reading its own fresh context off the earlier
8910 // units in this same leaf (the same per-TU pattern `decode_block`'s
8911 // multi-TU branch runs at bigger blocks).
8912 luma_grid = vec![0i32; 64];
8913 for tu_row in 0..2 {
8914 for tu_col in 0..2 {
8915 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
8916 let tu_px = px + tu_col * 4;
8917 let tu_py = py + tu_row * 4;
8918 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
8919 if crate::encode::Reach::in_vert_ab() {
8920 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));
8921 }
8922 let tu_reach = tu_reach(
8923 8,
8924 8,
8925 tu_col * 4,
8926 tu_row * 4,
8927 4,
8928 reach,
8929 px,
8930 py,
8931 y.width,
8932 y.height,
8933 );
8934 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
8935 let tu_grid = read_plane(
8936 dec,
8937 cdfs,
8938 if reduced_tx_set {
8939 TxbSet::Luma4
8940 } else {
8941 TxbSet::Luma4Set1
8942 },
8943 scans.1,
8944 0,
8945 tu_around,
8946 mode,
8947 mode,
8948 angle_delta_y,
8949 tu_reach,
8950 y,
8951 tu_px,
8952 tu_py,
8953 4,
8954 4,
8955 base_q_idx,
8956 None,
8957 filter_intra,
8958 Some(tu_skip_ctx),
8959 smooth_neighbor,
8960 )?;
8961 if std::env::var_os("EC_AV1_TRACE").is_some() {
8962 eprintln!(
8963 "TRACE tu_bitpos mi=({},{}) tell={}",
8964 tu_mi.0,
8965 tu_mi.1,
8966 dec.debug_bitpos()
8967 );
8968 }
8969 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
8970 }
8971 }
8972 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8973 let chroma_around = neighbours.around_mi(leaf_mi, 8);
8974 u_grid = read_plane(
8975 dec,
8976 cdfs,
8977 TxbSet::Chroma4,
8978 scans.1,
8979 1,
8980 chroma_around[1],
8981 mode,
8982 uv_predict_mode,
8983 angle_delta_uv,
8984 reach,
8985 u,
8986 cpx,
8987 cpy,
8988 4,
8989 TX4,
8990 base_q_idx,
8991 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8992 None,
8993 None,
8994 smooth_neighbor_uv,
8995 )?;
8996 v_grid = read_plane(
8997 dec,
8998 cdfs,
8999 TxbSet::Chroma4,
9000 scans.1,
9001 2,
9002 chroma_around[2],
9003 mode,
9004 uv_predict_mode,
9005 angle_delta_uv,
9006 reach,
9007 v,
9008 cpx,
9009 cpy,
9010 4,
9011 TX4,
9012 base_q_idx,
9013 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
9014 None,
9015 None,
9016 smooth_neighbor_uv,
9017 )?;
9018 // `record_split_luma` expects a `record`-style `(r, c)` position in
9019 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
9020 // already in mi units, so calling it here double-scaled the
9021 // position. Plane 0 is already correct per-TU from the
9022 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
9023 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
9024 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
9025 // leaf's own 8x8 side over `MI`).
9026 let side_mi = 2;
9027 for cell in 0..side_mi {
9028 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
9029 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
9030 }
9031 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9032 let bound_h = round_up_even(neighbours.mi_rows);
9033 let bound_w = round_up_even(neighbours.mi_cols);
9034 let u_state = neighbour_state(&u_grid);
9035 let v_state = neighbour_state(&v_grid);
9036 for cell in 0..side_mi {
9037 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
9038 neighbours.left[leaf_mi.0 + cell][1] = u_state;
9039 neighbours.left[leaf_mi.0 + cell][2] = v_state;
9040 }
9041 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
9042 neighbours.above[leaf_mi.1 + cell][1] = u_state;
9043 neighbours.above[leaf_mi.1 + cell][2] = v_state;
9044 }
9045 }
9046 // Non-palette 8x8 leaf (this path never reads a palette): clear the
9047 // above/left palette state over its own cell so the next block's ctx and
9048 // colour cache do not read a previous block's palette (lane-palette2 r8).
9049 {
9050 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
9051 neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
9052 neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
9053 }
9054 neighbours.fill_skip_grid(leaf_mi, 2, skip);
9055 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
9056 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
9057 return Ok(mode);
9058 }
9059 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
9060 // Non-palette 8x8 leaf (this path never reads a palette): clear the
9061 // above/left palette state over its own cell so the next block's ctx and
9062 // colour cache do not read a previous block's palette (lane-palette2 r8).
9063 {
9064 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
9065 neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
9066 neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
9067 }
9068 neighbours.fill_skip_grid(leaf_mi, 2, skip);
9069 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
9070 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
9071 Ok(mode)
9072}
9073
9074/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
9075/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
9076/// bottom, where no partition symbol is read at all -- `decode_block` runs
9077/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
9078/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
9079/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
9080/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
9081/// of the 2x2 4x4 group carries chroma syntax at all.
9082#[allow(clippy::too_many_arguments)]
9083fn read_intra_mode_sub8(
9084 dec: &mut SymbolDecoder,
9085 cdfs: &mut Cdfs,
9086 above_mode: usize,
9087 left_mode: usize,
9088 has_chroma: bool,
9089 enable_filter_intra: bool,
9090 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
9091 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
9092 // from the wrong row is the same VALUE with a different interval, so it
9093 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
9094 fi_class: usize,
9095 skip_ctx: usize,
9096 allow_intrabc: bool,
9097 mi_r: usize,
9098 mi_c: usize,
9099) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
9100 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
9101 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
9102 if trace {
9103 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
9104 }
9105 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
9106 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
9107 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
9108 if allow_intrabc {
9109 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
9110 if use_intrabc {
9111 return Err(unsupported(
9112 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
9113 ));
9114 }
9115 }
9116 let above_ctx = INTRA_MODE_CTX[above_mode];
9117 let left_ctx = INTRA_MODE_CTX[left_mode];
9118 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
9119 if trace {
9120 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
9121 }
9122 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
9123 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
9124 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
9125 // symbol. Reading one consumed a symbol the encoder never wrote and
9126 // desynced the tile at the very next element.
9127 let angle_delta_y = 0;
9128 let chroma = if has_chroma {
9129 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
9130 if trace {
9131 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
9132 }
9133 if (9..=12).contains(&uv_mode) {
9134 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
9135 }
9136 let alpha = if uv_mode == UV_CFL_PRED {
9137 Some(read_cfl_alphas(dec, cdfs))
9138 } else {
9139 None
9140 };
9141 if (V_PRED..=D67_PRED).contains(&uv_mode) {
9142 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
9143 }
9144 // See the luma comment above: no angle delta below 8x8.
9145 let angle_delta_uv = 0;
9146 Some((uv_mode, angle_delta_uv, alpha))
9147 } else {
9148 None
9149 };
9150 let mut filter_intra = None;
9151 if mode == DC_PRED && enable_filter_intra {
9152 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
9153 if trace {
9154 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
9155 }
9156 if use_filter_intra {
9157 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
9158 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
9159 filter_intra = Some(fi_mode);
9160 }
9161 }
9162 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
9163}
9164
9165/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
9166/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
9167/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
9168/// bookkeeping needs no change. Each leaf reads its own luma mode info,
9169/// neighboured off the *previously decoded leaf in this same group* on
9170/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
9171/// pattern, one level deeper); chroma is read and reconstructed exactly
9172/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
9173/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
9174/// derivation.
9175#[allow(clippy::too_many_arguments)]
9176fn decode_leaf_split4(
9177 dec: &mut SymbolDecoder,
9178 cdfs: &mut Cdfs,
9179 neighbours: &mut Neighbours,
9180 outer_at: (usize, usize),
9181 leaf_mi: (usize, usize),
9182 scan4: &[u16],
9183 prev_leaf: Option<((usize, usize), usize)>,
9184 y: &mut PlaneBuf,
9185 u: &mut PlaneBuf,
9186 v: &mut PlaneBuf,
9187 base_q_idx: u8,
9188 enable_filter_intra: bool,
9189 allow_intrabc: bool,
9190 reduced_tx_set: bool,
9191 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
9192 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
9193 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1)).
9194) -> Result<(usize, usize)> {
9195 SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1));
9196 let (r, c) = outer_at;
9197 let mut above_mode = neighbours.above_mode[c];
9198 let mut left_mode = neighbours.left_mode[r];
9199 if let Some(((pr, pc), pmode)) = prev_leaf {
9200 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
9201 above_mode = pmode;
9202 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
9203 left_mode = pmode;
9204 }
9205 }
9206 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
9207 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
9208 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
9209 let mut leaf_modes = [0usize; 4];
9210 let mut leaf_skips = [false; 4];
9211 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
9212 for i in 0..4usize {
9213 let (dr, dc) = (i / 2, i % 2);
9214 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
9215 // Neighbour modes at real mi granularity: inside the group the
9216 // sibling leaf, outside it the split-leaf map when the adjacent mi
9217 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
9218 // `sub8_mode_col`'s doc).
9219 let leaf_above = if dr == 0 {
9220 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
9221 } else {
9222 leaf_modes[i - 2]
9223 };
9224 let leaf_left = if dc == 0 {
9225 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
9226 } else {
9227 leaf_modes[i - 1]
9228 };
9229 let has_chroma = i == 3;
9230 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
9231 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
9232 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
9233 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
9234 skip_ctx, allow_intrabc, lmi.0, lmi.1,
9235 )?;
9236 leaf_modes[i] = mode;
9237 leaf_skips[i] = skip;
9238 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
9239 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
9240 if smooth_neighbor {
9241 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
9242 }
9243 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
9244 let reach = Reach::of(4, px, py, y.width, y.height);
9245 if skip {
9246 y.reconstruct(px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor);
9247 neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]);
9248 } else {
9249 let tu_around = neighbours.around_mi(lmi, 4)[0];
9250 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
9251 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
9252 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
9253 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
9254 // off the wrong CDF on the very first leaf and desynced the tile.
9255 let tu_grid = read_plane(
9256 dec,
9257 cdfs,
9258 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
9259 scan4,
9260 0,
9261 tu_around,
9262 mode,
9263 mode,
9264 angle_delta_y,
9265 reach,
9266 y,
9267 px,
9268 py,
9269 4,
9270 4,
9271 base_q_idx,
9272 None,
9273 filter_intra,
9274 None,
9275 smooth_neighbor,
9276 )?;
9277 neighbours.record_mi_luma(lmi, 4, &tu_grid);
9278 }
9279 neighbours.fill_skip_grid(lmi, 1, skip);
9280 neighbours.fill_lf_grid(lmi, 1, 4, 0);
9281 if has_chroma {
9282 last_uv = chroma;
9283 }
9284 }
9285 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
9286 let (cpx, cpy) = (gpx / 2, gpy / 2);
9287 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
9288 let (uv_mode, angle_delta_uv, alpha) =
9289 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
9290 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
9291 neighbours.above_uv_mode[c] = uv_predict_mode;
9292 neighbours.left_uv_mode[r] = uv_predict_mode;
9293 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
9294 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[3] {
9295 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
9296 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
9297 (vec![0i32; 16], vec![0i32; 16])
9298 } else {
9299 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
9300 let chroma_around = neighbours.around_mi(leaf_mi, 8);
9301 let ug = read_plane(
9302 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
9303 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
9304 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
9305 )?;
9306 let vg = read_plane(
9307 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
9308 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
9309 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
9310 )?;
9311 (ug, vg)
9312 };
9313 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
9314 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
9315 // rescaling is wrong for an already-mi-unit position, so this inlines
9316 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
9317 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
9318 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
9319 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
9320 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
9321 // bottom). libaom's `update_ext_partition_context` writes
9322 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
9323 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
9324 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
9325 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
9326 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
9327 // round's bug) makes the very next sibling 8x8's `partition_w8` read
9328 // with the wrong context and desync immediately.
9329 let side_mi = 2;
9330 for cell in 0..side_mi {
9331 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
9332 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
9333 }
9334 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9335 let bound_h = round_up_even(neighbours.mi_rows);
9336 let bound_w = round_up_even(neighbours.mi_cols);
9337 let u_state = neighbour_state(&u_grid);
9338 let v_state = neighbour_state(&v_grid);
9339 for cell in 0..side_mi {
9340 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
9341 neighbours.left[leaf_mi.0 + cell][1] = u_state;
9342 neighbours.left[leaf_mi.0 + cell][2] = v_state;
9343 }
9344 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
9345 neighbours.above[leaf_mi.1 + cell][1] = u_state;
9346 neighbours.above[leaf_mi.1 + cell][2] = v_state;
9347 }
9348 }
9349 Ok((leaf_modes[2], leaf_modes[1]))
9350}
9351
9352/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
9353/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
9354/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
9355/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
9356/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
9357/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
9358/// every sub-block one mi wide or high but the last) -- differing only where
9359/// the shape does:
9360///
9361/// * the transform is a true `TX_4X8`/`TX_8X4`
9362/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
9363/// `av1_inv_txfm_shift_ls` row already cover this size pair);
9364/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
9365/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
9366/// row -- see that variant's doc comment;
9367/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
9368/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
9369/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
9370/// ([`Reach::of_rect`]);
9371/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
9372/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
9373/// `BLOCK_4X4` split writes.
9374///
9375/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
9376/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
9377/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
9378/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
9379/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
9380/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
9381#[allow(clippy::too_many_arguments)]
9382fn decode_leaf_rect8(
9383 dec: &mut SymbolDecoder,
9384 cdfs: &mut Cdfs,
9385 neighbours: &mut Neighbours,
9386 outer_at: (usize, usize),
9387 leaf_mi: (usize, usize),
9388 vert: bool,
9389 scan4: &[u16],
9390 y: &mut PlaneBuf,
9391 u: &mut PlaneBuf,
9392 v: &mut PlaneBuf,
9393 base_q_idx: u8,
9394 enable_filter_intra: bool,
9395 allow_intrabc: bool,
9396 tx_select: bool,
9397 reduced_tx_set: bool,
9398) -> Result<(usize, usize)> {
9399 let (r, c) = outer_at;
9400 // lane-modectx r1: availability-correct fallback pair (see
9401 // `modes_above_left`), not the raw coarse bands.
9402 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
9403 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
9404 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
9405 let (w_mi, h_mi) = (bw / MI, bh / MI);
9406 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
9407 let mut leaf_modes = [0usize; 2];
9408 let mut leaf_skips = [false; 2];
9409 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
9410 for i in 0..2usize {
9411 let lmi = if vert {
9412 (leaf_mi.0, leaf_mi.1 + i)
9413 } else {
9414 (leaf_mi.0 + i, leaf_mi.1)
9415 };
9416 // Inside the pair the sibling is the neighbour on the split axis;
9417 // outside it the mi-granular map, else the coarse 16x16 slot.
9418 let leaf_above = if !vert && i == 1 {
9419 leaf_modes[0]
9420 } else {
9421 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
9422 };
9423 let leaf_left = if vert && i == 1 {
9424 leaf_modes[0]
9425 } else {
9426 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
9427 };
9428 let has_chroma = i == 1;
9429 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
9430 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
9431 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
9432 filter_intra_size_class_rect(bw, bh)
9433 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
9434 skip_ctx, allow_intrabc, lmi.0, lmi.1,
9435 )?;
9436 if filter_intra.is_some() {
9437 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
9438 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
9439 // same `reconstruct_rect`/`reconstruct` calls below -- and under
9440 // a split transform, per 4x4 unit with that unit's own edge,
9441 // which is exactly what the depth-1 loop already does.
9442 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
9443 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.set(c.get() + 1));
9444 }
9445 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
9446 // leaf too, and is read for every intra block, skipped or not. Its
9447 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
9448 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
9449 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
9450 // `tx_size_cat2` the 32x16 strips read -- with the rect context
9451 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
9452 // Missing this read consumed one symbol fewer than the encoder wrote
9453 // and desynced the tile at the very first rect leaf (class
9454 // `symbol-consumption-gap`).
9455 let depth = if tx_select {
9456 let ctx = tx_size_context_rect(neighbours, lmi, bw, bh);
9457 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
9458 } else {
9459 0
9460 };
9461 if depth != 0 {
9462 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
9463 RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
9464 }
9465 leaf_modes[i] = mode;
9466 leaf_skips[i] = skip;
9467 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
9468 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
9469 if smooth_neighbor {
9470 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
9471 }
9472 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
9473 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9474 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
9475 // two 4x4 transform units along its long axis, each predicted from
9476 // the previous unit's reconstruction and reading its own `txb_skip`
9477 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
9478 // four. The per-TU path writes its own neighbour state, so the
9479 // block-level write below is skipped for it.
9480 let split = depth != 0;
9481 if split {
9482 let mut done = 0usize;
9483 for tu in 0..2usize {
9484 let tu_mi = if vert {
9485 (lmi.0 + tu, lmi.1)
9486 } else {
9487 (lmi.0, lmi.1 + tu)
9488 };
9489 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
9490 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
9491 // Same per-TU rule as every other split-transform site
9492 // (lane-palette2 r12): a transform unit inside a block is not
9493 // a block at that position, so its reach comes from the
9494 // block's own row, offset by the unit's position.
9495 let tu_reach = tu_reach(
9496 bw,
9497 bh,
9498 tu_px - px,
9499 tu_py - py,
9500 4,
9501 reach,
9502 px,
9503 py,
9504 y.width,
9505 y.height,
9506 );
9507 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
9508 if skip {
9509 // A skipped leaf still predicts per transform unit: the
9510 // second 4x4 takes its above/left edge from the first
9511 // one's reconstruction, which is NOT what a single 4x8
9512 // prediction of the same mode produces.
9513 let zeros = vec![0i32; 16];
9514 y.reconstruct(
9515 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
9516 filter_intra, smooth_neighbor,
9517 );
9518 neighbours.record_mi_luma(tu_mi, 4, &zeros);
9519 continue;
9520 }
9521 let tu_grid = read_plane(
9522 dec,
9523 cdfs,
9524 if reduced_tx_set {
9525 TxbSet::Luma4
9526 } else {
9527 TxbSet::Luma4Set1
9528 },
9529 scan4,
9530 0,
9531 tu_around,
9532 mode,
9533 mode,
9534 angle_delta_y,
9535 tu_reach,
9536 y,
9537 tu_px,
9538 tu_py,
9539 4,
9540 TX4,
9541 base_q_idx,
9542 None,
9543 filter_intra,
9544 Some(tu_skip_ctx),
9545 smooth_neighbor,
9546 )?;
9547 if tu_grid.iter().any(|&l| l != 0) {
9548 done += 1;
9549 }
9550 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
9551 }
9552 if done > 0 {
9553 if vert {
9554 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
9555 } else {
9556 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
9557 }
9558 }
9559 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
9560 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0);
9561 if has_chroma {
9562 last_uv = chroma;
9563 }
9564 continue;
9565 }
9566 let grid = if skip {
9567 let zeros = vec![0i32; bw * bh];
9568 y.reconstruct_rect(
9569 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
9570 smooth_neighbor,
9571 );
9572 zeros
9573 } else {
9574 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
9575 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
9576 // at 0 -- see `decode_leaf_split4`'s own note.
9577 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
9578 let set = if reduced_tx_set {
9579 TxbSet::LumaRect4x8
9580 } else {
9581 TxbSet::LumaRect4x8Set1
9582 };
9583 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
9584 let (levels, tx_type) = read_coeffs_rect(
9585 dec,
9586 &mut coding,
9587 scan,
9588 bw,
9589 bh,
9590 0,
9591 dc_sign_ctx(around.2),
9592 TxType::DctDct,
9593 )?;
9594 if levels.iter().any(|&l| l != 0) {
9595 if vert {
9596 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
9597 } else {
9598 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
9599 }
9600 }
9601 let residual = dequant_and_inverse_typed_wh(
9602 &levels,
9603 bw,
9604 bh,
9605 crate::decode::bit_depth(),
9606 CURRENT_Q_IDX.with(|q| q.get()),
9607 plane_q_delta(0).0,
9608 plane_q_delta(0).1,
9609 tx_type,
9610 );
9611 y.reconstruct_rect(
9612 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
9613 smooth_neighbor,
9614 );
9615 levels
9616 };
9617 // Plane 0's per-TU coefficient context over this leaf's own mi span
9618 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
9619 // for the whole 8x8 group below).
9620 let state = neighbour_state(&grid);
9621 for cell in 0..h_mi {
9622 if lmi.0 + cell < neighbours.mi_rows {
9623 neighbours.left[lmi.0 + cell][0] = state;
9624 }
9625 }
9626 for cell in 0..w_mi {
9627 if lmi.1 + cell < neighbours.mi_cols {
9628 neighbours.above[lmi.1 + cell][0] = state;
9629 }
9630 }
9631 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
9632 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
9633 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0);
9634 if has_chroma {
9635 last_uv = chroma;
9636 }
9637 }
9638 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
9639 let (cpx, cpy) = (gpx / 2, gpy / 2);
9640 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
9641 let (uv_mode, angle_delta_uv, alpha) =
9642 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
9643 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
9644 neighbours.above_uv_mode[c] = uv_predict_mode;
9645 neighbours.left_uv_mode[r] = uv_predict_mode;
9646 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
9647 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[1] {
9648 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
9649 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
9650 (vec![0i32; 16], vec![0i32; 16])
9651 } else {
9652 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
9653 let chroma_around = neighbours.around_mi(leaf_mi, 8);
9654 let ug = read_plane(
9655 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
9656 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
9657 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
9658 )?;
9659 let vg = read_plane(
9660 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
9661 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
9662 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
9663 )?;
9664 (ug, vg)
9665 };
9666 // `update_partition_context` at the 8x8 level writes
9667 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
9668 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
9669 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
9670 // `partition_ctx_mi` reads back off these side values.
9671 for cell in 0..2 {
9672 neighbours.above_side_mi[leaf_mi.1 + cell] = bw;
9673 neighbours.left_side_mi[leaf_mi.0 + cell] = bh;
9674 }
9675 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9676 let bound_h = round_up_even(neighbours.mi_rows);
9677 let bound_w = round_up_even(neighbours.mi_cols);
9678 let u_state = neighbour_state(&u_grid);
9679 let v_state = neighbour_state(&v_grid);
9680 for cell in 0..2usize {
9681 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
9682 neighbours.left[leaf_mi.0 + cell][1] = u_state;
9683 neighbours.left[leaf_mi.0 + cell][2] = v_state;
9684 }
9685 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
9686 neighbours.above[leaf_mi.1 + cell][1] = u_state;
9687 neighbours.above[leaf_mi.1 + cell][2] = v_state;
9688 }
9689 }
9690 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
9691 // bottom one (the second under HORZ, the left one under VERT), the one a
9692 // neighbour to the right sees is the top-right (the second under VERT).
9693 Ok(if vert {
9694 (leaf_modes[0], leaf_modes[1])
9695 } else {
9696 (leaf_modes[1], leaf_modes[0])
9697 })
9698}
9699
9700/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
9701/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
9702/// (mod 8) reuse the same table.
9703const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
9704 [(-1, 1), (-2, 2)],
9705 [(0, 1), (-1, 2)],
9706 [(0, 1), (0, 2)],
9707 [(0, 1), (1, 2)],
9708 [(1, 1), (2, 2)],
9709 [(1, 0), (2, 1)],
9710 [(1, 0), (2, 0)],
9711 [(1, 0), (2, -1)],
9712];
9713/// A neighbour tap outside the frame's true extent -- `constrain` reads this
9714/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
9715const CDEF_VERY_LARGE: i32 = 0x4000;
9716const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
9717const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
9718
9719fn cdef_msb(x: i32) -> i32 {
9720 31 - x.leading_zeros() as i32
9721}
9722
9723/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
9724/// centre sample a filter tap is allowed to contribute.
9725fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
9726 if threshold == 0 {
9727 return 0;
9728 }
9729 let shift = (damping - cdef_msb(threshold)).max(0);
9730 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
9731}
9732
9733/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
9734/// direction of an 8x8 luma window and the variance gap between it and its
9735/// orthogonal, `sample(row, col)` reading that window's own pixels.
9736fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
9737 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
9738 let mut partial = [[0i64; 15]; 8];
9739 for i in 0..8i64 {
9740 for j in 0..8i64 {
9741 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
9742 // accumulating, same as `constrain`'s threshold shift below.
9743 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
9744 partial[0][(i + j) as usize] += x;
9745 partial[1][(i + j / 2) as usize] += x;
9746 partial[2][i as usize] += x;
9747 partial[3][(3 + i - j / 2) as usize] += x;
9748 partial[4][(7 + i - j) as usize] += x;
9749 partial[5][(3 - i / 2 + j) as usize] += x;
9750 partial[6][j as usize] += x;
9751 partial[7][(i / 2 + j) as usize] += x;
9752 }
9753 }
9754 let mut cost = [0i64; 8];
9755 for i in 0..8usize {
9756 cost[2] += partial[2][i] * partial[2][i];
9757 cost[6] += partial[6][i] * partial[6][i];
9758 }
9759 cost[2] *= DIV_TABLE[8];
9760 cost[6] *= DIV_TABLE[8];
9761 for i in 0..7usize {
9762 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
9763 * DIV_TABLE[i + 1];
9764 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
9765 * DIV_TABLE[i + 1];
9766 }
9767 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
9768 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
9769 for i in (1..8).step_by(2) {
9770 for j in 0..5usize {
9771 cost[i] += partial[i][3 + j] * partial[i][3 + j];
9772 }
9773 cost[i] *= DIV_TABLE[8];
9774 for j in 0..3usize {
9775 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
9776 * DIV_TABLE[2 * j + 2];
9777 }
9778 }
9779 let mut best_cost = 0i64;
9780 let mut best_dir = 0usize;
9781 for (i, &c) in cost.iter().enumerate() {
9782 if c > best_cost {
9783 best_cost = c;
9784 best_dir = i;
9785 }
9786 }
9787 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
9788 (best_dir, var as i32)
9789}
9790
9791/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
9792/// (high variance gap) gets more deringing than a flat or non-directional
9793/// one, only ever applied to the luma primary strength.
9794fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
9795 if var == 0 {
9796 return 0;
9797 }
9798 let i = if var >> 6 != 0 {
9799 cdef_msb(var >> 6).min(12)
9800 } else {
9801 0
9802 };
9803 (strength * (4 + i) + 8) >> 4
9804}
9805
9806/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
9807/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
9808/// previously-filtered neighbour must never feed this block's own sum).
9809#[allow(clippy::too_many_arguments)]
9810fn cdef_filter_block(
9811 sample: impl Fn(i32, i32) -> i32,
9812 dst: &mut PlaneBuf,
9813 ox: usize,
9814 oy: usize,
9815 bw: usize,
9816 bh: usize,
9817 pri_strength: i32,
9818 sec_strength: i32,
9819 dir: usize,
9820 pri_damping: i32,
9821 sec_damping: i32,
9822 enable_primary: bool,
9823 enable_secondary: bool,
9824 coeff_shift: i32,
9825) {
9826 let clipping_required = enable_primary && enable_secondary;
9827 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
9828 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
9829 // derivative) carries the bit-depth shift, so the tap-set parity bit
9830 // must be read back above that shift, not off the raw low bit.
9831 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
9832 for i in 0..bh {
9833 for j in 0..bw {
9834 let x = sample(i as i32, j as i32);
9835 let mut sum = 0i32;
9836 let mut max = x;
9837 let mut min = x;
9838 for k in 0..2usize {
9839 if enable_primary {
9840 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
9841 let p0 = sample(i as i32 + tr, j as i32 + tc);
9842 let p1 = sample(i as i32 - tr, j as i32 - tc);
9843 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
9844 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
9845 if clipping_required {
9846 if p0 != CDEF_VERY_LARGE {
9847 max = max.max(p0);
9848 }
9849 if p1 != CDEF_VERY_LARGE {
9850 max = max.max(p1);
9851 }
9852 min = min.min(p0).min(p1);
9853 }
9854 }
9855 if enable_secondary {
9856 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
9857 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
9858 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
9859 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
9860 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
9861 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
9862 if clipping_required {
9863 for s in [s0, s1, s2, s3] {
9864 if s != CDEF_VERY_LARGE {
9865 max = max.max(s);
9866 }
9867 }
9868 min = min.min(s0).min(s1).min(s2).min(s3);
9869 }
9870 sum += CDEF_SEC_TAPS[k]
9871 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
9872 + cdef_constrain(s1 - x, sec_strength, sec_damping)
9873 + cdef_constrain(s2 - x, sec_strength, sec_damping)
9874 + cdef_constrain(s3 - x, sec_strength, sec_damping));
9875 }
9876 }
9877 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
9878 if clipping_required {
9879 y = y.clamp(min, max);
9880 }
9881 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, sample_max()) as u16;
9882 }
9883 }
9884}
9885
9886/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
9887/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
9888/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
9889/// every block's level comes from [`LoopFilterParams::level`] plus the
9890/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
9891/// `get_filter_level`, precomputed per-block here rather than cached in a
9892/// table the way libaom's `av1_loop_filter_frame_init` does).
9893///
9894/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
9895/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
9896fn apply_deblock(
9897 y: &mut PlaneBuf,
9898 u: &mut PlaneBuf,
9899 v: &mut PlaneBuf,
9900 lf: &LoopFilterParams,
9901 n: &Neighbours,
9902 frame_width: usize,
9903 frame_height: usize,
9904) {
9905 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
9906 // mismatch between the raw reconstruction and post-filter output.
9907 if std::env::var_os("EC_AV1_DEBUG_SKIP_DEBLOCK").is_some() {
9908 return;
9909 }
9910 if lf.level[0] != 0 || lf.level[1] != 0 {
9911 deblock_plane(y, 0, lf, n, frame_width, frame_height);
9912 }
9913 if lf.level[2] != 0 {
9914 deblock_plane(u, 1, lf, n, frame_width, frame_height);
9915 }
9916 if lf.level[3] != 0 {
9917 deblock_plane(v, 2, lf, n, frame_width, frame_height);
9918 }
9919}
9920
9921/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
9922/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
9923/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
9924/// mi unit under this decoder's assumed 4:2:0 subsampling).
9925fn plane_to_mi(chroma: bool, coord: usize) -> usize {
9926 if chroma { coord / 2 } else { coord / 4 }
9927}
9928
9929/// This plane's own transform width in pixels at the covering block, spec
9930/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
9931/// width directly; chroma halves it (this decoder's UV transform is always
9932/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
9933/// under 4:2:0 and a block that never splits its own transform).
9934fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
9935 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
9936 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
9937}
9938
9939/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
9940/// edges step and gate by transform height, which differs from width only
9941/// on rect partition strips.
9942fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
9943 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
9944 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
9945}
9946
9947/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
9948/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
9949/// present only when its neighbour exists inside the true frame -- whether
9950/// the block immediately above (at this block's own leftmost mi column) or
9951/// to the left (at its own topmost mi row) coded a transform at least as wide
9952/// as `own_side`.
9953fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
9954 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
9955 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
9956 usize::from(above) + usize::from(left)
9957}
9958
9959/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
9960/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
9961/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
9962/// inter path maintains), except that an *inter* neighbour contributes its
9963/// own BLOCK size rather than its transform size -- the two differ the moment
9964/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
9965/// approximation coincides with this only while every neighbour codes one
9966/// whole-block transform, which is exactly what `TxMode::Select` ends.
9967fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
9968 let has_above = mi_r > n.tile_row0_mi;
9969 let has_left = mi_c > n.tile_col0_mi;
9970 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
9971 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
9972 if has_above && n.above_inter[mi_c / (SUB / MI)] {
9973 above = n.above_side_mi[mi_c] >= side;
9974 }
9975 if has_left && n.left_inter[mi_r / (SUB / MI)] {
9976 left = n.left_side_mi[mi_r] >= side;
9977 }
9978 match (has_above, has_left) {
9979 (true, true) => usize::from(above) + usize::from(left),
9980 (true, false) => usize::from(above),
9981 (false, true) => usize::from(left),
9982 (false, false) => 0,
9983 }
9984}
9985
9986/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
9987/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
9988/// the transform's own side in pixels (`side >> depth`) -- this decoder's
9989/// four square categories (8/16/32/64) each halve at most twice, matching
9990/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
9991fn read_tx_size(
9992 dec: &mut SymbolDecoder,
9993 cdfs: &mut Cdfs,
9994 n: &Neighbours,
9995 at_mi: (usize, usize),
9996 side: usize,
9997 // lane-txselect: `get_tx_size_context`'s real context, for the callers
9998 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
9999 // key-frame path's own deblock-grid approximation.
10000 ctx_override: Option<usize>,
10001) -> usize {
10002 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
10003 // `get_tx_size_context`): a block wider than 64 still tops out at
10004 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
10005 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
10006 // never against its own 128 side (lane-sb128b r1).
10007 let max_tx = side.min(64);
10008 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
10009 let depth = match max_tx {
10010 8 => {
10011 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
10012 }
10013 16 => {
10014 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
10015 }
10016 32 => {
10017 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
10018 }
10019 64 => {
10020 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
10021 }
10022 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
10023 };
10024 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
10025 let (rng, _) = dec.debug_state();
10026 let (mi_r, mi_c) = at_mi;
10027 eprintln!(
10028 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
10029 );
10030 }
10031 if depth != 0 {
10032 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
10033 }
10034 max_tx >> depth
10035}
10036
10037/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
10038/// `txfm_split` context -- a category from the block's own largest square
10039/// transform and whether this unit already sits below it, times three, plus
10040/// the two neighbour terms (whether the transform last written above/left of
10041/// this unit is narrower/shorter than the unit itself).
10042fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
10043 let above = usize::from(usize::from(above_px) < tx_px);
10044 let left = usize::from(usize::from(left_px) < tx_px);
10045 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
10046 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
10047 // `log2(px) - 2`.
10048 let max_tx = blk_max_px.min(64);
10049 let max_idx = max_tx.trailing_zeros() as usize - 2;
10050 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
10051 category * 3 + above + left
10052}
10053
10054/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
10055/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
10056/// resolved transform's own size.
10057fn txfm_partition_update(
10058 n: &mut Neighbours,
10059 (mi_r, mi_c): (usize, usize),
10060 tx_px: usize,
10061 txb_px: usize,
10062) {
10063 for i in 0..txb_px / MI {
10064 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
10065 *cell = tx_px as u8;
10066 }
10067 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
10068 *cell = tx_px as u8;
10069 }
10070 }
10071}
10072
10073/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
10074/// same contexts -- a skipped *inter* block records its own block size rather
10075/// than its transform size.
10076fn set_txfm_ctxs(
10077 n: &mut Neighbours,
10078 (mi_r, mi_c): (usize, usize),
10079 tx_px: usize,
10080 w_mi: usize,
10081 h_mi: usize,
10082 skip_inter: bool,
10083) {
10084 let bw = if skip_inter { w_mi * MI } else { tx_px };
10085 let bh = if skip_inter { h_mi * MI } else { tx_px };
10086 for i in 0..w_mi {
10087 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
10088 *cell = bw as u8;
10089 }
10090 }
10091 for i in 0..h_mi {
10092 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
10093 *cell = bh as u8;
10094 }
10095 }
10096}
10097
10098/// The value libaom initialises both transform contexts to -- NOT zero:
10099/// `av1_zero_above_context` memsets the txfm row to
10100/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
10101/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
10102/// pixels, so an unwritten neighbour reads as the *widest* possible
10103/// transform, not the narrowest.
10104const TXFM_CTX_INIT: u8 = 64;
10105
10106/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
10107/// twice below its own largest transform.
10108const MAX_VARTX_DEPTH: usize = 2;
10109
10110/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
10111/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
10112/// max-transform-sized unit of an inter block, collecting the resolved leaf
10113/// transform units into `out` as `(row offset, col offset, side)` in mi units
10114/// -- exactly the order `decode_reconstruct_tx` later reads their
10115/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
10116/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
10117/// `max_block_high`).
10118#[allow(clippy::too_many_arguments)]
10119fn read_var_tx_size(
10120 dec: &mut SymbolDecoder,
10121 cdfs: &mut Cdfs,
10122 n: &mut Neighbours,
10123 at_mi: (usize, usize),
10124 blk_max_px: usize,
10125 (max_w_mi, max_h_mi): (usize, usize),
10126 tx_px: usize,
10127 depth: usize,
10128 blk_row: usize,
10129 blk_col: usize,
10130 out: &mut Vec<(usize, usize, usize)>,
10131) {
10132 if blk_row >= max_h_mi || blk_col >= max_w_mi {
10133 return;
10134 }
10135 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
10136 if depth == MAX_VARTX_DEPTH {
10137 out.push((blk_row, blk_col, tx_px));
10138 txfm_partition_update(n, unit, tx_px, tx_px);
10139 return;
10140 }
10141 let ctx = txfm_partition_ctx(n.above_txfm[unit.1], n.left_txfm[unit.0], blk_max_px, tx_px);
10142 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
10143 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
10144 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
10145 let (rng, _) = dec.debug_state();
10146 eprintln!(
10147 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
10148 unit.0,
10149 unit.1,
10150 u8::from(split)
10151 );
10152 }
10153 if !split {
10154 out.push((blk_row, blk_col, tx_px));
10155 txfm_partition_update(n, unit, tx_px, tx_px);
10156 return;
10157 }
10158 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
10159 let sub = tx_px / 2;
10160 if sub == 4 {
10161 // libaom's `sub_txs == TX_4X4` early return: the whole 8x8 unit is
10162 // marked 4x4 (four transform units, raster order) without recursing.
10163 for row in 0..2 {
10164 for col in 0..2 {
10165 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
10166 out.push((blk_row + row, blk_col + col, 4));
10167 }
10168 }
10169 }
10170 txfm_partition_update(n, unit, 4, tx_px);
10171 return;
10172 }
10173 for row in (0..tx_px / MI).step_by(sub / MI) {
10174 for col in (0..tx_px / MI).step_by(sub / MI) {
10175 read_var_tx_size(
10176 dec,
10177 cdfs,
10178 n,
10179 at_mi,
10180 blk_max_px,
10181 (max_w_mi, max_h_mi),
10182 sub,
10183 depth + 1,
10184 blk_row + row,
10185 blk_col + col,
10186 out,
10187 );
10188 }
10189 }
10190}
10191
10192/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
10193/// branch): every block of a `TxMode::Select` inter frame codes its transform
10194/// size right after its own mode info -- an inter non-skip block through the
10195/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
10196/// every other block through the intra `tx_depth` symbol (a skipped inter
10197/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
10198/// block's own resolved transform side and the leaf list, the latter only
10199/// when the tree resolved to more than one transform unit.
10200#[allow(clippy::too_many_arguments)]
10201fn read_block_tx_size(
10202 dec: &mut SymbolDecoder,
10203 cdfs: &mut Cdfs,
10204 n: &mut Neighbours,
10205 at_mi: (usize, usize),
10206 side: usize,
10207 (mi_cols, mi_rows): (usize, usize),
10208 is_inter: bool,
10209 skip: bool,
10210) -> Result<(usize, Option<Vec<(usize, usize, usize)>>)> {
10211 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
10212 return Ok((side, None));
10213 }
10214 let side_mi = side / MI;
10215 if is_inter && !skip {
10216 let max_tx = side.min(64);
10217 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
10218 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
10219 let mut leaves = Vec::new();
10220 let step = max_tx / MI;
10221 for row in (0..side_mi).step_by(step) {
10222 for col in (0..side_mi).step_by(step) {
10223 read_var_tx_size(
10224 dec,
10225 cdfs,
10226 n,
10227 at_mi,
10228 side,
10229 (max_w_mi, max_h_mi),
10230 max_tx,
10231 0,
10232 row,
10233 col,
10234 &mut leaves,
10235 );
10236 }
10237 }
10238 let single = leaves.len() == 1 && leaves[0].2 == side;
10239 if !single && leaves.iter().any(|leaf| leaf.2 > 32) {
10240 // Only a block wider than a superblock's own 64x64 max transform
10241 // reaches here; this crate has no 64-point *inter* coefficient
10242 // table set ([`inter_txbset_for`] stops at 32).
10243 return Err(unsupported(
10244 "an inter var-tx tree with a leaf transform larger than 32x32",
10245 ));
10246 }
10247 let resolved = leaves.last().map_or(side, |l| l.2);
10248 return Ok((resolved, (!single).then_some(leaves)));
10249 }
10250 let tx = if is_inter {
10251 side.min(64)
10252 } else {
10253 read_tx_size(
10254 dec,
10255 cdfs,
10256 n,
10257 at_mi,
10258 side,
10259 Some(tx_size_context_txfm(n, at_mi, side)),
10260 )
10261 };
10262 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
10263 if !is_inter && tx != side {
10264 // lane-intrainter r1: an intra block inside an inter frame whose
10265 // `tx_depth` split its luma transform codes exactly the key-frame
10266 // split path's transform units (`decode_block`'s multi-TU loop),
10267 // raster order over the block. Handed back in the same leaf shape the
10268 // inter var-tx tree uses, so the caller's per-TU luma loop, the
10269 // `record_split_luma` neighbour write-back and the per-TU deblock
10270 // edges are the ones it already runs for a var-tx inter block. A
10271 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
10272 // seeing `Some` here.
10273 let step = tx / MI;
10274 let mut leaves = Vec::new();
10275 for row in (0..side_mi).step_by(step) {
10276 for col in (0..side_mi).step_by(step) {
10277 leaves.push((row, col, tx));
10278 }
10279 }
10280 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
10281 let mut h = c.get();
10282 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
10283 c.set(h);
10284 });
10285 return Ok((tx, Some(leaves)));
10286 }
10287 Ok((tx, None))
10288}
10289
10290/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
10291/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
10292/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
10293/// raster order, each reading its own coefficient context off the units
10294/// already decoded before it. Returns the block's luma grid (all-zero in the
10295/// split case, whose reconstruction has already happened unit by unit) and
10296/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
10297/// which for a split block lands on the top-left unit.
10298#[allow(clippy::too_many_arguments)]
10299fn read_inter_luma8(
10300 dec: &mut SymbolDecoder,
10301 cdfs: &mut Cdfs,
10302 neighbours: &mut Neighbours,
10303 leaf_mi: (usize, usize),
10304 y: &mut PlaneBuf,
10305 px: usize,
10306 py: usize,
10307 pred_y: &[u16],
10308 mode_for_tx: usize,
10309 base_q_idx: u8,
10310 scan8: &[u16],
10311 scan4: &[u16],
10312 reduced_tx_set: bool,
10313 split: bool,
10314) -> Result<(Vec<i32>, TxType)> {
10315 if !split {
10316 return read_inter_plane(
10317 dec,
10318 cdfs,
10319 if reduced_tx_set {
10320 TxbSet::Luma8Inter
10321 } else {
10322 TxbSet::Luma8InterSet1
10323 },
10324 scan8,
10325 0,
10326 neighbours.around_mi(leaf_mi, 8)[0],
10327 mode_for_tx,
10328 y,
10329 px,
10330 py,
10331 8,
10332 base_q_idx,
10333 pred_y,
10334 None,
10335 None,
10336 );
10337 }
10338 let mut first = TxType::DctDct;
10339 for tu_row in 0..2 {
10340 for tu_col in 0..2 {
10341 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
10342 let mut tu_pred = Vec::with_capacity(16);
10343 for rr in 0..4 {
10344 let start = (tu_row * 4 + rr) * 8 + tu_col * 4;
10345 tu_pred.extend_from_slice(&pred_y[start..start + 4]);
10346 }
10347 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
10348 let (tu_grid, tu_tx_type) = read_inter_plane(
10349 dec,
10350 cdfs,
10351 if reduced_tx_set {
10352 TxbSet::Luma4Inter
10353 } else {
10354 TxbSet::Luma4InterSet1
10355 },
10356 scan4,
10357 0,
10358 neighbours.around_mi(tu_mi, 4)[0],
10359 mode_for_tx,
10360 y,
10361 px + tu_col * 4,
10362 py + tu_row * 4,
10363 4,
10364 base_q_idx,
10365 &tu_pred,
10366 None,
10367 Some(tu_skip_ctx),
10368 )?;
10369 if tu_row == 0 && tu_col == 0 {
10370 first = tu_tx_type;
10371 }
10372 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
10373 }
10374 }
10375 Ok((vec![0i32; 64], first))
10376}
10377
10378/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
10379/// coefficient tables from -- the inter counterpart of [`txbset_for`].
10380fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
10381 match tx_px {
10382 32 => TxbSet::Luma32Inter,
10383 16 if reduced_tx_set => TxbSet::Luma16Inter,
10384 16 => TxbSet::Luma16InterSet1,
10385 8 if reduced_tx_set => TxbSet::Luma8Inter,
10386 8 => TxbSet::Luma8InterSet1,
10387 4 if reduced_tx_set => TxbSet::Luma4Inter,
10388 4 => TxbSet::Luma4InterSet1,
10389 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
10390 }
10391}
10392
10393/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
10394/// the only four sizes a `TxMode::Select` block's coded coefficient grid
10395/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
10396fn scan_for<'a>(
10397 tx_px: usize,
10398 scan32: &'a [u16],
10399 scan16: &'a [u16],
10400 scan8: &'a [u16],
10401 scan4: &'a [u16],
10402) -> &'a [u16] {
10403 match tx_px {
10404 32 => scan32,
10405 16 => scan16,
10406 8 => scan8,
10407 4 => scan4,
10408 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
10409 }
10410}
10411
10412/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
10413/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
10414/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
10415/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
10416/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
10417/// regardless of the flag (`av1_get_ext_tx_set_type`'s
10418/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
10419/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
10420/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
10421/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
10422/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
10423/// inter `ext_tx` sets, never the mode-indexed intra ones.
10424fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
10425 match tx_px {
10426 64 => TxbSet::Luma64,
10427 32 => TxbSet::Luma32Inter,
10428 16 if reduced_tx_set => TxbSet::Luma16Inter,
10429 16 => TxbSet::Luma16InterSet1,
10430 8 if reduced_tx_set => TxbSet::Luma8Inter,
10431 8 => TxbSet::Luma8InterSet1,
10432 _ => TxbSet::Luma64,
10433 }
10434}
10435
10436fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
10437 match tx_px {
10438 64 => TxbSet::Luma64,
10439 32 => TxbSet::Luma32,
10440 16 => TxbSet::Luma16,
10441 8 if reduced_tx_set => TxbSet::Luma8,
10442 8 => TxbSet::Luma8Set1,
10443 4 if reduced_tx_set => TxbSet::Luma4,
10444 4 => TxbSet::Luma4Set1,
10445 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
10446 }
10447}
10448
10449/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
10450/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
10451fn unit_log2(px: u32) -> i32 {
10452 if px == 0 {
10453 0
10454 } else {
10455 px.trailing_zeros() as i32 - 2
10456 }
10457}
10458
10459/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
10460/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
10461/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
10462/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
10463/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
10464/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
10465/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
10466/// block anywhere aborted the whole stream's decode before comparison).
10467fn lf_level(
10468 lf: &LoopFilterParams,
10469 plane_idx: usize,
10470 dir: usize,
10471 ref_frame: i8,
10472 delta_lf: i32,
10473 segment_id: u8,
10474) -> i32 {
10475 let base = i32::from(if plane_idx == 0 {
10476 lf.level[dir]
10477 } else if plane_idx == 1 {
10478 lf.level[2]
10479 } else {
10480 lf.level[3]
10481 });
10482 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
10483 // ref/mode delta scaling below, and regardless of `delta_enabled`
10484 // (that flag only gates `ref_deltas`/`mode_deltas`).
10485 let base = (base + delta_lf).clamp(0, 63);
10486 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
10487 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
10488 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
10489 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
10490 // for chroma.
10491 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
10492 let base = match seg_feature(usize::from(segment_id), feature) {
10493 Some(data) => (base + data).clamp(0, 63),
10494 None => base,
10495 };
10496 if !lf.delta_enabled {
10497 return base;
10498 }
10499 let scale = 1i32 << (base >> 5);
10500 let is_inter = ref_frame != 0;
10501 let is_globalmv = ref_frame < 0;
10502 let ref_idx = ref_frame.unsigned_abs() as usize;
10503 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
10504 if is_inter {
10505 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
10506 }
10507 lvl.clamp(0, 63)
10508}
10509
10510/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
10511/// no-segmentation, no-delta-LF path and to this decoder's own invariant
10512/// that a coded block's transform is always its own full size -- so a TU
10513/// edge is always also a PU edge, and the "both sides skipped, not a PU
10514/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
10515/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
10516/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
10517fn edge_params(
10518 lf: &LoopFilterParams,
10519 n: &Neighbours,
10520 plane_idx: usize,
10521 dir: usize,
10522 chroma: bool,
10523 x0: usize,
10524 y0: usize,
10525) -> Option<(u8, i32)> {
10526 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
10527 let cur_tx = if dir == 0 {
10528 tx_px_at(n, chroma, mi_r, mi_c)
10529 } else {
10530 tx_h_px_at(n, chroma, mi_r, mi_c)
10531 };
10532 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
10533 return None;
10534 }
10535 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
10536 let (pv_mi_r, pv_mi_c) = if dir == 0 {
10537 (mi_r, mi_c - 1)
10538 } else {
10539 (mi_r - 1, mi_c)
10540 };
10541 let pv_tx = if dir == 0 {
10542 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
10543 } else {
10544 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
10545 };
10546 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
10547 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
10548 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
10549 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
10550
10551 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
10552 let pv_level = lf_level(
10553 lf,
10554 plane_idx,
10555 dir,
10556 pv_ref,
10557 pv_delta_lf,
10558 segment_id_at(pv_mi_r, pv_mi_c),
10559 );
10560 if cur_level == 0 && pv_level == 0 {
10561 return None;
10562 }
10563 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
10564 let len: u8 = if chroma {
10565 if dim == 0 { 4 } else { 6 }
10566 } else {
10567 [4, 8, 14, 14, 14][dim]
10568 };
10569 let level = if cur_level != 0 { cur_level } else { pv_level };
10570 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
10571 Some((len, level))
10572}
10573
10574/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
10575fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
10576 let sharpness = i32::from(sharpness);
10577 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
10578 let mut lim = level >> shift;
10579 if sharpness > 0 {
10580 lim = lim.min(9 - sharpness);
10581 }
10582 lim = lim.max(1);
10583 (2 * (level + 2) + lim, lim, level >> 4)
10584}
10585
10586fn sclamp(v: i32) -> i32 {
10587 // libaom's `signed_char_clamp_high`: the clamp range scales with
10588 // `128 << (bit_depth - 8)` alongside the centering constant below.
10589 let scale = 1i32 << (bit_depth() - 8);
10590 v.clamp(-128 * scale, 128 * scale - 1)
10591}
10592
10593fn round_pow2(v: i32, n: u32) -> i32 {
10594 (v + (1 << (n - 1))) >> n
10595}
10596
10597/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
10598/// fallback.
10599fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
10600 if !mask {
10601 return [p1, p0, q0, q1];
10602 }
10603 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
10604 let centre = 128i32 << (bit_depth() - 8);
10605 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
10606 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
10607 let filter = sclamp(outer + 3 * (qs0 - ps0));
10608 let filter1 = sclamp(filter + 4) >> 3;
10609 let filter2 = sclamp(filter + 3) >> 3;
10610 let oq0 = sclamp(qs0 - filter1) + centre;
10611 let op0 = sclamp(ps0 + filter2) + centre;
10612 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
10613 let oq1 = sclamp(qs1 - tap) + centre;
10614 let op1 = sclamp(ps1 + tap) + centre;
10615 [op1, op0, oq0, oq1]
10616}
10617
10618/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
10619/// `filter4`'s narrow taps.
10620#[allow(clippy::too_many_arguments)]
10621fn filter6(
10622 mask: bool,
10623 thresh: i32,
10624 flat: bool,
10625 p2: i32,
10626 p1: i32,
10627 p0: i32,
10628 q0: i32,
10629 q1: i32,
10630 q2: i32,
10631) -> [i32; 4] {
10632 if flat && mask {
10633 [
10634 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
10635 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
10636 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
10637 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
10638 ]
10639 } else {
10640 filter4(mask, thresh, p1, p0, q0, q1)
10641 }
10642}
10643
10644/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
10645#[allow(clippy::too_many_arguments)]
10646fn filter8(
10647 mask: bool,
10648 thresh: i32,
10649 flat: bool,
10650 p3: i32,
10651 p2: i32,
10652 p1: i32,
10653 p0: i32,
10654 q0: i32,
10655 q1: i32,
10656 q2: i32,
10657 q3: i32,
10658) -> [i32; 6] {
10659 if flat && mask {
10660 [
10661 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
10662 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
10663 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
10664 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
10665 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
10666 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
10667 ]
10668 } else {
10669 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
10670 [p2, op1, op0, oq0, oq1, q2]
10671 }
10672}
10673
10674/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
10675/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
10676/// way -- they are only ever taps here, never written).
10677#[allow(clippy::too_many_arguments)]
10678fn filter14(
10679 mask: bool,
10680 thresh: i32,
10681 flat: bool,
10682 flat2: bool,
10683 p6: i32,
10684 p5: i32,
10685 p4: i32,
10686 p3: i32,
10687 p2: i32,
10688 p1: i32,
10689 p0: i32,
10690 q0: i32,
10691 q1: i32,
10692 q2: i32,
10693 q3: i32,
10694 q4: i32,
10695 q5: i32,
10696 q6: i32,
10697) -> [i32; 12] {
10698 if flat2 && flat && mask {
10699 [
10700 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
10701 round_pow2(
10702 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
10703 4,
10704 ),
10705 round_pow2(
10706 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
10707 4,
10708 ),
10709 round_pow2(
10710 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
10711 4,
10712 ),
10713 round_pow2(
10714 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
10715 4,
10716 ),
10717 round_pow2(
10718 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
10719 4,
10720 ),
10721 round_pow2(
10722 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
10723 4,
10724 ),
10725 round_pow2(
10726 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
10727 4,
10728 ),
10729 round_pow2(
10730 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
10731 4,
10732 ),
10733 round_pow2(
10734 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
10735 4,
10736 ),
10737 round_pow2(
10738 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
10739 4,
10740 ),
10741 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
10742 ]
10743 } else {
10744 let [op2, op1, op0, oq0, oq1, oq2] =
10745 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
10746 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
10747 }
10748}
10749
10750/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
10751/// the first (`q0`) sample past the edge, `outer_stride` advances to the
10752/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
10753/// the next along the edge's own filtering direction.
10754#[allow(clippy::too_many_arguments)]
10755fn filter_edge(
10756 data: &mut [u16],
10757 base: usize,
10758 outer_stride: isize,
10759 tap_stride: isize,
10760 len: u8,
10761 level: i32,
10762 sharpness: u8,
10763) {
10764 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
10765 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
10766 // every 8-bit threshold (including the flat masks' fixed `1`) is
10767 // compared against a raw pixel difference on the stream's own bit-depth
10768 // scale, so each is shifted left by `bit_depth - 8` before use.
10769 let shift = bit_depth() - 8;
10770 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
10771 let flat_thresh = 1i32 << shift;
10772 for i in 0..4isize {
10773 let center = (base as isize + i * outer_stride) as usize;
10774 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
10775 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
10776 match len {
10777 4 => {
10778 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
10779 let mask = (p1 - p0).abs() <= limit
10780 && (q1 - q0).abs() <= limit
10781 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10782 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
10783 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10784 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10785 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10786 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10787 }
10788 6 => {
10789 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
10790 let mask = (p2 - p1).abs() <= limit
10791 && (p1 - p0).abs() <= limit
10792 && (q1 - q0).abs() <= limit
10793 && (q2 - q1).abs() <= limit
10794 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10795 let flat = (p1 - p0).abs() <= flat_thresh
10796 && (q1 - q0).abs() <= flat_thresh
10797 && (p2 - p0).abs() <= flat_thresh
10798 && (q2 - q0).abs() <= flat_thresh;
10799 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
10800 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10801 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10802 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10803 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10804 }
10805 8 => {
10806 let (p3, p2, p1, p0, q0, q1, q2, q3) =
10807 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
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 [op2, op1, op0, oq0, oq1, oq2] =
10822 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
10823 data[idx(-3)] = op2.clamp(0, sample_max()) as u16;
10824 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10825 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10826 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10827 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10828 data[idx(2)] = oq2.clamp(0, sample_max()) as u16;
10829 }
10830 _ => {
10831 let (p6, p5, p4, p3, p2, p1, p0) =
10832 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
10833 let (q0, q1, q2, q3, q4, q5, q6) =
10834 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
10835 let mask = (p3 - p2).abs() <= limit
10836 && (p2 - p1).abs() <= limit
10837 && (p1 - p0).abs() <= limit
10838 && (q1 - q0).abs() <= limit
10839 && (q2 - q1).abs() <= limit
10840 && (q3 - q2).abs() <= limit
10841 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10842 let flat = (p1 - p0).abs() <= flat_thresh
10843 && (q1 - q0).abs() <= flat_thresh
10844 && (p2 - p0).abs() <= flat_thresh
10845 && (q2 - q0).abs() <= flat_thresh
10846 && (p3 - p0).abs() <= flat_thresh
10847 && (q3 - q0).abs() <= flat_thresh;
10848 let flat2 = (p4 - p0).abs() <= flat_thresh
10849 && (q4 - q0).abs() <= flat_thresh
10850 && (p5 - p0).abs() <= flat_thresh
10851 && (q5 - q0).abs() <= flat_thresh
10852 && (p6 - p0).abs() <= flat_thresh
10853 && (q6 - q0).abs() <= flat_thresh;
10854 let out = filter14(
10855 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
10856 q6,
10857 );
10858 for (k, v) in (-6..=5isize).zip(out) {
10859 data[idx(k)] = v.clamp(0, sample_max()) as u16;
10860 }
10861 }
10862 }
10863 }
10864}
10865
10866/// One plane's worth of spec 7.14: every vertical edge across the plane,
10867/// then every horizontal edge (the order the spec and libaom both use).
10868fn deblock_plane(
10869 plane: &mut PlaneBuf,
10870 plane_idx: usize,
10871 lf: &LoopFilterParams,
10872 n: &Neighbours,
10873 frame_width: usize,
10874 frame_height: usize,
10875) {
10876 let chroma = plane_idx != 0;
10877 // r7: libaom clips the deblock loop to the CODED frame's own
10878 // width/height, not the mi-aligned `true_width`/`true_height` margin
10879 // (the padding up to the next 8-pixel/superblock boundary that
10880 // reconstruction still fills in but the loop filter never visits).
10881 // Confirmed against the superres gate: with the margin included, the
10882 // last coded mi column's horizontal edges were filtered when libaom's
10883 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
10884 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
10885 let (cw, ch) = if chroma {
10886 (frame_width.div_ceil(2), frame_height.div_ceil(2))
10887 } else {
10888 (frame_width, frame_height)
10889 };
10890 let (tw, th, stride) = (
10891 plane.true_width.min(cw),
10892 plane.true_height.min(ch),
10893 plane.width,
10894 );
10895 let mut y0 = 0usize;
10896 while y0 < th {
10897 let mut x0 = 4usize;
10898 while x0 < tw {
10899 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
10900 filter_edge(
10901 &mut plane.data,
10902 y0 * stride + x0,
10903 stride as isize,
10904 1,
10905 len,
10906 level,
10907 lf.sharpness,
10908 );
10909 }
10910 x0 += 4;
10911 }
10912 y0 += 4;
10913 }
10914 let mut x0 = 0usize;
10915 while x0 < tw {
10916 let mut y0 = 4usize;
10917 while y0 < th {
10918 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
10919 if std::env::var_os("EC_AV1_DEBLOCK_TRACE").is_some()
10920 && plane_idx == 0
10921 && x0 == 44
10922 {
10923 eprintln!(
10924 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
10925 lf.sharpness
10926 );
10927 }
10928 filter_edge(
10929 &mut plane.data,
10930 y0 * stride + x0,
10931 1,
10932 stride as isize,
10933 len,
10934 level,
10935 lf.sharpness,
10936 );
10937 }
10938 y0 += 4;
10939 }
10940 x0 += 4;
10941 }
10942}
10943
10944fn apply_cdef(
10945 y: &mut PlaneBuf,
10946 u: &mut PlaneBuf,
10947 v: &mut PlaneBuf,
10948 cdef: &CdefParams,
10949 skip_grid: &Neighbours,
10950) {
10951 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
10952 if std::env::var_os("EC_AV1_DEBUG_SKIP_CDEF").is_some() {
10953 return;
10954 }
10955 // `cdef.bits == 0` still means "no filtering at all" whenever the single
10956 // (index 0) strength pair is all-zero -- the fast path every existing
10957 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
10958 // at every index, but that is rare enough not to special-case; the
10959 // per-superblock lookup below degrades to the same index-0 read anyway
10960 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
10961 if cdef.bits == 0
10962 && cdef.y_pri_strength[0] == 0
10963 && cdef.y_sec_strength[0] == 0
10964 && cdef.uv_pri_strength[0] == 0
10965 && cdef.uv_sec_strength[0] == 0
10966 {
10967 return;
10968 }
10969 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
10970 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
10971 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
10972 if sb_cols == 0 {
10973 return 0;
10974 }
10975 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
10976 idx_grid
10977 .get(sb_r * sb_cols + sb_c)
10978 .copied()
10979 .unwrap_or(0) as usize
10980 };
10981 let src_y = y.data.clone();
10982 let src_u = u.data.clone();
10983 let src_v = v.data.clone();
10984 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
10985 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
10986 let coeff_shift = i32::from(bit_depth()) - 8;
10987 let damping = i32::from(cdef.damping) + coeff_shift;
10988 let damping_uv = (damping - 1).max(0);
10989 let mut mi_r = 0usize;
10990 while mi_r < skip_grid.mi_rows {
10991 let mut mi_c = 0usize;
10992 while mi_c < skip_grid.mi_cols {
10993 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
10994 let sidx = strength_idx(mi_r, mi_c);
10995 let (ox, oy) = (mi_c * 4, mi_r * 4);
10996 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
10997 let sample_y = |r: i32, c: i32| -> i32 {
10998 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
10999 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
11000 CDEF_VERY_LARGE
11001 } else {
11002 i32::from(src_y[ny as usize * y_stride + nx as usize])
11003 }
11004 };
11005 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| {
11006 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
11007 i32::from(src_y[ny * y_stride + nx])
11008 });
11009
11010 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
11011 // -- each plane zeroes the shared direction when *its own*
11012 // frame-level primary strength is 0, independent of the
11013 // per-block adjusted `t` and of the other plane's strength.
11014 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
11015 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
11016 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
11017 let t = cdef_adjust_strength(y_pri_strength, var);
11018 let enable_primary = t != 0;
11019 let enable_secondary = y_sec_strength != 0;
11020 if enable_primary || enable_secondary {
11021 cdef_filter_block(
11022 sample_y,
11023 y,
11024 ox,
11025 oy,
11026 8,
11027 8,
11028 t,
11029 y_sec_strength,
11030 y_dir,
11031 damping,
11032 damping,
11033 enable_primary,
11034 enable_secondary,
11035 coeff_shift,
11036 );
11037 }
11038
11039 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
11040 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
11041 let uv_dir = if t_uv != 0 { dir } else { 0 };
11042 let enable_primary_uv = t_uv != 0;
11043 let enable_secondary_uv = uv_sec_strength != 0;
11044 if enable_primary_uv || enable_secondary_uv {
11045 let (cox, coy) = (ox / 2, oy / 2);
11046 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
11047 let (tw, th) = (plane.true_width, plane.true_height);
11048 let stride = plane.width;
11049 let sample_uv = |r: i32, c: i32| -> i32 {
11050 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
11051 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
11052 CDEF_VERY_LARGE
11053 } else {
11054 i32::from(src_p[ny as usize * stride + nx as usize])
11055 }
11056 };
11057 cdef_filter_block(
11058 sample_uv,
11059 plane,
11060 cox,
11061 coy,
11062 4,
11063 4,
11064 t_uv,
11065 uv_sec_strength,
11066 uv_dir,
11067 damping_uv,
11068 damping_uv,
11069 enable_primary_uv,
11070 enable_secondary_uv,
11071 coeff_shift,
11072 );
11073 }
11074 }
11075 }
11076 mi_c += 2;
11077 }
11078 mi_r += 2;
11079 }
11080}
11081
11082/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
11083/// ordering note: libaom also runs `superres_post_decode` between the two,
11084/// but this decoder never implements super-resolution, so there is nothing
11085/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
11086/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
11087/// restoration's stripe-boundary rows read from it instead of the
11088/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
11089#[allow(clippy::too_many_arguments)]
11090fn apply_loop_restoration(
11091 y: &mut PlaneBuf,
11092 u: &mut PlaneBuf,
11093 v: &mut PlaneBuf,
11094 deblocked_y: &PlaneBuf,
11095 deblocked_u: &PlaneBuf,
11096 deblocked_v: &PlaneBuf,
11097 lr: &LoopRestorationParams,
11098 grid: &crate::restoration::RestorationGrid,
11099) {
11100 y.data = crate::restoration::apply_loop_restoration_plane(
11101 &y.data,
11102 &deblocked_y.data,
11103 y.width,
11104 y.true_width,
11105 y.true_height,
11106 0,
11107 lr.frame_restoration_type[0],
11108 lr.loop_restoration_size[0],
11109 grid,
11110 0,
11111 );
11112 u.data = crate::restoration::apply_loop_restoration_plane(
11113 &u.data,
11114 &deblocked_u.data,
11115 u.width,
11116 u.true_width,
11117 u.true_height,
11118 1,
11119 lr.frame_restoration_type[1],
11120 lr.loop_restoration_size[1],
11121 grid,
11122 1,
11123 );
11124 v.data = crate::restoration::apply_loop_restoration_plane(
11125 &v.data,
11126 &deblocked_v.data,
11127 v.width,
11128 v.true_width,
11129 v.true_height,
11130 1,
11131 lr.frame_restoration_type[2],
11132 lr.loop_restoration_size[2],
11133 grid,
11134 2,
11135 );
11136}
11137
11138/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
11139/// returning the picture it reconstructs to.
11140///
11141/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
11142/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
11143/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
11144/// `compute_image_size` derives one from the other, but not losslessly: a
11145/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
11146/// what the reconstruction is cropped to on the way out, mirroring
11147/// [`crate::encode::crop_encoded`].
11148///
11149/// # Errors
11150/// Returns an error when a block's partition, mode, skip flag or transform
11151/// type is anything this decoder does not reconstruct (round 2: inter, tx
11152/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
11153/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
11154/// or when the tile payload runs out of the symbols this decode expects (a
11155/// genuinely foreign stream).
11156pub fn decode_key_frame_tile(
11157 data: &[u8],
11158 mi_cols: u32,
11159 mi_rows: u32,
11160 base_q_idx: u8,
11161 frame_width: u32,
11162 frame_height: u32,
11163 enable_filter_intra: bool,
11164 cdef: &CdefParams,
11165 loop_filter: &LoopFilterParams,
11166 tx_select: bool,
11167 reduced_tx_set: bool,
11168 allow_screen_content_tools: bool,
11169 allow_intrabc: bool,
11170) -> Result<Picture> {
11171 let delta = DeltaParams::default();
11172 let single_tile = TileInfo {
11173 mi_col_starts: vec![0, mi_cols],
11174 mi_row_starts: vec![0, mi_rows],
11175 ..TileInfo::default()
11176 };
11177 decode_key_frame_tile_with_cdfs(
11178 &[data],
11179 &single_tile,
11180 mi_cols,
11181 mi_rows,
11182 base_q_idx,
11183 crate::quant::QuantDeltas::default(),
11184 frame_width,
11185 frame_height,
11186 enable_filter_intra,
11187 false,
11188 cdef,
11189 loop_filter,
11190 &LoopRestorationParams::default(),
11191 None,
11192 tx_select,
11193 reduced_tx_set,
11194 allow_screen_content_tools,
11195 allow_intrabc,
11196 delta,
11197 )
11198 .map(|(picture, _)| picture)
11199}
11200
11201thread_local! {
11202 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
11203 /// the mi-aligned `true_width`, set by the most recent
11204 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
11205 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
11206 /// their reconstructed buffer down from the same mi-aligned extent, so
11207 /// they share this one slot. See each function's own comment at its
11208 /// write site. `None` when there was no margin to save.
11209 static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
11210 const { std::cell::RefCell::new(None) };
11211}
11212
11213/// The margin the most recent key- or inter-frame tile decode stashed
11214/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
11215/// reads this immediately after the call, before any other frame
11216/// decode can overwrite it.
11217pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
11218 LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
11219}
11220
11221/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
11222/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
11223/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
11224/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
11225/// since a key frame's own header always forces `primary_ref_frame ==
11226/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
11227/// alongside the picture, for the caller to save into whichever reference
11228/// slots this frame's `refresh_frame_flags` names.
11229/// The order the 64x64 superblock quadrants of a tile are decoded in.
11230///
11231/// At `sb_size == 64` this is plain raster order over the tile's own
11232/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
11233/// each 128x128 superblock in raster order and visits its four 64x64
11234/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
11235/// 64-level bodies must run in that nested order. `row_start` marks the first
11236/// item of each *superblock* row (where the left neighbour context resets),
11237/// `sb_start` the first item of each superblock (where the 128 root's own
11238/// loop-restoration units and partition symbol are read).
11239fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
11240 let mut out = Vec::new();
11241 if !sb128 {
11242 for r in r0..r1 {
11243 for c in c0..c1 {
11244 out.push((r, c, c == c0, true));
11245 }
11246 }
11247 return out;
11248 }
11249 let mut r = r0;
11250 while r < r1 {
11251 let mut first_in_row = true;
11252 let mut c = c0;
11253 while c < c1 {
11254 let mut first_in_sb = true;
11255 for qr in 0..2 {
11256 for qc in 0..2 {
11257 let (rr, cc) = (r + qr, c + qc);
11258 if rr >= r1 || cc >= c1 {
11259 continue;
11260 }
11261 out.push((rr, cc, first_in_row, first_in_sb));
11262 first_in_row = false;
11263 first_in_sb = false;
11264 }
11265 }
11266 c += 2;
11267 }
11268 r += 2;
11269 }
11270 out
11271}
11272
11273/// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
11274/// the inter tile loop. Its loop-restoration units are read once for the whole
11275/// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
11276/// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
11277/// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
11278/// decoder codes, the other seven arms refuse by name.
11279#[allow(clippy::too_many_arguments)]
11280thread_local! {
11281 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
11282 /// whole 128x128 block (lane-sb128b r1's gate counter).
11283 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
11284}
11285
11286/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
11287pub(crate) fn part128_none_hits() -> usize {
11288 PART128_NONE_HITS.with(std::cell::Cell::get)
11289}
11290
11291fn read_sb128_root(
11292 dec: &mut SymbolDecoder,
11293 cdfs: &mut Cdfs,
11294 neighbours: &Neighbours,
11295 lr: &LoopRestorationParams,
11296 lr_grid: &mut crate::restoration::RestorationGrid,
11297 lr_reference: &mut [(
11298 crate::restoration::WienerInfo,
11299 crate::restoration::SgrprojInfo,
11300 ); 3],
11301 sb_r: u32,
11302 sb_c: u32,
11303 mi_cols: u32,
11304 mi_rows: u32,
11305) -> Result<usize> {
11306 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
11307 crate::restoration::read_lr(
11308 dec,
11309 cdfs,
11310 lr,
11311 lr_grid,
11312 lr_reference,
11313 mi_r128,
11314 mi_c128,
11315 SB_MI * 2,
11316 );
11317 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
11318 let ctx128 = neighbours.partition_ctx(at128, 128);
11319 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
11320 let part128 = if has_cols128 && has_rows128 {
11321 PART128_SYMBOLS.with(|c| c.set(c.get() + 1));
11322 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
11323 if std::env::var_os("EC_AV1_TRACE").is_some() {
11324 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
11325 }
11326 p
11327 } else {
11328 match (has_cols128, has_rows128) {
11329 (true, false) => {
11330 dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128));
11331 }
11332 (false, true) => {
11333 dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128));
11334 }
11335 _ => {}
11336 }
11337 PARTITION_SPLIT
11338 };
11339 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
11340 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
11341 // four AB shapes) still need the rect/AB machinery at this size.
11342 if part128 != PARTITION_SPLIT && part128 != PARTITION_NONE {
11343 return Err(unsupported(
11344 "a 128x128 superblock HORZ/VERT or AB partition (only SPLIT and NONE are decoded at the 128 root)",
11345 ));
11346 }
11347 if part128 == PARTITION_SPLIT {
11348 PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1));
11349 } else {
11350 PART128_NONE_HITS.with(|c| c.set(c.get() + 1));
11351 // lane-sb128b r1 RESIDUAL: the luma half of a 128x128 `PARTITION_NONE`
11352 // block is coded below (four TX_64X64 units), but its CHROMA is not:
11353 // `av1_get_max_uv_txsize` runs `av1_get_adjusted_tx_size` over the
11354 // 64x64 uv plane block, so the uv transform is TX_32X32 and each
11355 // plane is FOUR units -- `decode_block` codes exactly one whole-plane
11356 // chroma unit, which desyncs the tile at the first such block (gate
11357 // `a_real_aomenc_key_frame_with_a_128x128_none_partition_decodes_pixel_exact`,
11358 // 384x384 cq63: decoded, small deltas over 94% of the luma plane).
11359 return Err(unsupported(
11360 "a 128x128 PARTITION_NONE block's chroma (its 64x64 uv plane block is four TX_32X32 units, and this decoder codes one whole-plane chroma unit per block)",
11361 ));
11362 }
11363 Ok(part128)
11364}
11365
11366pub(crate) fn decode_key_frame_tile_with_cdfs(
11367 tiles: &[&[u8]],
11368 tile_info: &TileInfo,
11369 mi_cols: u32,
11370 mi_rows: u32,
11371 base_q_idx: u8,
11372 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
11373 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
11374 // tile alongside [`CURRENT_Q_IDX`].
11375 deltas: crate::quant::QuantDeltas,
11376 frame_width: u32,
11377 frame_height: u32,
11378 enable_filter_intra: bool,
11379 enable_edge_filter: bool,
11380 cdef: &CdefParams,
11381 loop_filter: &LoopFilterParams,
11382 lr: &LoopRestorationParams,
11383 initial_cdfs: Option<Cdfs>,
11384 tx_select: bool,
11385 reduced_tx_set: bool,
11386 allow_screen_content_tools: bool,
11387 allow_intrabc: bool,
11388 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
11389 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
11390 // `stream.rs` still refuses a frame with `lf_present` set before this
11391 // function is ever called.
11392 delta: DeltaParams,
11393) -> Result<(Picture, Cdfs)> {
11394 if mi_cols == 0 || mi_rows == 0 {
11395 return Err(unsupported("a frame with no mode-info grid"));
11396 }
11397 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
11398 let sb128 = sb128();
11399 if sb128 && allow_intrabc {
11400 return Err(unsupported(
11401 "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)",
11402 ));
11403 }
11404 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
11405 INTRABC_MI_GRID.with(|g| {
11406 *g.borrow_mut() = allow_intrabc.then(|| {
11407 (
11408 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
11409 mi_cols as usize,
11410 mi_rows as usize,
11411 )
11412 });
11413 });
11414 INTRABC_DV.with(|c| c.set(None));
11415 CDEF_BITS.with(|c| c.set(cdef.bits));
11416 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
11417 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
11418 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
11419 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
11420 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
11421 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
11422 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
11423 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
11424 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
11425 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
11426
11427 let mut y = PlaneBuf {
11428 data: vec![0u16; width * height],
11429 width,
11430 height,
11431 true_width,
11432 true_height,
11433 tile_x0: 0,
11434 tile_y0: 0,
11435 tile_x1: width,
11436 tile_y1: height,
11437 };
11438 let mut u = PlaneBuf {
11439 data: vec![0u16; width * height / 4],
11440 width: width / 2,
11441 height: height / 2,
11442 true_width: true_width / 2,
11443 true_height: true_height / 2,
11444 tile_x0: 0,
11445 tile_y0: 0,
11446 tile_x1: width / 2,
11447 tile_y1: height / 2,
11448 };
11449 let mut v = PlaneBuf {
11450 data: vec![0u16; width * height / 4],
11451 width: width / 2,
11452 height: height / 2,
11453 true_width: true_width / 2,
11454 true_height: true_height / 2,
11455 tile_x0: 0,
11456 tile_y0: 0,
11457 tile_x1: width / 2,
11458 tile_y1: height / 2,
11459 };
11460
11461 let scan32 = default_scan(TX32);
11462 let scan16 = default_scan(TX16);
11463 let scan8 = default_scan(TX8);
11464 let scan4 = default_scan(TX4);
11465
11466 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
11467 let mut result_cdfs = base_cdfs.clone();
11468 let mut neighbours = Neighbours::new(
11469 cols32 as usize * 2,
11470 rows32 as usize * 2,
11471 mi_cols as usize,
11472 mi_rows as usize,
11473 );
11474 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
11475 let mut lr_reference = [(
11476 crate::restoration::WienerInfo::default(),
11477 crate::restoration::SgrprojInfo::default(),
11478 ); 3];
11479
11480 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
11481 // own byte range and its own fresh copy of the frame's initial CDFs
11482 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
11483 // `context_update_tile_id` has its end-of-tile adapted table kept as the
11484 // frame's own output (spec `exit_symbol`) -- every other tile's
11485 // adaptation is discarded, matching the refusal this replaces.
11486 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
11487 let tile_num = tile_idx as u32;
11488 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
11489 let mi_row0 = tile_info.mi_row_starts[trow as usize];
11490 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
11491 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
11492 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
11493 // Tile boundaries are always superblock-aligned in mi units (spec
11494 // 5.9.15's uniform/non-uniform derivation both only ever emit
11495 // multiples of the superblock's own mi size), so plain division is
11496 // exact here -- no rounding needed.
11497 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
11498 // tile boundary) are always superblock-aligned by spec 5.9.15; the
11499 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
11500 // last entry) is not, so the upper bound needs `div_ceil` the same
11501 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
11502 // trailing partial superblock row/column in scope.
11503 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
11504 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
11505
11506 let mut cdfs = base_cdfs.clone();
11507 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
11508 // `base_q_idx` at the top of every tile, not once per frame.
11509 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
11510 QUANT_DELTAS.with(|c| c.set(deltas));
11511 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
11512 if std::env::var_os("EC_AV1_TRACE").is_some() {
11513 eprintln!(
11514 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
11515 tile_bytes.len(),
11516 &tile_bytes[..tile_bytes.len().min(8)]
11517 );
11518 }
11519 let mut dec = SymbolDecoder::new(tile_bytes);
11520 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
11521 y.set_tile_origin(
11522 mi_col0 as usize * 4,
11523 mi_row0 as usize * 4,
11524 (mi_col1 as usize * 4).min(y.width),
11525 (mi_row1 as usize * 4).min(y.height),
11526 );
11527 u.set_tile_origin(
11528 mi_col0 as usize * 2,
11529 mi_row0 as usize * 2,
11530 (mi_col1 as usize * 2).min(u.width),
11531 (mi_row1 as usize * 2).min(u.height),
11532 );
11533 v.set_tile_origin(
11534 mi_col0 as usize * 2,
11535 mi_row0 as usize * 2,
11536 (mi_col1 as usize * 2).min(v.width),
11537 (mi_row1 as usize * 2).min(v.height),
11538 );
11539 TILE_HITS.with(|c| c.set(c.get() + 1));
11540
11541 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
11542 // its one block covers all four 64x64 quadrants, so the remaining three
11543 // visits of this superblock code nothing at all.
11544 let mut sb128_none = false;
11545 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
11546 if row_start {
11547 neighbours.start_row();
11548 }
11549 if sb_start {
11550 sb128_none = false;
11551 }
11552 if sb128_none {
11553 continue;
11554 }
11555 {
11556 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
11557 // once for the whole 128x128 (spec 5.11.57 is called with the
11558 // superblock's own size), then one partition symbol off the
11559 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
11560 // recurses into the four 64x64 quadrants this decoder codes.
11561 if sb128 && sb_start {
11562 let part128 = read_sb128_root(
11563 &mut dec,
11564 &mut cdfs,
11565 &neighbours,
11566 lr,
11567 &mut lr_grid,
11568 &mut lr_reference,
11569 sb_r,
11570 sb_c,
11571 mi_cols,
11572 mi_rows,
11573 )?;
11574 if part128 == PARTITION_NONE {
11575 // One 128x128 intra block: four TX_64X64 luma units and a
11576 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
11577 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
11578 // block). No CfL, no filter intra, no palette at this size --
11579 // [`read_intra_mode`]'s own size gates already say so.
11580 sb128_none = true;
11581 CDEF_TRANSMITTED.with(|c| c.set(false));
11582 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
11583 decode_block(
11584 &mut dec,
11585 &mut cdfs,
11586 &mut neighbours,
11587 at128,
11588 SB * 2,
11589 TxbSet::Luma64,
11590 TxbSet::Chroma32,
11591 TX32,
11592 TX32,
11593 (&scan32, &scan32),
11594 false,
11595 &mut y,
11596 &mut u,
11597 &mut v,
11598 base_q_idx,
11599 enable_filter_intra,
11600 allow_screen_content_tools,
11601 allow_intrabc,
11602 &scan32,
11603 &scan16,
11604 &scan8,
11605 &scan4,
11606 tx_select,
11607 reduced_tx_set,
11608 )?;
11609 // libaom writes one `cdef_strength` into the block's own
11610 // `MB_MODE_INFO`, which every mi cell of the block --
11611 // hence all four 64x64 CDEF units -- points at; our grid
11612 // is per-unit, so the read (which only ever lands in the
11613 // top-left unit, `read_cdef`'s index 0) is copied across.
11614 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
11615 CDEF_IDX_GRID.with(|g| {
11616 let mut g = g.borrow_mut();
11617 let cols = CDEF_SB_COLS.with(|c| c.get());
11618 if cols > 0 && q_r * cols + q_c < g.len() {
11619 let idx = g[q_r * cols + q_c];
11620 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
11621 let i = (q_r + dr) * cols + q_c + dc;
11622 if q_c + dc < cols && i < g.len() {
11623 g[i] = idx;
11624 }
11625 }
11626 }
11627 });
11628 continue;
11629 }
11630 }
11631 if !sb128 {
11632 crate::restoration::read_lr(
11633 &mut dec,
11634 &mut cdfs,
11635 lr,
11636 &mut lr_grid,
11637 &mut lr_reference,
11638 sb_r * SB_MI,
11639 sb_c * SB_MI,
11640 SB_MI,
11641 );
11642 }
11643 CDEF_TRANSMITTED.with(|c| c.set(false));
11644 let at = (sb_r as usize * 4, sb_c as usize * 4);
11645 let ctx = neighbours.partition_ctx(at, SB);
11646 let (has_cols, has_rows) = (
11647 sb_c * SB_MI + SB_MI / 2 < mi_cols,
11648 sb_r * SB_MI + SB_MI / 2 < mi_rows,
11649 );
11650 // Recomputed at this superblock's own half (spec
11651 // `decode_partition`): a full alphabet symbol when both halves are
11652 // inside the true frame, a single gathered bit when just one is
11653 // (the superblock cannot be left whole, so this is forced split),
11654 // and nothing at all (SPLIT inferred, no bits) when neither is —
11655 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
11656 // three-way write exactly.
11657 let part = if has_cols && has_rows {
11658 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
11659 if std::env::var_os("EC_AV1_TRACE").is_some() {
11660 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
11661 }
11662 p
11663 } else {
11664 match (has_cols, has_rows) {
11665 (true, false) => {
11666 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
11667 }
11668 (false, true) => {
11669 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
11670 }
11671 _ => {}
11672 }
11673 PARTITION_SPLIT
11674 };
11675 match part {
11676 PARTITION_NONE => {
11677 decode_block(
11678 &mut dec,
11679 &mut cdfs,
11680 &mut neighbours,
11681 at,
11682 SB,
11683 TxbSet::Luma64,
11684 TxbSet::Chroma32,
11685 TX32,
11686 TX32,
11687 (&scan32, &scan32),
11688 false,
11689 &mut y,
11690 &mut u,
11691 &mut v,
11692 base_q_idx,
11693 enable_filter_intra,
11694 allow_screen_content_tools,
11695 allow_intrabc,
11696 &scan32,
11697 &scan16,
11698 &scan8,
11699 &scan4,
11700 tx_select,
11701 reduced_tx_set,
11702 )?;
11703 }
11704 PARTITION_SPLIT => {
11705 for q in 0..4 {
11706 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
11707 if r32 >= rows32 || c32 >= cols32 {
11708 continue;
11709 }
11710 let at32 = (r32 as usize * 2, c32 as usize * 2);
11711 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
11712 let (has_cols32, has_rows32) = (
11713 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
11714 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
11715 );
11716 let part32 = if has_cols32 && has_rows32 {
11717 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
11718 if std::env::var_os("EC_AV1_TRACE").is_some() {
11719 let (rng, _) = dec.debug_state();
11720 eprintln!(
11721 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
11722 r32 * BLOCK_MI,
11723 c32 * BLOCK_MI
11724 );
11725 }
11726 p
11727 } else {
11728 match (has_cols32, has_rows32) {
11729 (true, false) => {
11730 dec.symbol_fixed(&gather(
11731 &cdfs.partition_w32[ctx32],
11732 VERT_ALIKE,
11733 ));
11734 }
11735 (false, true) => {
11736 dec.symbol_fixed(&gather(
11737 &cdfs.partition_w32[ctx32],
11738 HORZ_ALIKE,
11739 ));
11740 }
11741 _ => {}
11742 }
11743 PARTITION_SPLIT
11744 };
11745 match part32 {
11746 PARTITION_NONE => {
11747 decode_block(
11748 &mut dec,
11749 &mut cdfs,
11750 &mut neighbours,
11751 at32,
11752 BLOCK,
11753 TxbSet::Luma32,
11754 TxbSet::Chroma16,
11755 TX32,
11756 TX16,
11757 (&scan32, &scan16),
11758 true,
11759 &mut y,
11760 &mut u,
11761 &mut v,
11762 base_q_idx,
11763 enable_filter_intra,
11764 allow_screen_content_tools,
11765 allow_intrabc,
11766 &scan32,
11767 &scan16,
11768 &scan8,
11769 &scan4,
11770 tx_select,
11771 reduced_tx_set,
11772 )?;
11773 }
11774 PARTITION_SPLIT => {
11775 for sub in 0..4 {
11776 let (sr, sc) =
11777 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
11778 if (sr as u32) * SUB_MI >= mi_rows
11779 || (sc as u32) * SUB_MI >= mi_cols
11780 {
11781 continue;
11782 }
11783 let (has_cols16, has_rows16) = (
11784 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
11785 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
11786 );
11787 let at16 = (sr, sc);
11788 let ctx16 = neighbours.partition_ctx(at16, SUB);
11789 if has_cols16 && has_rows16 {
11790 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
11791 if std::env::var_os("EC_AV1_TRACE").is_some() {
11792 eprintln!(
11793 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
11794 at16.0, at16.1
11795 );
11796 }
11797 if part16 == PARTITION_NONE {
11798 decode_block(
11799 &mut dec,
11800 &mut cdfs,
11801 &mut neighbours,
11802 at16,
11803 SUB,
11804 TxbSet::Luma16,
11805 TxbSet::Chroma8,
11806 TX16,
11807 TX8,
11808 (&scan16, &scan8),
11809 true,
11810 &mut y,
11811 &mut u,
11812 &mut v,
11813 base_q_idx,
11814 enable_filter_intra,
11815 allow_screen_content_tools,
11816 allow_intrabc,
11817 &scan32,
11818 &scan16,
11819 &scan8,
11820 &scan4,
11821 tx_select,
11822 reduced_tx_set,
11823 )?;
11824 continue;
11825 }
11826 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
11827 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
11828 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
11829 // `decode_partition` visit order (decodeframe.c):
11830 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
11831 // HORZ_B: top 16x8, BL 8x8, BR 8x8
11832 // VERT_A: TL 8x8, BL 8x8, right 8x16
11833 // VERT_B: left 8x16, TR 8x8, BR 8x8
11834 // The squares go through `decode_leaf8`, the strip through
11835 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
11836 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
11837 // used refuses the non-skip case at this size). Both writers keep
11838 // mi-granular mode/skip/palette records, so a later block's
11839 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
11840 // 16x16 cell.
11841 //
11842 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
11843 // top-right neighbour is the partition's own not-yet-decoded
11844 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
11845 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
11846 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
11847 let arm = part16 - PARTITION_HORZ_A;
11848 bump_ab16(arm);
11849 if part16 == PARTITION_VERT_B {
11850 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
11851 }
11852 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
11853 Some(crate::encode::Reach::vert_ab_partition())
11854 } else {
11855 None
11856 };
11857 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
11858 macro_rules! ab_leaf8 {
11859 ($mi:expr, $prev:expr) => {
11860 decode_leaf8(
11861 &mut dec,
11862 &mut cdfs,
11863 &mut neighbours,
11864 at16,
11865 $mi,
11866 (&scan8, &scan4),
11867 $prev,
11868 &mut y,
11869 &mut u,
11870 &mut v,
11871 base_q_idx,
11872 enable_filter_intra,
11873 allow_screen_content_tools,
11874 allow_intrabc,
11875 tx_select,
11876 reduced_tx_set,
11877 )?
11878 };
11879 }
11880 macro_rules! ab_strip {
11881 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
11882 decode_leaf_rect(
11883 &mut dec,
11884 &mut cdfs,
11885 &mut neighbours,
11886 at16,
11887 $mi,
11888 $bw,
11889 $bh,
11890 $prev,
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 };
11901 }
11902 let tl = (mi_row0, mi_col0);
11903 let tr = (mi_row0, mi_col0 + 2);
11904 let bl = (mi_row0 + 2, mi_col0);
11905 let br = (mi_row0 + 2, mi_col0 + 2);
11906 let mut done: Vec<((usize, usize), usize)> = Vec::new();
11907 match part16 {
11908 PARTITION_HORZ_A => {
11909 let m_tl = ab_leaf8!(tl, done.last().copied());
11910 done.push((tl, m_tl));
11911 let m_tr = ab_leaf8!(tr, done.last().copied());
11912 done.push((tr, m_tr));
11913 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
11914 done.push((bl, m_bot));
11915 }
11916 PARTITION_HORZ_B => {
11917 let m_top = ab_strip!(tl, 16, 8, None);
11918 done.push((tl, m_top));
11919 let m_bl = ab_leaf8!(bl, done.last().copied());
11920 done.push((bl, m_bl));
11921 let m_br = ab_leaf8!(br, done.last().copied());
11922 done.push((br, m_br));
11923 }
11924 PARTITION_VERT_A => {
11925 let m_tl = ab_leaf8!(tl, done.last().copied());
11926 done.push((tl, m_tl));
11927 let m_bl = ab_leaf8!(bl, done.last().copied());
11928 done.push((bl, m_bl));
11929 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
11930 done.push((tr, m_right));
11931 }
11932 _ => {
11933 let m_left = ab_strip!(tl, 8, 16, None);
11934 done.push((tl, m_left));
11935 let m_tr = ab_leaf8!(tr, done.last().copied());
11936 done.push((tr, m_tr));
11937 let m_br = ab_leaf8!(br, done.last().copied());
11938 done.push((br, m_br));
11939 }
11940 }
11941 // Same coarse-slot write-back the real SPLIT path takes: the
11942 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
11943 // sub-block on the parent's bottom / right edge (the mi-exact map
11944 // above wins wherever it has an entry).
11945 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
11946 continue;
11947 }
11948 if part16 == PARTITION_HORZ {
11949 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
11950 let (mi_row0, mi_col0) = (
11951 sr as u32 * SUB_MI,
11952 sc as u32 * SUB_MI,
11953 );
11954 let top = (mi_row0 as usize, mi_col0 as usize);
11955 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
11956 let mode_top = decode_leaf_rect(
11957 &mut dec,
11958 &mut cdfs,
11959 &mut neighbours,
11960 at16,
11961 top,
11962 16,
11963 8,
11964 None,
11965 &mut y,
11966 &mut u,
11967 &mut v,
11968 enable_filter_intra,
11969 allow_screen_content_tools,
11970 base_q_idx,
11971 tx_select,
11972 reduced_tx_set,
11973 )?;
11974 let mode_bot = decode_leaf_rect(
11975 &mut dec,
11976 &mut cdfs,
11977 &mut neighbours,
11978 at16,
11979 bot,
11980 16,
11981 8,
11982 Some((top, mode_top)),
11983 &mut y,
11984 &mut u,
11985 &mut v,
11986 enable_filter_intra,
11987 allow_screen_content_tools,
11988 base_q_idx,
11989 tx_select,
11990 reduced_tx_set,
11991 )?;
11992 neighbours.above_mode[sc] = mode_bot;
11993 neighbours.left_mode[sr] = mode_bot;
11994 continue;
11995 }
11996 if part16 == PARTITION_VERT {
11997 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
11998 let (mi_row0, mi_col0) = (
11999 sr as u32 * SUB_MI,
12000 sc as u32 * SUB_MI,
12001 );
12002 let left = (mi_row0 as usize, mi_col0 as usize);
12003 let right = (mi_row0 as usize, mi_col0 as usize + 2);
12004 let mode_left = decode_leaf_rect(
12005 &mut dec,
12006 &mut cdfs,
12007 &mut neighbours,
12008 at16,
12009 left,
12010 8,
12011 16,
12012 None,
12013 &mut y,
12014 &mut u,
12015 &mut v,
12016 enable_filter_intra,
12017 allow_screen_content_tools,
12018 base_q_idx,
12019 tx_select,
12020 reduced_tx_set,
12021 )?;
12022 let mode_right = decode_leaf_rect(
12023 &mut dec,
12024 &mut cdfs,
12025 &mut neighbours,
12026 at16,
12027 right,
12028 8,
12029 16,
12030 Some((left, mode_left)),
12031 &mut y,
12032 &mut u,
12033 &mut v,
12034 enable_filter_intra,
12035 allow_screen_content_tools,
12036 base_q_idx,
12037 tx_select,
12038 reduced_tx_set,
12039 )?;
12040 neighbours.above_mode[sc] = mode_right;
12041 neighbours.left_mode[sr] = mode_right;
12042 continue;
12043 }
12044 if part16 != PARTITION_SPLIT {
12045 return Err(unsupported(
12046 "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)",
12047 ));
12048 }
12049 // A real (non-straddle) SPLIT of a
12050 // whole 16x16 into four 8x8 leaves --
12051 // the same recursion the straddle
12052 // path below already runs when the
12053 // true frame edge forces it, just
12054 // over all four positions instead of
12055 // the one or two the edge leaves.
12056 let (mi_row0, mi_col0) =
12057 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
12058 // Each 8x8 leaf's intra-mode context
12059 // must see its own siblings: the
12060 // bottom-left leaf's ABOVE neighbour
12061 // is leaf 0, not the previously
12062 // decoded leaf 1 (and the bottom-right
12063 // leaf's above is leaf 1, while
12064 // `prev_leaf` only ever carried the
12065 // immediately preceding one). The
12066 // coarse `above_mode`/`left_mode`
12067 // arrays hold one slot per 16x16, so
12068 // the sibling modes are swapped in
12069 // around each leaf call and restored
12070 // after; the loop tail writes the last
12071 // leaf's mode as before.
12072 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
12073 for i in 0..4 {
12074 let (mr, mc) =
12075 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
12076 let leaf_mi = (mr as usize, mc as usize);
12077 let li = i as usize;
12078 let saved_modes =
12079 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
12080 if li >= 2 {
12081 if let Some((below, _)) = sib_modes[li - 2] {
12082 neighbours.above_mode[sc] = below;
12083 }
12084 }
12085 if li % 2 == 1 {
12086 if let Some((_, right)) = sib_modes[li - 1] {
12087 neighbours.left_mode[sr] = right;
12088 }
12089 }
12090 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
12091 let part8 =
12092 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
12093 if std::env::var_os("EC_AV1_TRACE").is_some() {
12094 eprintln!(
12095 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
12096 );
12097 }
12098 let leaf_mode = if part8 == PARTITION_NONE {
12099 decode_leaf8(
12100 &mut dec,
12101 &mut cdfs,
12102 &mut neighbours,
12103 at16,
12104 leaf_mi,
12105 (&scan8, &scan4),
12106 None,
12107 &mut y,
12108 &mut u,
12109 &mut v,
12110 base_q_idx,
12111 enable_filter_intra,
12112 allow_screen_content_tools,
12113 allow_intrabc,
12114 tx_select,
12115 reduced_tx_set,
12116 ).map(|m| (m, m))?
12117 } else if part8 == PARTITION_SPLIT {
12118 decode_leaf_split4(
12119 &mut dec,
12120 &mut cdfs,
12121 &mut neighbours,
12122 at16,
12123 leaf_mi,
12124 &scan4,
12125 None,
12126 &mut y,
12127 &mut u,
12128 &mut v,
12129 base_q_idx,
12130 enable_filter_intra,
12131 allow_intrabc,
12132 reduced_tx_set,
12133 )?
12134 } else if part8 == PARTITION_HORZ
12135 || part8 == PARTITION_VERT
12136 {
12137 decode_leaf_rect8(
12138 &mut dec,
12139 &mut cdfs,
12140 &mut neighbours,
12141 at16,
12142 leaf_mi,
12143 part8 == PARTITION_VERT,
12144 &scan4,
12145 &mut y,
12146 &mut u,
12147 &mut v,
12148 base_q_idx,
12149 enable_filter_intra,
12150 allow_intrabc,
12151 tx_select,
12152 reduced_tx_set,
12153 )?
12154 } else {
12155 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
12156 };
12157 neighbours.above_mode[sc] = saved_modes.0;
12158 neighbours.left_mode[sr] = saved_modes.1;
12159 sib_modes[li] = Some(leaf_mode);
12160 }
12161 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
12162 neighbours.above_mode[sc] = below;
12163 }
12164 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
12165 neighbours.left_mode[sr] = right;
12166 }
12167 continue;
12168 }
12169 // The true edge falls inside this 16x16
12170 // leaf itself (mod-32==8 target sizes,
12171 // lane-av1-rect): one axis only -- an 8x8
12172 // leaf never itself straddles, so the
12173 // block splits cleanly along whichever
12174 // axis is short.
12175 if !has_cols16 && !has_rows16 {
12176 return Err(unsupported(
12177 "a 16x16 block whose true edge cuts through both \
12178 axes needs a rectangular transform this decoder \
12179 does not code yet",
12180 ));
12181 }
12182 if has_cols16 {
12183 dec.symbol_fixed(&gather(
12184 &cdfs.partition_w16[ctx16],
12185 VERT_ALIKE,
12186 ));
12187 } else {
12188 dec.symbol_fixed(&gather(
12189 &cdfs.partition_w16[ctx16],
12190 HORZ_ALIKE,
12191 ));
12192 }
12193 let (mi_row0, mi_col0) =
12194 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
12195 let leaf_positions: Vec<(u32, u32)> = (0..4)
12196 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
12197 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
12198 .collect();
12199 // See the sibling-mode note in the clean
12200 // SPLIT path above.
12201 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
12202 for (mr, mc) in leaf_positions {
12203 let leaf_mi = (mr as usize, mc as usize);
12204 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
12205 as usize;
12206 let saved_modes =
12207 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
12208 if li >= 2 {
12209 if let Some((below, _)) = sib_modes[li - 2] {
12210 neighbours.above_mode[sc] = below;
12211 }
12212 }
12213 if li % 2 == 1 {
12214 if let Some((_, right)) = sib_modes[li - 1] {
12215 neighbours.left_mode[sr] = right;
12216 }
12217 }
12218 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
12219 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
12220 if std::env::var_os("EC_AV1_TRACE").is_some() {
12221 eprintln!(
12222 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
12223 );
12224 }
12225 let leaf_mode = if part8 == PARTITION_NONE {
12226 decode_leaf8(
12227 &mut dec,
12228 &mut cdfs,
12229 &mut neighbours,
12230 at16,
12231 leaf_mi,
12232 (&scan8, &scan4),
12233 None,
12234 &mut y,
12235 &mut u,
12236 &mut v,
12237 base_q_idx,
12238 enable_filter_intra,
12239 allow_screen_content_tools,
12240 allow_intrabc,
12241 tx_select,
12242 reduced_tx_set,
12243 ).map(|m| (m, m))?
12244 } else if part8 == PARTITION_SPLIT {
12245 decode_leaf_split4(
12246 &mut dec,
12247 &mut cdfs,
12248 &mut neighbours,
12249 at16,
12250 leaf_mi,
12251 &scan4,
12252 None,
12253 &mut y,
12254 &mut u,
12255 &mut v,
12256 base_q_idx,
12257 enable_filter_intra,
12258 allow_intrabc,
12259 reduced_tx_set,
12260 )?
12261 } else if part8 == PARTITION_HORZ
12262 || part8 == PARTITION_VERT
12263 {
12264 decode_leaf_rect8(
12265 &mut dec,
12266 &mut cdfs,
12267 &mut neighbours,
12268 at16,
12269 leaf_mi,
12270 part8 == PARTITION_VERT,
12271 &scan4,
12272 &mut y,
12273 &mut u,
12274 &mut v,
12275 base_q_idx,
12276 enable_filter_intra,
12277 allow_intrabc,
12278 tx_select,
12279 reduced_tx_set,
12280 )?
12281 } else {
12282 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
12283 };
12284 neighbours.above_mode[sc] = saved_modes.0;
12285 neighbours.left_mode[sr] = saved_modes.1;
12286 sib_modes[li] = Some(leaf_mode);
12287 }
12288 // `record()`'s `above_mode`/`left_mode`
12289 // write is a no-op at an 8x8 leaf's own
12290 // side, so force the write once the whole
12291 // 16x16 slot's leaves are done, from the
12292 // last leaf (mirrors the writer's r15
12293 // fix).
12294 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
12295 neighbours.above_mode[sc] = below;
12296 }
12297 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
12298 neighbours.left_mode[sr] = right;
12299 }
12300 }
12301 }
12302 PARTITION_HORZ => {
12303 // lane-intradisp r1: two true 32x16 strips.
12304 decode_block_rect(
12305 &mut dec,
12306 &mut cdfs,
12307 &mut neighbours,
12308 at32,
12309 32,
12310 16,
12311 &mut y,
12312 &mut u,
12313 &mut v,
12314 enable_filter_intra,
12315 allow_screen_content_tools,
12316 base_q_idx,
12317 tx_select,
12318 reduced_tx_set,
12319 )?;
12320 decode_block_rect(
12321 &mut dec,
12322 &mut cdfs,
12323 &mut neighbours,
12324 (at32.0 + 1, at32.1),
12325 32,
12326 16,
12327 &mut y,
12328 &mut u,
12329 &mut v,
12330 enable_filter_intra,
12331 allow_screen_content_tools,
12332 base_q_idx,
12333 tx_select,
12334 reduced_tx_set,
12335 )?;
12336 }
12337 PARTITION_VERT => {
12338 // lane-intradisp r1: mirror of PARTITION_HORZ
12339 // above with width/height swapped.
12340 decode_block_rect(
12341 &mut dec,
12342 &mut cdfs,
12343 &mut neighbours,
12344 at32,
12345 16,
12346 32,
12347 &mut y,
12348 &mut u,
12349 &mut v,
12350 enable_filter_intra,
12351 allow_screen_content_tools,
12352 base_q_idx,
12353 tx_select,
12354 reduced_tx_set,
12355 )?;
12356 decode_block_rect(
12357 &mut dec,
12358 &mut cdfs,
12359 &mut neighbours,
12360 (at32.0, at32.1 + 1),
12361 16,
12362 32,
12363 &mut y,
12364 &mut u,
12365 &mut v,
12366 enable_filter_intra,
12367 allow_screen_content_tools,
12368 base_q_idx,
12369 tx_select,
12370 reduced_tx_set,
12371 )?;
12372 }
12373 PARTITION_HORZ_A => {
12374 // lane-part32 r1: two 16x16 squares on top +
12375 // a true 32x16 strip below (mirrors
12376 // decode_inter_block's cd6cb6d HORZ_A: TL,
12377 // TR, bottom strip).
12378 INTRA_HORZ_A_HITS.with(|c| c.set(c.get() + 1));
12379 decode_block(
12380 &mut dec,
12381 &mut cdfs,
12382 &mut neighbours,
12383 at32,
12384 SUB,
12385 TxbSet::Luma16,
12386 TxbSet::Chroma8,
12387 TX16,
12388 TX8,
12389 (&scan16, &scan8),
12390 true,
12391 &mut y,
12392 &mut u,
12393 &mut v,
12394 base_q_idx,
12395 enable_filter_intra,
12396 allow_screen_content_tools,
12397 allow_intrabc,
12398 &scan32,
12399 &scan16,
12400 &scan8,
12401 &scan4,
12402 tx_select,
12403 reduced_tx_set,
12404 )?;
12405 decode_block(
12406 &mut dec,
12407 &mut cdfs,
12408 &mut neighbours,
12409 (at32.0, at32.1 + 1),
12410 SUB,
12411 TxbSet::Luma16,
12412 TxbSet::Chroma8,
12413 TX16,
12414 TX8,
12415 (&scan16, &scan8),
12416 true,
12417 &mut y,
12418 &mut u,
12419 &mut v,
12420 base_q_idx,
12421 enable_filter_intra,
12422 allow_screen_content_tools,
12423 allow_intrabc,
12424 &scan32,
12425 &scan16,
12426 &scan8,
12427 &scan4,
12428 tx_select,
12429 reduced_tx_set,
12430 )?;
12431 decode_block_rect(
12432 &mut dec,
12433 &mut cdfs,
12434 &mut neighbours,
12435 (at32.0 + 1, at32.1),
12436 32,
12437 16,
12438 &mut y,
12439 &mut u,
12440 &mut v,
12441 enable_filter_intra,
12442 allow_screen_content_tools,
12443 base_q_idx,
12444 tx_select,
12445 reduced_tx_set,
12446 )?;
12447 }
12448 PARTITION_HORZ_B => {
12449 // lane-part32 r1: a true 32x16 strip on top +
12450 // two 16x16 squares below (mirrors HORZ_A
12451 // with the strip/squares order flipped, same
12452 // shape as libaom decode_partition's HORZ_B).
12453 INTRA_HORZ_B_HITS.with(|c| c.set(c.get() + 1));
12454 decode_block_rect(
12455 &mut dec,
12456 &mut cdfs,
12457 &mut neighbours,
12458 at32,
12459 32,
12460 16,
12461 &mut y,
12462 &mut u,
12463 &mut v,
12464 enable_filter_intra,
12465 allow_screen_content_tools,
12466 base_q_idx,
12467 tx_select,
12468 reduced_tx_set,
12469 )?;
12470 decode_block(
12471 &mut dec,
12472 &mut cdfs,
12473 &mut neighbours,
12474 (at32.0 + 1, at32.1),
12475 SUB,
12476 TxbSet::Luma16,
12477 TxbSet::Chroma8,
12478 TX16,
12479 TX8,
12480 (&scan16, &scan8),
12481 true,
12482 &mut y,
12483 &mut u,
12484 &mut v,
12485 base_q_idx,
12486 enable_filter_intra,
12487 allow_screen_content_tools,
12488 allow_intrabc,
12489 &scan32,
12490 &scan16,
12491 &scan8,
12492 &scan4,
12493 tx_select,
12494 reduced_tx_set,
12495 )?;
12496 decode_block(
12497 &mut dec,
12498 &mut cdfs,
12499 &mut neighbours,
12500 (at32.0 + 1, at32.1 + 1),
12501 SUB,
12502 TxbSet::Luma16,
12503 TxbSet::Chroma8,
12504 TX16,
12505 TX8,
12506 (&scan16, &scan8),
12507 true,
12508 &mut y,
12509 &mut u,
12510 &mut v,
12511 base_q_idx,
12512 enable_filter_intra,
12513 allow_screen_content_tools,
12514 allow_intrabc,
12515 &scan32,
12516 &scan16,
12517 &scan8,
12518 &scan4,
12519 tx_select,
12520 reduced_tx_set,
12521 )?;
12522 }
12523 PARTITION_VERT_A => {
12524 // lane-part32 r1: mirror of HORZ_A with
12525 // width/height swapped (TL, BL, right 16x32
12526 // strip).
12527 INTRA_VERT_A_HITS.with(|c| c.set(c.get() + 1));
12528 let _vert_ab = crate::encode::Reach::vert_ab_partition();
12529 decode_block(
12530 &mut dec,
12531 &mut cdfs,
12532 &mut neighbours,
12533 at32,
12534 SUB,
12535 TxbSet::Luma16,
12536 TxbSet::Chroma8,
12537 TX16,
12538 TX8,
12539 (&scan16, &scan8),
12540 true,
12541 &mut y,
12542 &mut u,
12543 &mut v,
12544 base_q_idx,
12545 enable_filter_intra,
12546 allow_screen_content_tools,
12547 allow_intrabc,
12548 &scan32,
12549 &scan16,
12550 &scan8,
12551 &scan4,
12552 tx_select,
12553 reduced_tx_set,
12554 )?;
12555 decode_block(
12556 &mut dec,
12557 &mut cdfs,
12558 &mut neighbours,
12559 (at32.0 + 1, at32.1),
12560 SUB,
12561 TxbSet::Luma16,
12562 TxbSet::Chroma8,
12563 TX16,
12564 TX8,
12565 (&scan16, &scan8),
12566 true,
12567 &mut y,
12568 &mut u,
12569 &mut v,
12570 base_q_idx,
12571 enable_filter_intra,
12572 allow_screen_content_tools,
12573 allow_intrabc,
12574 &scan32,
12575 &scan16,
12576 &scan8,
12577 &scan4,
12578 tx_select,
12579 reduced_tx_set,
12580 )?;
12581 decode_block_rect(
12582 &mut dec,
12583 &mut cdfs,
12584 &mut neighbours,
12585 (at32.0, at32.1 + 1),
12586 16,
12587 32,
12588 &mut y,
12589 &mut u,
12590 &mut v,
12591 enable_filter_intra,
12592 allow_screen_content_tools,
12593 base_q_idx,
12594 tx_select,
12595 reduced_tx_set,
12596 )?;
12597 }
12598 PARTITION_VERT_B => {
12599 // lane-part32 r1: a true 16x32 strip on the
12600 // left + two 16x16 squares on the right
12601 // (libaom decode_partition VERT_B: left
12602 // strip, TR, BR).
12603 INTRA_VERT_B_HITS.with(|c| c.set(c.get() + 1));
12604 let _vert_ab = crate::encode::Reach::vert_ab_partition();
12605 decode_block_rect(
12606 &mut dec,
12607 &mut cdfs,
12608 &mut neighbours,
12609 at32,
12610 16,
12611 32,
12612 &mut y,
12613 &mut u,
12614 &mut v,
12615 enable_filter_intra,
12616 allow_screen_content_tools,
12617 base_q_idx,
12618 tx_select,
12619 reduced_tx_set,
12620 )?;
12621 decode_block(
12622 &mut dec,
12623 &mut cdfs,
12624 &mut neighbours,
12625 (at32.0, at32.1 + 1),
12626 SUB,
12627 TxbSet::Luma16,
12628 TxbSet::Chroma8,
12629 TX16,
12630 TX8,
12631 (&scan16, &scan8),
12632 true,
12633 &mut y,
12634 &mut u,
12635 &mut v,
12636 base_q_idx,
12637 enable_filter_intra,
12638 allow_screen_content_tools,
12639 allow_intrabc,
12640 &scan32,
12641 &scan16,
12642 &scan8,
12643 &scan4,
12644 tx_select,
12645 reduced_tx_set,
12646 )?;
12647 decode_block(
12648 &mut dec,
12649 &mut cdfs,
12650 &mut neighbours,
12651 (at32.0 + 1, at32.1 + 1),
12652 SUB,
12653 TxbSet::Luma16,
12654 TxbSet::Chroma8,
12655 TX16,
12656 TX8,
12657 (&scan16, &scan8),
12658 true,
12659 &mut y,
12660 &mut u,
12661 &mut v,
12662 base_q_idx,
12663 enable_filter_intra,
12664 allow_screen_content_tools,
12665 allow_intrabc,
12666 &scan32,
12667 &scan16,
12668 &scan8,
12669 &scan4,
12670 tx_select,
12671 reduced_tx_set,
12672 )?;
12673 }
12674 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
12675 // lane-tx64x16 r3: the 1:4 pair at the 32x32
12676 // level -- four 32x8 (or 8x32) strips in
12677 // raster order, `quarter_step` = 2 mi, with
12678 // libaom `decode_partition`'s own `i > 0`
12679 // frame-edge break.
12680 let horz = part32 == PARTITION_HORZ_4;
12681 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
12682 let mut prev: Option<((usize, usize), usize)> = None;
12683 for i in 0..4 {
12684 let strip_mi = if horz {
12685 (base_mi.0 + i * 2, base_mi.1)
12686 } else {
12687 (base_mi.0, base_mi.1 + i * 2)
12688 };
12689 if i > 0
12690 && (strip_mi.0 >= mi_rows as usize
12691 || strip_mi.1 >= mi_cols as usize)
12692 {
12693 break;
12694 }
12695 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
12696 let (mode, _uv) = decode_block_rect4(
12697 &mut dec,
12698 &mut cdfs,
12699 &mut neighbours,
12700 strip_mi,
12701 bw,
12702 bh,
12703 prev,
12704 &mut y,
12705 &mut u,
12706 &mut v,
12707 enable_filter_intra,
12708 allow_screen_content_tools,
12709 base_q_idx,
12710 tx_select,
12711 )?;
12712 prev = Some((strip_mi, mode));
12713 }
12714 }
12715 _ => {
12716 return Err(unsupported(format!(
12717 "a 32x32 partition type this decoder does not code (value={part32})"
12718 )));
12719 }
12720 }
12721 }
12722 }
12723 PARTITION_HORZ => {
12724 // lane-sbpart r2: two true 64x32 strips.
12725 decode_block_rect64(
12726 &mut dec,
12727 &mut cdfs,
12728 &mut neighbours,
12729 at,
12730 64,
12731 32,
12732 &mut y,
12733 &mut u,
12734 &mut v,
12735 enable_filter_intra,
12736 allow_screen_content_tools,
12737 base_q_idx,
12738 tx_select,
12739 reduced_tx_set,
12740 )?;
12741 decode_block_rect64(
12742 &mut dec,
12743 &mut cdfs,
12744 &mut neighbours,
12745 (at.0 + 2, at.1),
12746 64,
12747 32,
12748 &mut y,
12749 &mut u,
12750 &mut v,
12751 enable_filter_intra,
12752 allow_screen_content_tools,
12753 base_q_idx,
12754 tx_select,
12755 reduced_tx_set,
12756 )?;
12757 }
12758 PARTITION_VERT => {
12759 // lane-sbpart r2: mirror of PARTITION_HORZ above with
12760 // width/height swapped.
12761 decode_block_rect64(
12762 &mut dec,
12763 &mut cdfs,
12764 &mut neighbours,
12765 at,
12766 32,
12767 64,
12768 &mut y,
12769 &mut u,
12770 &mut v,
12771 enable_filter_intra,
12772 allow_screen_content_tools,
12773 base_q_idx,
12774 tx_select,
12775 reduced_tx_set,
12776 )?;
12777 decode_block_rect64(
12778 &mut dec,
12779 &mut cdfs,
12780 &mut neighbours,
12781 (at.0, at.1 + 2),
12782 32,
12783 64,
12784 &mut y,
12785 &mut u,
12786 &mut v,
12787 enable_filter_intra,
12788 allow_screen_content_tools,
12789 base_q_idx,
12790 tx_select,
12791 reduced_tx_set,
12792 )?;
12793 }
12794 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
12795 // lane-part32 r4: the four superblock-level AB arms, each
12796 // two 32x32 squares plus one 64x32/32x64 strip, in
12797 // libaom's own `decode_partition` order (decodeframe.c:
12798 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
12799 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
12800 // TR, BR). The pieces are exactly the ones already proven
12801 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
12802 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
12803 SB_AB_HITS.with(|c| {
12804 let mut h = c.get();
12805 h[part - PARTITION_HORZ_A] += 1;
12806 c.set(h);
12807 });
12808 // lane-part32 r5: only the two VERTICAL arms reorder the
12809 // square sub-blocks (TL, BL, TR, BR), so only they switch
12810 // libaom's `has_tr`/`has_bl` tables.
12811 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
12812 .then(crate::encode::Reach::vert_ab_partition);
12813 macro_rules! square32 {
12814 ($at:expr) => {
12815 decode_block(
12816 &mut dec,
12817 &mut cdfs,
12818 &mut neighbours,
12819 $at,
12820 BLOCK,
12821 TxbSet::Luma32,
12822 TxbSet::Chroma16,
12823 TX32,
12824 TX16,
12825 (&scan32, &scan16),
12826 true,
12827 &mut y,
12828 &mut u,
12829 &mut v,
12830 base_q_idx,
12831 enable_filter_intra,
12832 allow_screen_content_tools,
12833 allow_intrabc,
12834 &scan32,
12835 &scan16,
12836 &scan8,
12837 &scan4,
12838 tx_select,
12839 reduced_tx_set,
12840 )?
12841 };
12842 }
12843 macro_rules! strip64 {
12844 ($at:expr, $bw:expr, $bh:expr) => {
12845 decode_block_rect64(
12846 &mut dec,
12847 &mut cdfs,
12848 &mut neighbours,
12849 $at,
12850 $bw,
12851 $bh,
12852 &mut y,
12853 &mut u,
12854 &mut v,
12855 enable_filter_intra,
12856 allow_screen_content_tools,
12857 base_q_idx,
12858 tx_select,
12859 reduced_tx_set,
12860 )?
12861 };
12862 }
12863 let (br, bc) = (at.0 + 2, at.1 + 2);
12864 match part {
12865 PARTITION_HORZ_A => {
12866 square32!(at);
12867 square32!((at.0, bc));
12868 strip64!((br, at.1), 64, 32);
12869 }
12870 PARTITION_HORZ_B => {
12871 strip64!(at, 64, 32);
12872 square32!((br, at.1));
12873 square32!((br, bc));
12874 }
12875 PARTITION_VERT_A => {
12876 square32!(at);
12877 square32!((br, at.1));
12878 strip64!((at.0, bc), 32, 64);
12879 }
12880 _ => {
12881 strip64!(at, 32, 64);
12882 square32!((at.0, bc));
12883 square32!((br, bc));
12884 }
12885 }
12886 }
12887 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
12888 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
12889 // 16x64) strips in raster order. `decode_partition`
12890 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
12891 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
12892 // frame edge for `i > 0`, so a partial superblock codes
12893 // only the strips whose origin is inside the frame.
12894 let horz = part == PARTITION_HORZ_4;
12895 for i in 0..4 {
12896 let step_mi = i * (SB_MI as usize / 4);
12897 let (this_r_mi, this_c_mi) = if horz {
12898 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
12899 } else {
12900 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
12901 };
12902 if i > 0
12903 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
12904 {
12905 break;
12906 }
12907 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
12908 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
12909 decode_block_rect64(
12910 &mut dec,
12911 &mut cdfs,
12912 &mut neighbours,
12913 strip_at,
12914 bw,
12915 bh,
12916 &mut y,
12917 &mut u,
12918 &mut v,
12919 enable_filter_intra,
12920 allow_screen_content_tools,
12921 base_q_idx,
12922 tx_select,
12923 reduced_tx_set,
12924 )?;
12925 }
12926 }
12927 _ => {
12928 return Err(unsupported(
12929 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
12930 ));
12931 }
12932 }
12933 }
12934 }
12935
12936 if tile_num == tile_info.context_update_tile_id {
12937 result_cdfs = cdfs;
12938 }
12939 }
12940
12941 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
12942 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
12943 // that isolate whether a decode-order frame's mismatch already exists
12944 // in reconstruction (this dump) vs is introduced by the loop filter
12945 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
12946 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
12947 use std::io::Write;
12948 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12949 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12950 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
12951 let _ = f.write_all(&narrow(&y));
12952 let _ = f.write_all(&narrow(&u));
12953 let _ = f.write_all(&narrow(&v));
12954 }
12955 } else {
12956 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12957 }
12958 if let Ok(path) = std::env::var("EC_AV1_PREFILT_WIDE_DUMP") {
12959 use std::io::Write;
12960 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12961 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12962 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
12963 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
12964 for row in 0..plane.true_height {
12965 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
12966 }
12967 out
12968 };
12969 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12970 let _ = f.write_all(&crop_wide(&y));
12971 let _ = f.write_all(&crop_wide(&u));
12972 let _ = f.write_all(&crop_wide(&v));
12973 }
12974 }
12975 apply_deblock(
12976 &mut y,
12977 &mut u,
12978 &mut v,
12979 loop_filter,
12980 &neighbours,
12981 frame_width as usize,
12982 frame_height as usize,
12983 );
12984 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
12985 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
12986 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
12987 // dump above these bisect WHICH filter stage introduced a mismatch.
12988 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
12989 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
12990 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
12991 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
12992
12993 let (fw, fh) = (frame_width as usize, frame_height as usize);
12994 if fw == width && fh == height {
12995 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
12996 return Ok((
12997 Picture {
12998 width,
12999 height,
13000 y: y.data,
13001 u: u.data,
13002 v: v.data,
13003 },
13004 result_cdfs,
13005 ));
13006 }
13007 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
13008 let mut out = Vec::with_capacity(w * h);
13009 for row in 0..h {
13010 out.extend(plane.data[row * plane.width..][..w].iter().copied());
13011 }
13012 out
13013 };
13014 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
13015 // is the real reconstructed extent -- columns `[fw, true_width)` hold
13016 // genuine decoded samples (the last coding block straddles the frame
13017 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
13018 // libaom's superres upscale runs on that buffer's own border-extended
13019 // margin, so it reads those real columns, not a synthetic replicate of
13020 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
13021 // aomenc 43->64 stream pinned column-by-column against libaom's own
13022 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
13023 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
13024 // decoder used before was off by 1 at the columns the tap window
13025 // reaches into that real margin; `None` when there is no margin (this
13026 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
13027 // non-superres frame whose width just isn't 32-block aligned).
13028 LAST_FRAME_WIDE_MARGIN.with(|m| {
13029 *m.borrow_mut() = if true_width > fw || true_height > fh {
13030 let yc = crop(&y, true_width, true_height);
13031 if let Ok(path) = std::env::var("EC_AV1_MARGIN_DUMP") {
13032 use std::io::Write;
13033 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
13034 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
13035 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
13036 // corner-cut: this diagnostic dump stays 8-bit-narrowed
13037 // regardless of the stream's real bit depth (debug-only,
13038 // never read by a gate); widen if a >8-bit margin dump
13039 // is ever needed.
13040 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
13041 }
13042 }
13043 Some(Picture {
13044 width: true_width,
13045 height: true_height,
13046 y: yc,
13047 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
13048 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
13049 })
13050 } else {
13051 None
13052 }
13053 });
13054 Ok((
13055 Picture {
13056 width: fw,
13057 height: fh,
13058 y: crop(&y, fw, fh),
13059 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
13060 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
13061 },
13062 result_cdfs,
13063 ))
13064}
13065
13066/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
13067/// -- `above`/`left` are the neighbour's own resolved index for this
13068/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
13069/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
13070/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
13071/// block itself has a second reference) -- lane-av1idx: a stale "this
13072/// decoder never codes a compound reference" assumption baked this to
13073/// always-0, which desynced the CDF context bucket (not the decoded value
13074/// outright, hence small pixel deltas rather than a hard desync) the moment
13075/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
13076/// filter frame.
13077fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
13078 let base = dir * 8 + if is_compound { 4 } else { 0 };
13079 let term = if left == above {
13080 left
13081 } else if left == 3 {
13082 above
13083 } else if above == 3 {
13084 left
13085 } else {
13086 3
13087 };
13088 base + term as usize
13089}
13090
13091/// Resolves the interpolation filter kernel(s) an inter block's motion
13092/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
13093/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
13094/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
13095/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
13096/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
13097/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
13098/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
13099/// which forces `EIGHTTAP` without reading anything.
13100#[allow(clippy::too_many_arguments)]
13101fn resolve_interp_filter(
13102 dec: &mut SymbolDecoder,
13103 cdfs: &mut Cdfs,
13104 interp_fixed: Option<mc::InterpFilterKind>,
13105 enable_dual_filter: bool,
13106 force_regular: bool,
13107 above: [u8; 2],
13108 left: [u8; 2],
13109 is_compound: bool,
13110) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
13111 if let Some(kind) = interp_fixed {
13112 return (kind, kind, [3, 3]);
13113 }
13114 if force_regular {
13115 return (
13116 mc::InterpFilterKind::Regular,
13117 mc::InterpFilterKind::Regular,
13118 [0, 0],
13119 );
13120 }
13121 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
13122 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
13123 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
13124 // "horizontal then vertical" despite `predict_with_filters`' own
13125 // `h_kind`/`v_kind` argument order, which is why this function returns
13126 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
13127 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
13128 if std::env::var_os("EC_AV1_IFDBG").is_some() {
13129 eprintln!(
13130 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
13131 &cdfs.switchable_interp[ctx0][..3]
13132 );
13133 }
13134 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
13135 let sym1 = if enable_dual_filter {
13136 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
13137 if std::env::var_os("EC_AV1_IFDBG").is_some() {
13138 eprintln!(
13139 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
13140 &cdfs.switchable_interp[ctx1][..3]
13141 );
13142 }
13143 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
13144 } else {
13145 sym0
13146 };
13147 (
13148 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
13149 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
13150 [sym0, sym1],
13151 )
13152}
13153
13154/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
13155/// duplicating [`crate::tile`]'s private copy of the same rule.
13156pub(crate) fn intra_inter_ctx(
13157 has_above: bool,
13158 has_left: bool,
13159 above_inter: bool,
13160 left_inter: bool,
13161) -> usize {
13162 match (has_above, has_left) {
13163 (true, true) => {
13164 let (above_intra, left_intra) = (!above_inter, !left_inter);
13165 if above_intra && left_intra {
13166 3
13167 } else {
13168 usize::from(above_intra || left_intra)
13169 }
13170 }
13171 (true, false) => 2 * usize::from(!above_inter),
13172 (false, true) => 2 * usize::from(!left_inter),
13173 (false, false) => 0,
13174 }
13175}
13176
13177/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
13178/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
13179/// bits start counting from.
13180fn mv_class_base(class: usize) -> i32 {
13181 if class == 0 { 0 } else { 2i32 << (class + 2) }
13182}
13183
13184/// One motion vector component's non-zero diff (spec 5.11.32
13185/// `read_mv_component`), the inverse of [`crate::tile`]'s private
13186/// `write_mv_component`.
13187fn read_mv_component(
13188 dec: &mut SymbolDecoder,
13189 c: &mut MvComponentCdfs,
13190 allow_high_precision_mv: bool,
13191 force_integer_mv: bool,
13192) -> i32 {
13193 let sign = dec.symbol(&mut c.sign);
13194 let class = dec.symbol(&mut c.class);
13195 let local = if class == 0 {
13196 let bit = dec.symbol(&mut c.class0_bit);
13197 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
13198 // forces integer motion vectors -- implicitly `3` (the top
13199 // fractional value) rather than read, else every symbol after it
13200 // in the tile desyncs by one read.
13201 let fr = if force_integer_mv {
13202 3
13203 } else {
13204 dec.symbol(&mut c.class0_fr[bit])
13205 };
13206 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
13207 // high-precision motion vectors, else implicitly 1 (the low bit
13208 // stays at half-pel precision) -- this crate's own writer always
13209 // leaves the flag off, but a foreign stream can set it per frame.
13210 let hp = if allow_high_precision_mv {
13211 dec.symbol(&mut c.class0_hp)
13212 } else {
13213 1
13214 };
13215 (bit << 3) | (fr << 1) | hp
13216 } else {
13217 let mut d = 0;
13218 for i in 0..class {
13219 d |= dec.symbol(&mut c.bit[i]) << i;
13220 }
13221 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
13222 // `mv_class0_fr` above.
13223 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
13224 let hp = if allow_high_precision_mv {
13225 dec.symbol(&mut c.hp)
13226 } else {
13227 1
13228 };
13229 (d << 3) | (fr << 1) | hp
13230 };
13231 let mag = mv_class_base(class) + local as i32 + 1;
13232 if sign == 1 { -mag } else { mag }
13233}
13234
13235/// A motion vector coded as a residual against `pred` (spec 5.11.32
13236/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
13237fn read_mv(
13238 dec: &mut SymbolDecoder,
13239 mv_comp: &mut [MvComponentCdfs; 2],
13240 mv_joint: &mut [u16; 5],
13241 pred: (i32, i32),
13242 allow_high_precision_mv: bool,
13243 force_integer_mv: bool,
13244) -> (i32, i32) {
13245 let joint = dec.symbol(mv_joint);
13246 let mut diff = (0, 0);
13247 if joint == 2 || joint == 3 {
13248 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
13249 }
13250 if joint == 1 || joint == 3 {
13251 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
13252 }
13253 (pred.0 + diff.0, pred.1 + diff.1)
13254}
13255
13256/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
13257/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
13258///
13259/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
13260/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
13261/// when that is zero, or -- when both are -- the fixed fallback DV one
13262/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
13263/// left when this is the tile's first superblock row. The predictor is then
13264/// rounded to full pel, and the difference reads off the *dv* nmv context
13265/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
13266/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
13267/// symbol is coded for a DV, so none of this can move the bitstream
13268/// position -- only the reconstructed vector.
13269fn read_intrabc_dv(
13270 dec: &mut SymbolDecoder,
13271 cdfs: &mut Cdfs,
13272 mi_r: usize,
13273 mi_c: usize,
13274 side: usize,
13275) -> (i32, i32) {
13276 const INTRABC_DELAY_PIXELS: i32 = 256;
13277 let n4 = side / MI;
13278 let stack_pred = INTRABC_MI_GRID.with(|g| {
13279 let g = g.borrow();
13280 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
13281 let stack = crate::mvstack::find_mv_stack(
13282 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
13283 *mi_cols, *mi_rows,
13284 );
13285 if stack.nearest_mv == (0, 0) {
13286 stack.near_mv
13287 } else {
13288 stack.nearest_mv
13289 }
13290 })
13291 });
13292 let mut pred = stack_pred.unwrap_or((0, 0));
13293 if pred == (0, 0) {
13294 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
13295 // single-tile-row case every intrabc gate stream is).
13296 let sb_px = SB_MI as i32 * MI as i32;
13297 pred = if mi_r < SB_MI as usize {
13298 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
13299 } else {
13300 (-sb_px * 8, 0)
13301 };
13302 }
13303 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
13304 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
13305 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
13306}
13307
13308/// A 1/8-pel motion vector component converted to the 1/16-pel offset
13309/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
13310/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
13311fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
13312 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
13313}
13314
13315impl PlaneBuf {
13316 /// Adds `residual` onto an already-computed `prediction` (motion
13317 /// compensation's output, rather than [`predict`]'s intra one), writing
13318 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
13319 /// counterpart of [`PlaneBuf::reconstruct`].
13320 fn reconstruct_mc(
13321 &mut self,
13322 x: usize,
13323 y: usize,
13324 side: usize,
13325 prediction: &[u16],
13326 residual: &[i32],
13327 ) {
13328 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
13329 }
13330
13331 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
13332 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
13333 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
13334 /// VERT strip is predicted at its enclosing square `side` (matching
13335 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
13336 /// but only its own true `w`x`h` footprint is committed to the plane, so
13337 /// two strips sharing a square's coordinate origin never clobber each
13338 /// other's real pixels.
13339 fn reconstruct_mc_rect(
13340 &mut self,
13341 x: usize,
13342 y: usize,
13343 side: usize,
13344 w: usize,
13345 h: usize,
13346 prediction: &[u16],
13347 residual: &[i32],
13348 ) {
13349 for row in 0..h {
13350 for col in 0..w {
13351 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
13352 .clamp(0, crate::decode::sample_max()) as u16;
13353 self.data[(y + row) * self.width + x + col] = sample;
13354 }
13355 }
13356 }
13357}
13358
13359/// Reads one inter-coded plane's transform block and reconstructs it by
13360/// adding its residual onto a motion-compensated `prediction` -- the inter
13361/// counterpart of [`read_plane`] (every inter transform this decoder reads is
13362/// `side`-square with no oversized-64 case, so there is no padded-grid
13363/// branch to mirror).
13364#[allow(clippy::too_many_arguments)]
13365fn read_inter_plane(
13366 dec: &mut SymbolDecoder,
13367 cdfs: &mut Cdfs,
13368 set: TxbSet,
13369 scan: &[u16],
13370 plane_idx: usize,
13371 around: (bool, bool, i32),
13372 tx_mode: usize,
13373 plane: &mut PlaneBuf,
13374 x: usize,
13375 y: usize,
13376 side: usize,
13377 base_q_idx: u8,
13378 prediction: &[u16],
13379 // lane-chromau: this block's own luma transform's *actual coded*
13380 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
13381 // chroma plane never codes its own `tx_type` symbol, but (unlike an
13382 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
13383 // the colocated luma transform's coded type verbatim, clamped back to
13384 // `DCT_DCT` at the chroma tx sizes the spec forces DCT-only
13385 // (`av1_get_ext_tx_set_type`: `tx_size_sqr_up >= TX_32X32`, i.e. this
13386 // function's own `side >= 32`). `None` for the luma call itself
13387 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
13388 // `DCT_DCT` default at 32-point+) already resolves it without help.
13389 inherited_luma_tx_type: Option<TxType>,
13390 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
13391 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
13392 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
13393 // transform every non-var-tx caller reads, whose plane-0 context is the
13394 // lone-transform-unit 0.
13395 luma_skip_ctx: Option<usize>,
13396) -> Result<(Vec<i32>, TxType)> {
13397 let skip_ctx = if plane_idx == 0 {
13398 luma_skip_ctx.unwrap_or(0)
13399 } else {
13400 usize::from(around.0) + usize::from(around.1)
13401 };
13402 let mut coding = cdfs.txb(set, tx_mode);
13403 let default_tx_type = match inherited_luma_tx_type {
13404 Some(t) if side < 32 => t,
13405 _ => TxType::DctDct,
13406 };
13407 let (grid, tx_type) = read_coeffs(
13408 dec,
13409 &mut coding,
13410 scan,
13411 skip_ctx,
13412 dc_sign_ctx(around.2),
13413 default_tx_type,
13414 None,
13415 )?;
13416 note_chroma_class1(plane_idx, tx_type);
13417 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
13418 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
13419 // caller hands the 32-point `scan` there, and the coded corner goes into
13420 // the top-left of the true `side`-sized grid before dequantization
13421 // (dqDenom is keyed by the true size, not the corner's), mirroring
13422 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
13423 // this decoder codes has `tx_side == side`, so this is inert below 64.
13424 let tx_side = side.min(32);
13425 let grid = if tx_side == side {
13426 grid
13427 } else {
13428 let mut full = vec![0i32; side * side];
13429 for row in 0..tx_side {
13430 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
13431 }
13432 full
13433 };
13434 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
13435 let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
13436 plane.reconstruct_mc(x, y, side, prediction, &residual);
13437 Ok((grid, tx_type))
13438}
13439
13440/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
13441/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
13442/// `reference_select` set before this is ever called, so that read is never
13443/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
13444/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
13445fn read_single_ref(
13446 dec: &mut SymbolDecoder,
13447 cdfs: &mut Cdfs,
13448 above_ref: i8,
13449 above_ref1: Option<i8>,
13450 left_ref: i8,
13451 left_ref1: Option<i8>,
13452) -> i8 {
13453 let above = (above_ref > 0).then_some(above_ref);
13454 let left = (left_ref > 0).then_some(left_ref);
13455 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
13456 let ref_frame = if p1 == 1 {
13457 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
13458 if p2 == 1 {
13459 ALTREF_FRAME
13460 } else {
13461 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
13462 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
13463 }
13464 } else {
13465 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
13466 if p3 == 1 {
13467 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
13468 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
13469 } else {
13470 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
13471 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
13472 }
13473 };
13474 if ref_frame != LAST_FRAME {
13475 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
13476 let c = match ref_frame {
13477 LAST2_FRAME => &LAST2_HITS,
13478 LAST3_FRAME => &LAST3_HITS,
13479 GOLDEN_FRAME => &GOLDEN_HITS,
13480 BWDREF_FRAME => &BWDREF_HITS,
13481 ALTREF2_FRAME => &ALTREF2_HITS,
13482 ALTREF_FRAME => &ALTREF_HITS,
13483 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
13484 };
13485 c.with(|v| v.set(v.get() + 1));
13486 }
13487 ref_frame
13488}
13489
13490/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
13491/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
13492/// `reference_select` header bit lets a block choose per-block instead of
13493/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
13494/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
13495/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
13496/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
13497/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
13498/// Resolves a compound reference's own planes -- the same `ref_frame ==
13499/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
13500/// [`decode_inter_block`]'s single-ref path already does, factored out so
13501/// the compound path can call it twice (lane-av1comp).
13502fn ref_planes<'a>(
13503 ref_frame: i8,
13504 ref_y: &'a PlaneBuf,
13505 ref_u: &'a PlaneBuf,
13506 ref_v: &'a PlaneBuf,
13507 other_refs: &'a RefSlots,
13508) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
13509 if ref_frame == LAST_FRAME {
13510 Ok((ref_y, ref_u, ref_v))
13511 } else {
13512 match other_refs[ref_frame as usize] {
13513 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
13514 None => Err(unsupported(
13515 "a reference frame selected with no picture at this frame's own \
13516 ref_frame_idx slot for it",
13517 )),
13518 }
13519 }
13520}
13521
13522/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
13523/// directly above this block's own column span, one bordering block at a
13524/// time (stepping by that neighbour's own `MiInfo::size`, which is always
13525/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
13526/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
13527/// unit at a time, and does not itself count as a step). `max_neighbors`
13528/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
13529/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
13530/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
13531/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
13532/// not ported -- no block this decoder codes is narrower than 8px, so it
13533/// never fires here regardless of what a neighbour's own decoder was.
13534fn overlappable_above(
13535 grid: &MiGrid,
13536 mi_row: usize,
13537 mi_col: usize,
13538 bw4: usize,
13539 mi_cols: usize,
13540 max_neighbors: usize,
13541) -> Vec<(usize, usize, MiInfo)> {
13542 let mut out = Vec::new();
13543 if mi_row == 0 {
13544 return out;
13545 }
13546 let end_col = (mi_col + bw4).min(mi_cols);
13547 let mut col = mi_col;
13548 while col < end_col && out.len() < max_neighbors {
13549 let cell = grid.get(mi_row - 1, col);
13550 let step = cell.map_or(1, |c| c.size).max(1);
13551 if let Some(info) = cell {
13552 if info.is_inter {
13553 out.push((col - mi_col, step.min(end_col - col), *info));
13554 }
13555 }
13556 col += step;
13557 }
13558 out
13559}
13560
13561/// `foreach_overlappable_nb_left`'s left-column mirror of
13562/// [`overlappable_above`] -- see its doc for the shared corner-cut.
13563fn overlappable_left(
13564 grid: &MiGrid,
13565 mi_row: usize,
13566 mi_col: usize,
13567 bh4: usize,
13568 mi_rows: usize,
13569 max_neighbors: usize,
13570) -> Vec<(usize, usize, MiInfo)> {
13571 let mut out = Vec::new();
13572 if mi_col == 0 {
13573 return out;
13574 }
13575 let end_row = (mi_row + bh4).min(mi_rows);
13576 let mut row = mi_row;
13577 while row < end_row && out.len() < max_neighbors {
13578 let cell = grid.get(row, mi_col - 1);
13579 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
13580 // width (8) would swallow the strip below it.
13581 let step = cell.map_or(1, |c| c.size_h).max(1);
13582 if let Some(info) = cell {
13583 if info.is_inter {
13584 out.push((row - mi_row, step.min(end_row - row), *info));
13585 }
13586 }
13587 row += step;
13588 }
13589 out
13590}
13591
13592/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples`
13593/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2:
13594/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128`
13595/// libaom's mask loop runs one level further and strips the top-right sample
13596/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame
13597/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates
13598/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is
13599/// the block's own side in 4x4 (`mi`) units (square inter leaves only here).
13600fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
13601 crate::mvstack::has_top_right(mi_row, mi_col, bs, bs)
13602}
13603
13604/// `av1_findSamples` (`mvref_common.c`), full port: the up to
13605/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
13606/// samples (`record_samples`) that share this block's own single reference
13607/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
13608/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
13609/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
13610/// libaom are also mi units of that same square side here). Each sample's
13611/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
13612/// come from the *neighbour* cell's own coded size, not this block's.
13613#[allow(clippy::too_many_arguments)]
13614fn find_samples(
13615 grid: &MiGrid,
13616 mi_row: usize,
13617 mi_col: usize,
13618 bw4: usize,
13619 bh4: usize,
13620 mi_cols: usize,
13621 mi_rows: usize,
13622 ref_frame: i8,
13623) -> Vec<crate::warp::Sample> {
13624 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
13625 let up_available = mi_row > 0;
13626 let left_available = mi_col > 0;
13627 let mut samples = Vec::with_capacity(MAX);
13628 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
13629 let mut do_tl = true;
13630 let mut do_tr = true;
13631 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
13632 let nb_bw = (info.size * 4) as i32;
13633 // lane-rect r2: the neighbour's own true height -- a rect strip
13634 // neighbour donates its sample at ITS center (aom pts y=-72 for a
13635 // 32x16 above strip; the square assumption put it at -136).
13636 let nb_bh = (info.size_h * 4) as i32;
13637 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
13638 };
13639
13640 'outer: {
13641 if up_available {
13642 let above = grid.get(mi_row - 1, mi_col);
13643 let superblock_width = above.map_or(1, |c| c.size).max(1);
13644 if bw4 <= superblock_width {
13645 let col_offset = -((mi_col % superblock_width) as isize);
13646 if col_offset < 0 {
13647 do_tl = false;
13648 }
13649 if col_offset + superblock_width as isize > bw4 as isize {
13650 do_tr = false;
13651 }
13652 if let Some(info) = above {
13653 if single_ref_match(info) {
13654 samples.push(rec(info, 0, -1, col_offset as i32, 1));
13655 if samples.len() >= MAX {
13656 break 'outer;
13657 }
13658 }
13659 }
13660 } else {
13661 let mut i = 0usize;
13662 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
13663 while i < limit {
13664 let cell = grid.get(mi_row - 1, mi_col + i);
13665 let sw = cell.map_or(1, |c| c.size).max(1);
13666 if let Some(info) = cell {
13667 if single_ref_match(info) {
13668 samples.push(rec(info, 0, -1, i as i32, 1));
13669 if samples.len() >= MAX {
13670 break 'outer;
13671 }
13672 }
13673 }
13674 i += sw;
13675 }
13676 }
13677 }
13678
13679 if left_available {
13680 let left = grid.get(mi_row, mi_col - 1);
13681 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
13682 if bh4 <= superblock_height {
13683 let row_offset = -((mi_row % superblock_height) as isize);
13684 if row_offset < 0 {
13685 do_tl = false;
13686 }
13687 if let Some(info) = left {
13688 if single_ref_match(info) {
13689 samples.push(rec(info, row_offset as i32, 1, 0, -1));
13690 if samples.len() >= MAX {
13691 break 'outer;
13692 }
13693 }
13694 }
13695 } else {
13696 let mut i = 0usize;
13697 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
13698 while i < limit {
13699 let cell = grid.get(mi_row + i, mi_col - 1);
13700 let sh = cell.map_or(1, |c| c.size_h).max(1);
13701 if let Some(info) = cell {
13702 if single_ref_match(info) {
13703 samples.push(rec(info, i as i32, 1, 0, -1));
13704 if samples.len() >= MAX {
13705 break 'outer;
13706 }
13707 }
13708 }
13709 i += sh;
13710 }
13711 }
13712 }
13713
13714 if do_tl && left_available && up_available {
13715 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
13716 if single_ref_match(info) {
13717 samples.push(rec(info, 0, -1, 0, -1));
13718 if samples.len() >= MAX {
13719 break 'outer;
13720 }
13721 }
13722 }
13723 }
13724
13725 if do_tr && has_top_right(mi_row, mi_col, bw4) {
13726 let tr_col = mi_col + bw4;
13727 if mi_row > 0 && tr_col < mi_cols {
13728 if let Some(info) = grid.get(mi_row - 1, tr_col) {
13729 if single_ref_match(info) {
13730 samples.push(rec(info, 0, -1, bw4 as i32, 1));
13731 }
13732 }
13733 }
13734 }
13735 }
13736 samples
13737}
13738
13739/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
13740/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
13741/// the 2-symbol `obmc_cdf` (spec 5.11.24).
13742#[allow(clippy::too_many_arguments)]
13743fn num_proj_ref(
13744 grid: &MiGrid,
13745 mi_row: usize,
13746 mi_col: usize,
13747 bw4: usize,
13748 bh4: usize,
13749 mi_cols: usize,
13750 mi_rows: usize,
13751 ref_frame: i8,
13752) -> u8 {
13753 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
13754}
13755
13756/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
13757/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
13758/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
13759/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
13760/// to 64 (no neighbour contribution) away from it. Only the lengths this
13761/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
13762/// are transcribed.
13763fn obmc_mask(len: usize) -> &'static [u8] {
13764 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
13765 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
13766 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
13767 // round wired interior 16x16 splits down to real 8x8 leaves, where the
13768 // old `unreachable!()` below fired as a hard panic.
13769 const M1: [u8; 1] = [64];
13770 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
13771 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
13772 // chroma), which only became live once 8x8 inter leaves stopped being
13773 // refused.
13774 const M2: [u8; 2] = [45, 64];
13775 const M4: [u8; 4] = [39, 50, 59, 64];
13776 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
13777 const M16: [u8; 16] = [
13778 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
13779 ];
13780 const M32: [u8; 32] = [
13781 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
13782 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
13783 ];
13784 match len {
13785 1 => &M1,
13786 2 => &M2,
13787 4 => &M4,
13788 8 => &M8,
13789 16 => &M16,
13790 32 => &M32,
13791 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
13792 }
13793}
13794
13795/// A bordering block's own resolved interp filter kernel, `(h, v)` --
13796/// mirrors [`resolve_interp_filter`]'s own return order from its stored
13797/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
13798/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]`
13799/// sentinel: that value is only ever stored for an intra neighbour (already
13800/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter`
13801/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here
13802/// first.
13803fn neighbour_filter(
13804 interp_fixed: Option<mc::InterpFilterKind>,
13805 sym: [u8; 2],
13806) -> (mc::InterpFilterKind, mc::InterpFilterKind) {
13807 if let Some(kind) = interp_fixed {
13808 return (kind, kind);
13809 }
13810 (
13811 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
13812 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
13813 )
13814}
13815
13816/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
13817/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
13818/// under `av1_setup_build_prediction_by_{above,left}_pred`).
13819#[allow(clippy::too_many_arguments)]
13820fn obmc_neighbour_pred(
13821 refplane: &PlaneBuf,
13822 x: usize,
13823 y: usize,
13824 mv: (i32, i32),
13825 w: usize,
13826 h: usize,
13827 luma: bool,
13828 h_kind: mc::InterpFilterKind,
13829 v_kind: mc::InterpFilterKind,
13830 // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own
13831 // reference (derived from luma widths, applied unchanged to chroma whose
13832 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
13833 // the ordinary stride-1 path bit-exact.
13834 x_scale_fp: i64,
13835) -> Vec<u16> {
13836 let mut out = vec![0u16; w * h];
13837 if x_scale_fp == mc::REF_NO_SCALE {
13838 mc::predict_with_filters(
13839 &refplane.data,
13840 refplane.width,
13841 refplane.true_width,
13842 refplane.true_height,
13843 mv_to_q4(x, mv.1, luma),
13844 mv_to_q4(y, mv.0, luma),
13845 w,
13846 h,
13847 h_kind,
13848 v_kind,
13849 &mut out,
13850 );
13851 } else {
13852 mc::predict_scaled(
13853 &refplane.data,
13854 refplane.width,
13855 refplane.true_width,
13856 refplane.true_height,
13857 mv_to_q4(x, mv.1, luma),
13858 mv_to_q4(y, mv.0, luma),
13859 x_scale_fp,
13860 w,
13861 h,
13862 h_kind,
13863 v_kind,
13864 &mut out,
13865 );
13866 }
13867 out
13868}
13869
13870/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
13871/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
13872/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
13873const II_WEIGHTS_1D: [u8; 128] = [
13874 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
13875 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
13876 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
13877 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
13878 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
13879 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
13880 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
13881];
13882
13883/// lane-interintra r1: non-wedge interintra prediction for one plane
13884/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
13885/// `build_smooth_interintra_mask`). Builds the intra predictor for the
13886/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
13887/// own decoded edges at `(x, y)`, then blends it over the inter prediction
13888/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
13889/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
13890/// reduces to `128 / side` for the square plane sizes this decoder reaches.
13891/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
13892/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
13893fn interintra_blend(
13894 plane: &PlaneBuf,
13895 x: usize,
13896 y: usize,
13897 side: usize,
13898 ii_mode: u8,
13899 wedge: Option<(&'static [u8], usize)>,
13900 pred: &mut [u16],
13901) {
13902 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
13903 let intra_mode = match ii_mode {
13904 0 => crate::intra::DC_PRED,
13905 1 => crate::intra::V_PRED,
13906 2 => crate::intra::H_PRED,
13907 _ => crate::intra::SMOOTH_PRED,
13908 };
13909 let (above, left, corner) = plane.edges(
13910 x,
13911 y,
13912 side,
13913 crate::encode::Reach {
13914 above_right: false,
13915 below_left: false,
13916 },
13917 );
13918 let mut intra = vec![0u16; side * side];
13919 // Edge filtering never applies here: V/H at delta 0 are plain edge
13920 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
13921 // angle at all.
13922 predict(
13923 intra_mode,
13924 0,
13925 above.as_deref(),
13926 left.as_deref(),
13927 corner,
13928 side,
13929 side,
13930 false,
13931 false,
13932 &mut intra,
13933 );
13934 let scale = 128 / side;
13935 for i in 0..side {
13936 for j in 0..side {
13937 let m = u32::from(match wedge {
13938 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
13939 // over the wedge codebook, intra as src0, fixed sign 0).
13940 // Luma plane: mask rows are luma-resolution, ms == side.
13941 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
13942 // subw == subh == 1).
13943 Some((mask, ms)) if ms == side => mask[i * side + j],
13944 Some((mask, ms)) => {
13945 let t = 2 * i * ms + 2 * j;
13946 ((u32::from(mask[t])
13947 + u32::from(mask[t + 1])
13948 + u32::from(mask[t + ms])
13949 + u32::from(mask[t + ms + 1])
13950 + 2)
13951 >> 2) as u8
13952 }
13953 None => match ii_mode {
13954 0 => 32,
13955 1 => II_WEIGHTS_1D[i * scale],
13956 2 => II_WEIGHTS_1D[j * scale],
13957 _ => II_WEIGHTS_1D[i.min(j) * scale],
13958 },
13959 });
13960 let idx = i * side + j;
13961 pred[idx] =
13962 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u16;
13963 }
13964 }
13965}
13966
13967fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
13968 let mask = obmc_mask(h);
13969 for row in 0..h {
13970 let m = u32::from(mask[row]);
13971 for col in 0..w {
13972 let d = &mut dst[(oy + row) * stride + ox + col];
13973 let t = u32::from(tmp[row * w + col]);
13974 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
13975 }
13976 }
13977}
13978
13979/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
13980/// left-neighbour pass, `aom_blend_a64_hmask`).
13981fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
13982 let mask = obmc_mask(w);
13983 for row in 0..h {
13984 for col in 0..w {
13985 let m = u32::from(mask[col]);
13986 let d = &mut dst[(oy + row) * stride + ox + col];
13987 let t = u32::from(tmp[row * w + col]);
13988 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
13989 }
13990 }
13991}
13992
13993/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
13994/// the overlap strip against each bordering above/left inter neighbour's own
13995/// mv/ref/filter and blends it into this block's just-built single-reference
13996/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
13997/// left, each reading only the *original* prediction this function was
13998/// handed (never the other pass's own output), matching libaom's own
13999/// independence between the two. `max_neighbor_obmc`'s own cap table
14000/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
14001/// decoder's own square blocks always index the same value both ways) bounds
14002/// how many bordering blocks actually get blended, separate from the
14003/// eligibility scan's own unbounded ("any at all") walk.
14004#[allow(clippy::too_many_arguments)]
14005fn obmc_blend(
14006 grid: &MiGrid,
14007 neighbours: &Neighbours,
14008 mi_row: usize,
14009 mi_col: usize,
14010 bw4: usize,
14011 bh4: usize,
14012 mi_rows: usize,
14013 mi_cols: usize,
14014 side: usize,
14015 write_w: usize,
14016 write_h: usize,
14017 chroma_side: usize,
14018 px: usize,
14019 py: usize,
14020 cpx: usize,
14021 cpy: usize,
14022 ref_y: &PlaneBuf,
14023 ref_u: &PlaneBuf,
14024 ref_v: &PlaneBuf,
14025 other_refs: &RefSlots,
14026 interp_fixed: Option<mc::InterpFilterKind>,
14027 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
14028 // neighbour is re-predicted against ITS OWN reference, which may be
14029 // scaled differently from this block's (spec 7.11.3.3 / libaom
14030 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
14031 // `scale_factors`).
14032 frame_width: usize,
14033 pred_y: &mut [u16],
14034 pred_u: &mut [u16],
14035 pred_v: &mut [u16],
14036) -> Result<()> {
14037 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
14038 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
14039 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
14040 // right only for square blocks.
14041 let max_nb = |n4: usize| match n4 {
14042 1..=4 => 2,
14043 5..=8 => 3,
14044 _ => 4,
14045 };
14046 let overlap_above = write_h / 2;
14047 let overlap_left = write_w / 2;
14048 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
14049 // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided
14050 // obmc") returns `dir == 0` when the chroma plane's own block is
14051 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
14052 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
14053 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
14054
14055 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
14056 {
14057 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
14058 // (this decoder's own outer block-loop granularity), one step
14059 // coarser than the mi(4px) units `overlappable_above` walks in --
14060 // divide back down to that column.
14061 // lane-gmaffine r2: the neighbour's OWN mi-granular filter
14062 // (libaom `av1_setup_build_prediction_by_above_pred` reads
14063 // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot
14064 // stays as the fallback for paths that do not record one yet
14065 // (compound), which is what every earlier round used.
14066 let (h_kind, v_kind) = neighbour_filter(
14067 interp_fixed,
14068 neighbours.above_filter[mi_col + off4],
14069 );
14070 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
14071 let nb_scale = mc::scale_factor(ny.width, frame_width);
14072 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
14073 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
14074 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
14075 if !skip_chroma_above {
14076 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
14077 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
14078 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
14079 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
14080 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
14081 }
14082 }
14083
14084 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
14085 let (h_kind, v_kind) = neighbour_filter(
14086 interp_fixed,
14087 neighbours.left_filter[mi_row + off4],
14088 );
14089 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
14090 let nb_scale = mc::scale_factor(ny.width, frame_width);
14091 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
14092 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
14093 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
14094 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
14095 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
14096 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
14097 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
14098 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
14099 }
14100 Ok(())
14101}
14102
14103/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
14104/// the square block sizes this decoder ever decodes (32/16/8, all
14105/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
14106/// always `is_interinter_compound_used`, so the function is always `true`
14107/// for `side` -- kept as a named call (rather than inlined `true`) so a
14108/// future sub-8 block size does not silently misdecode a real stream.
14109fn is_any_masked_compound_used_here(side: usize) -> bool {
14110 side.min(side) >= 8
14111}
14112
14113/// Whether a compound reference pair is unidirectional (both references on
14114/// the same temporal side of the current frame) -- `has_uni_comp_refs`
14115/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
14116/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
14117/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
14118/// is_backward(ref1)`). Used to build a real
14119/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
14120/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
14121fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
14122 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
14123 backward(ref0) == backward(ref1)
14124}
14125
14126/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
14127/// above/left neighbour contributions [`Neighbours::record_inter`]/
14128/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
14129/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
14130/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
14131/// leaves read the same neighbour cell (class context-read-from-one-cell).
14132fn get_comp_group_idx_context(
14133 neighbours: &Neighbours,
14134 at_mi: (usize, usize),
14135 side: usize,
14136) -> usize {
14137 let _ = side;
14138 let (rmi, cmi) = at_mi;
14139 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
14140 .min(5)
14141}
14142
14143/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
14144/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
14145/// block's own two references' distances from the current frame (spec
14146/// 7.11.3.15's `get_relative_dist`, same convention
14147/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
14148#[allow(clippy::too_many_arguments)]
14149fn get_comp_index_context(
14150 neighbours: &Neighbours,
14151 at_mi: (usize, usize),
14152 side: usize,
14153 order_hint_bits: u32,
14154 cur_order_hint: u32,
14155 ref0_order_hint: u32,
14156 ref1_order_hint: u32,
14157) -> usize {
14158 let _ = side;
14159 let (rmi, cmi) = at_mi;
14160 let fwd =
14161 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
14162 .abs();
14163 let bck =
14164 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
14165 .abs();
14166 let offset = usize::from(fwd == bck);
14167 neighbours.above_compound_idx[cmi] as usize
14168 + neighbours.left_compound_idx[rmi] as usize
14169 + 3 * offset
14170}
14171
14172fn read_comp_mode(
14173 dec: &mut SymbolDecoder,
14174 cdfs: &mut Cdfs,
14175 above: Option<NeighbourRef>,
14176 left: Option<NeighbourRef>,
14177) -> bool {
14178 let ctx = reference_mode_ctx(above, left);
14179 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
14180 if compound {
14181 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
14182 }
14183 compound
14184}
14185
14186/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
14187/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
14188/// arm), reached once [`read_comp_mode`] has already returned
14189/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
14190/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
14191/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
14192/// convention [`read_single_ref`] already uses, for every downstream binary
14193/// decision. libaom `pred_common.c`'s own compound context functions
14194/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
14195/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
14196/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
14197/// (same vote-the-neighbours-above-left shape, same forward/backward and
14198/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
14199/// against the C source rather than porting six near-duplicate functions.
14200/// Its caller today only needs the symbols consumed, correctly, to keep the
14201/// arithmetic decoder's own state in sync before refusing the block by name
14202/// -- the returned pair is not yet threaded into any motion-compensation
14203/// path.
14204fn read_compound_ref_frames(
14205 dec: &mut SymbolDecoder,
14206 cdfs: &mut Cdfs,
14207 above: Option<NeighbourRef>,
14208 left: Option<NeighbourRef>,
14209 above_ref: i8,
14210 left_ref: i8,
14211) -> (i8, i8) {
14212 let a = (above_ref > 0).then_some(above_ref);
14213 let l = (left_ref > 0).then_some(left_ref);
14214 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
14215 // neighbour's references, not just its first -- `a1`/`l1` carry that
14216 // second reference through to every vote below (lane-av1blend r6: a
14217 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
14218 // row for a block sitting under a skip_mode-forced compound neighbour).
14219 let a1 = above.and_then(|n| n.ref1);
14220 let l1 = left.and_then(|n| n.ref1);
14221 let type_ctx = comp_reference_type_ctx(above, left);
14222 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
14223 if unidir {
14224 UNI_COMP_HITS.with(|c| c.set(c.get() + 1));
14225 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
14226 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
14227 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
14228 if bit == 1 {
14229 (BWDREF_FRAME, ALTREF_FRAME)
14230 } else {
14231 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
14232 if p1 == 1 {
14233 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
14234 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
14235 if p2 == 1 {
14236 (LAST_FRAME, GOLDEN_FRAME)
14237 } else {
14238 (LAST_FRAME, LAST3_FRAME)
14239 }
14240 } else {
14241 (LAST_FRAME, LAST2_FRAME)
14242 }
14243 }
14244 } else {
14245 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
14246 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
14247 let ref0 = if bit0 == 0 {
14248 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
14249 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
14250 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
14251 } else {
14252 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
14253 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
14254 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
14255 };
14256 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
14257 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
14258 let ref1 = if bit1 == 0 {
14259 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
14260 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
14261 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
14262 } else {
14263 ALTREF_FRAME
14264 };
14265 (ref0, ref1)
14266 }
14267}
14268
14269/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
14270/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
14271/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
14272/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
14273/// libaom's `av1_mode_context_analyzer`'s compound branch --
14274/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
14275/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
14276/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
14277/// is not yet turned into an assigned MV pair or motion-compensated --
14278/// lane-av1comp.
14279fn read_inter_compound_mode(
14280 dec: &mut SymbolDecoder,
14281 cdfs: &mut Cdfs,
14282 new_mv_ctx: usize,
14283 ref_mv_ctx: usize,
14284) -> u8 {
14285 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
14286 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
14287 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
14288}
14289
14290/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
14291/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
14292/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
14293/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
14294/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
14295/// non-`IDENTITY` global motion model before a tile is ever decoded.
14296///
14297/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
14298/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
14299/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
14300/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
14301/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
14302fn assign_compound_mv(
14303 dec: &mut SymbolDecoder,
14304 cdfs: &mut Cdfs,
14305 comp_stack: &crate::mvstack::CompoundMvStack,
14306 mode: u8,
14307 allow_high_precision_mv: bool,
14308 force_integer_mv: bool,
14309 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
14310 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
14311 global_mv: ((i32, i32), (i32, i32)),
14312) -> ((i32, i32), (i32, i32)) {
14313 const NEAREST_NEARESTMV: u8 = 0;
14314 const NEAR_NEARMV: u8 = 1;
14315 const NEAREST_NEWMV: u8 = 2;
14316 const NEW_NEARESTMV: u8 = 3;
14317 const NEAR_NEWMV: u8 = 4;
14318 const NEW_NEARMV: u8 = 5;
14319 const GLOBAL_GLOBALMV: u8 = 6;
14320 const NEW_NEWMV: u8 = 7;
14321
14322 let mut ref_mv_idx = 0usize;
14323 if mode == NEW_NEWMV {
14324 let mut idx = 0usize;
14325 while idx < 2 && comp_stack.entries.len() > idx + 1 {
14326 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
14327 break;
14328 }
14329 idx += 1;
14330 }
14331 ref_mv_idx = idx;
14332 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
14333 let mut idx = 1usize;
14334 while idx < 3 && comp_stack.entries.len() > idx + 1 {
14335 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
14336 break;
14337 }
14338 idx += 1;
14339 }
14340 ref_mv_idx = idx - 1;
14341 }
14342
14343 let near = comp_stack
14344 .entries
14345 .get(ref_mv_idx + 1)
14346 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
14347 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
14348 ref_mv_idx + 1
14349 } else {
14350 ref_mv_idx
14351 };
14352 let new_pred = comp_stack
14353 .entries
14354 .get(new_idx)
14355 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
14356
14357 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
14358 read_mv(
14359 dec,
14360 &mut cdfs.mv_comp,
14361 &mut cdfs.mv_joint,
14362 base,
14363 allow_high_precision_mv,
14364 force_integer_mv,
14365 )
14366 };
14367
14368 match mode {
14369 NEAREST_NEARESTMV => comp_stack.nearest_mv,
14370 NEAR_NEARMV => near,
14371 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
14372 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
14373 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
14374 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
14375 GLOBAL_GLOBALMV => global_mv,
14376 _ => (
14377 read_new(dec, cdfs, new_pred.0),
14378 read_new(dec, cdfs, new_pred.1),
14379 ),
14380 }
14381}
14382
14383/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
14384/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
14385/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
14386/// table is always computed at the *querying* block's position, never a
14387/// donating neighbour's).
14388fn build_gm_mv_table(
14389 global_motion: &[ec_av1_syntax::WarpParams; 7],
14390 mi_row: usize,
14391 mi_col: usize,
14392 bw4: usize,
14393 bh4: usize,
14394 allow_high_precision_mv: bool,
14395 force_integer_mv: bool,
14396) -> crate::mvstack::GmMvTable {
14397 std::array::from_fn(|i| {
14398 let gm = &global_motion[i];
14399 crate::warp::gm_get_motion_vector(
14400 gm.model,
14401 &gm.params,
14402 mi_row,
14403 mi_col,
14404 bw4,
14405 bh4,
14406 allow_high_precision_mv,
14407 force_integer_mv,
14408 )
14409 })
14410}
14411
14412/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
14413/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
14414/// and motion-compensated reconstruction, or the inter frame's own intra
14415/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
14416/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
14417/// private `write_inter_frame_leaf` -- both share this one function here,
14418/// parameterised by `side`/the transform sets/scan tables/size group they
14419/// each use.
14420///
14421/// # Errors
14422/// Returns an error when a symbol names anything this decoder does not
14423/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
14424/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
14425/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
14426/// refuse.
14427#[allow(clippy::too_many_arguments)]
14428fn decode_inter_block(
14429 dec: &mut SymbolDecoder,
14430 cdfs: &mut Cdfs,
14431 neighbours: &mut Neighbours,
14432 grid: &mut MiGrid,
14433 at: (usize, usize),
14434 side: usize,
14435 mi_cols: u32,
14436 mi_rows: u32,
14437 y: &mut PlaneBuf,
14438 u: &mut PlaneBuf,
14439 v: &mut PlaneBuf,
14440 ref_y: &PlaneBuf,
14441 ref_u: &PlaneBuf,
14442 ref_v: &PlaneBuf,
14443 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
14444 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
14445 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
14446 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
14447 // slot's still empty (an error-resilient stream, or too early in the
14448 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
14449 other_refs: &RefSlots,
14450 sign_bias_table: &SignBiasTable,
14451 // lane-gm r2: this frame header's own `global_motion` table (spec
14452 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
14453 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
14454 // assignment and the mv-stack's neighbour substitution.
14455 global_motion: &[ec_av1_syntax::WarpParams; 7],
14456 base_q_idx: u8,
14457 luma_set_intra: TxbSet,
14458 luma_set_inter: TxbSet,
14459 chroma_set: TxbSet,
14460 luma_tx: usize,
14461 chroma_tx: usize,
14462 scan_luma: &[u16],
14463 scan_chroma: &[u16],
14464 size_group: usize,
14465 allow_high_precision_mv: bool,
14466 force_integer_mv: bool,
14467 interp_fixed: Option<mc::InterpFilterKind>,
14468 enable_dual_filter: bool,
14469 tpl_frame: Option<&TplFrameArgs>,
14470 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
14471 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
14472 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
14473 // refuses (rather than silently misdecoding) the ones that pick
14474 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
14475 // wired yet.
14476 reference_select: bool,
14477 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
14478 // compound enable bits, gating `comp_group_idx`/`compound_idx`
14479 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
14480 // compound blend weights need this frame's own order hint regardless
14481 // of `use_ref_frame_mvs`.
14482 enable_masked_compound: bool,
14483 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
14484 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
14485 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
14486 // and before `read_motion_mode` on the single-ref path below, gated by
14487 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
14488 // every mode this single-ref branch can produce is already in
14489 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
14490 // (inter+intra blended prediction unimplemented) rather than a
14491 // mis-decode.
14492 enable_interintra_compound: bool,
14493 enable_jnt_comp: bool,
14494 order_hint_bits: u32,
14495 order_hint: u32,
14496 ref_order_hints: [u32; 7],
14497 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
14498 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
14499 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
14500 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
14501 // when this is `true` (every block this decoder reaches is >= 8x8, so
14502 // `is_comp_ref_allowed` never gates it further); a `true` result forces
14503 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
14504 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
14505 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
14506 skip_mode_present: bool,
14507 skip_mode_frame: [u8; 2],
14508 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
14509 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
14510 switchable_motion_mode: bool,
14511 allow_warped_motion: bool,
14512 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
14513 // as a square 32x32 block, which over-reads a residual unless coded
14514 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
14515 reject_residual: bool,
14516 // lane-partitions r1: the strip's own true width/height in pixels --
14517 // `side` keeps governing every syntax/CDF/prediction-buffer decision
14518 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
14519 // the final pixel write and this block's own neighbour-context stamp
14520 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
14521 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
14522 // for every existing (square) caller.
14523 write_w: usize,
14524 write_h: usize,
14525 // lane-screen r2: this frame header's own `allow_screen_content_tools`
14526 // bit, threaded to the intra-sub-block branch below -- libaom's
14527 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
14528 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
14529 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
14530 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
14531 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
14532 // under the same `av1_allow_palette` gate as the key-frame path.
14533 allow_screen_content_tools: bool,
14534 // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) --
14535 // compared against each reference's stored picture width to decide
14536 // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary
14537 // stride-1 one (`mc::predict_with_filters`) applies per reference, and to
14538 // refuse (rather than mis-decode) the warp/OBMC/interintra/compound
14539 // combinations that don't implement scaled MC yet.
14540 frame_width: usize,
14541) -> Result<()> {
14542 let (r, c) = at;
14543 // lane-inter8 r2: the inter side bands are mi-granular; this block's own
14544 // above/left neighbour is the mi cell at its top-left corner (libaom
14545 // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads
14546 // exactly what it read before.
14547 let (rmi, cmi) = (r * (SUB / MI), c * (SUB / MI));
14548 let (px, py) = (c * SUB, r * SUB);
14549 let (cpx, cpy) = (px / 2, py / 2);
14550 let chroma_side = side / 2;
14551 let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2);
14552
14553 if std::env::var_os("EC_AV1_TELL").is_some() {
14554 eprintln!(
14555 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
14556 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
14557 );
14558 }
14559 let skip_mode_ctx =
14560 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
14561 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
14562 // MSAC tell so it can be diffed against an equivalent hook in libaom's
14563 // own `read_skip_mode`/`av1_get_skip_mode_context`.
14564 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
14565 eprintln!(
14566 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
14567 dec.debug_bitpos()
14568 );
14569 }
14570 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
14571 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
14572 let (seg_mi_r, seg_mi_c) = (r * SUB_MI as usize, c * SUB_MI as usize);
14573 let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
14574 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
14575 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
14576 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
14577 eprintln!(
14578 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
14579 dec.debug_bitpos()
14580 );
14581 }
14582 if skip_mode {
14583 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
14584 }
14585
14586 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
14587 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
14588 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
14589 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
14590 maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
14591 maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
14592 // lane-warp r5: see `reject_residual` -- a square-block decode of a
14593 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
14594 // motion_mode/warp symbol), so gate here before any further read.
14595 if reject_residual && !skip {
14596 return Err(unsupported(
14597 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
14598 ));
14599 }
14600
14601 let (has_above, has_left) = (
14602 r > neighbours.tile_row0_mi / (SUB / MI),
14603 c > neighbours.tile_col0_mi / (SUB / MI),
14604 );
14605 let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]);
14606 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
14607 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
14608 if std::env::var_os("EC_TRACE_MODE").is_some() {
14609 eprintln!(
14610 "EC_MODE mi_row={} mi_col={} rng={}",
14611 r * SUB_MI as usize,
14612 c * SUB_MI as usize,
14613 dec.debug_state().0
14614 );
14615 }
14616 if std::env::var_os("EC_AV1_TELL").is_some() {
14617 eprintln!(
14618 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
14619 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
14620 );
14621 }
14622
14623 let mode_for_tx;
14624 let uv_predict_mode;
14625 let (luma_grid, u_grid, v_grid);
14626 let block_filter;
14627 let ref_frame_for_lf;
14628 let globalmv_for_lf;
14629 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
14630 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
14631 // common `record_inter` call below (which would otherwise stamp the
14632 // single-ref ALTREF-special-case default over it).
14633 let mut compound_ctx: Option<(i8, u8, u8)> = None;
14634 // lane-txselect: `read_block_tx_size`'s leaf transform units (spec
14635 // 5.11.17), `Some` only when this block's var-tx tree resolved to more
14636 // than one luma transform -- read back by the residual loop, the
14637 // coefficient-context write-back and the loop-filter grid fill below.
14638 let mut vartx_leaves: Option<Vec<(usize, usize, usize)>> = None;
14639 let at_mi = (r * (SUB / MI), c * (SUB / MI));
14640 if is_inter {
14641 let above_nbr = has_above.then(|| NeighbourRef {
14642 is_inter: above_inter,
14643 ref0: if above_inter {
14644 neighbours.above_ref[cmi]
14645 } else {
14646 0
14647 },
14648 ref1: neighbours.above_ref1[cmi],
14649 uni: neighbours.above_ref1[cmi]
14650 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[cmi], r1)),
14651 });
14652 let left_nbr = has_left.then(|| NeighbourRef {
14653 is_inter: left_inter,
14654 ref0: if left_inter {
14655 neighbours.left_ref[rmi]
14656 } else {
14657 0
14658 },
14659 ref1: neighbours.left_ref1[rmi],
14660 uni: neighbours.left_ref1[rmi]
14661 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
14662 });
14663 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
14664 eprintln!(
14665 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
14666 dec.debug_bitpos()
14667 );
14668 }
14669 let is_compound =
14670 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
14671 if is_compound {
14672 let (ref0, ref1) = if skip_mode {
14673 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
14674 } else {
14675 read_compound_ref_frames(
14676 dec,
14677 cdfs,
14678 above_nbr,
14679 left_nbr,
14680 neighbours.above_ref[cmi],
14681 neighbours.left_ref[rmi],
14682 )
14683 };
14684 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
14685 // lane-rect r2: true footprint, mirroring the single-ref path below.
14686 let bw4 = write_w / 4;
14687 let bh4 = write_h / 4;
14688 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
14689 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
14690 // below, just one `get_relative_dist` per reference.
14691 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
14692 field: t.field,
14693 cur_offset_0: crate::motion_field::get_relative_dist(
14694 t.order_hint_bits,
14695 t.order_hint,
14696 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
14697 ),
14698 cur_offset_1: crate::motion_field::get_relative_dist(
14699 t.order_hint_bits,
14700 t.order_hint,
14701 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
14702 ),
14703 allow_high_precision_mv,
14704 });
14705 let gm_table = build_gm_mv_table(
14706 global_motion,
14707 mi_row,
14708 mi_col,
14709 bw4,
14710 bh4,
14711 allow_high_precision_mv,
14712 force_integer_mv,
14713 );
14714 let comp_stack = crate::mvstack::find_mv_stack_compound(
14715 grid,
14716 mi_row,
14717 mi_col,
14718 bw4,
14719 bh4,
14720 (ref0, ref1),
14721 mi_cols as usize,
14722 mi_rows as usize,
14723 sign_bias_table,
14724 &gm_table,
14725 comp_tpl,
14726 );
14727 let compound_mode = if skip_mode {
14728 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
14729 } else {
14730 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
14731 };
14732 let (mv0, mv1) = assign_compound_mv(
14733 dec,
14734 cdfs,
14735 &comp_stack,
14736 compound_mode,
14737 allow_high_precision_mv,
14738 force_integer_mv,
14739 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
14740 );
14741 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
14742 // spec `is_nontrans_global_motion`: ALL active refs' models must
14743 // be non-TRANSLATION (IDENTITY counts) for the compound block's
14744 // interp-filter read to be suppressed.
14745 let gm_nontrans = is_globalmv
14746 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
14747 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
14748 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
14749 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
14750 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
14751 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
14752 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
14753 // the write extent below, so recompute the size bound from
14754 // `side` here (the block's own size, what libaom's `bsize`
14755 // is).
14756 let is_global_mv0 = is_globalmv
14757 && side >= 8
14758 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1;
14759 let is_global_mv1 = is_globalmv
14760 && side >= 8
14761 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1;
14762 // libaom `av1_init_warp_params` + `allow_warp`'s
14763 // `global_warp_allowed` branch, run once per reference for a
14764 // compound block exactly as for a single-ref one (reconinter.c
14765 // `build_inter_predictors_8x8_and_bigger` loops over `ref` and
14766 // calls `av1_init_warp_params` inside the loop) -- WARPED_CAUSAL
14767 // never reaches here (spec 5.11.27 / libaom `read_motion_mode`:
14768 // `has_second_ref` returns SIMPLE_TRANSLATION), so the local-warp
14769 // arm of `allow_warp` is dead on this path and only the global
14770 // one applies. `force_integer_mv` short-circuits
14771 // `av1_init_warp_params` before `allow_warp`.
14772 let compound_warp = |ref_frame: i8, eligible: bool| {
14773 if eligible
14774 && !force_integer_mv
14775 && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid
14776 {
14777 crate::warp::global_warp_params(
14778 global_motion[(ref_frame - LAST_FRAME) as usize].params,
14779 )
14780 } else {
14781 None
14782 }
14783 };
14784 let warp0 = compound_warp(ref0, is_global_mv0);
14785 let warp1 = compound_warp(ref1, is_global_mv1);
14786 if warp0.is_some() || warp1.is_some() {
14787 COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1));
14788 }
14789 // spec `get_ref_filter_type`: matches when EITHER of the
14790 // neighbour's two references equals this block's own ref0 --
14791 // `above_ref1`/`left_ref1` is the neighbour's real second
14792 // reference (`record_compound_ctx`) when it was itself a
14793 // compound block; checking `above_ref`/`left_ref` alone drops a
14794 // real filter match down to the "no neighbour" sentinel
14795 // whenever the shared reference sits in the neighbour's SECOND
14796 // slot (lane-av1idx r2).
14797 let above_filter_ctx = if neighbours.above_ref[cmi] == ref0
14798 || neighbours.above_ref1[cmi] == Some(ref0)
14799 {
14800 neighbours.above_filter[cmi]
14801 } else {
14802 [3, 3]
14803 };
14804 let left_filter_ctx = if neighbours.left_ref[rmi] == ref0
14805 || neighbours.left_ref1[rmi] == Some(ref0)
14806 {
14807 neighbours.left_filter[rmi]
14808 } else {
14809 [3, 3]
14810 };
14811 globalmv_for_lf = is_globalmv;
14812 ref_frame_for_lf = ref0;
14813 mode_for_tx = 0;
14814 uv_predict_mode = DC_PRED;
14815 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
14816 // `neighbours`) must be stamped with the block's true footprint
14817 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
14818 // NEXT strip's own rows/cols before it decodes, corrupting
14819 // every later mvstack scan that reads this cell back.
14820 for dr in 0..bh4 {
14821 for dc in 0..bw4 {
14822 grid.set(
14823 mi_row + dr,
14824 mi_col + dc,
14825 MiInfo {
14826 is_inter: true,
14827 ref_frame: ref0,
14828 ref_frame1: Some(ref1),
14829 mv1: Some(mv1),
14830 mv: mv0,
14831 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
14832 size: bw4,
14833 size_h: bh4,
14834 // libaom `is_global_mv_block`: per-ref-slot, mode
14835 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
14836 // own gm model > TRANSLATION (IDENTITY excluded
14837 // too -- the two-predicate trap, distinct from
14838 // `gm_nontrans` above which allows IDENTITY).
14839 is_global_mv0,
14840 is_global_mv1,
14841 },
14842 );
14843 }
14844 }
14845 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
14846 // masked compound / distance-weighted compound are actually
14847 // enabled for this stream -- `is_any_masked_compound_used_here`
14848 // is `true` for every block size this decoder ever reaches
14849 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
14850 // there), so the gate reduces to the sequence header bit; kept
14851 // as an explicit call so a future smaller block size is not
14852 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
14853 let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side);
14854 let comp_group_idx = if !skip_mode
14855 && enable_masked_compound
14856 && is_any_masked_compound_used_here(side)
14857 {
14858 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
14859 } else {
14860 0
14861 };
14862 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
14863 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
14864 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
14865 // when `comp_group_idx == 1`.
14866 let mut diffwtd_mask_type: Option<u8> = None;
14867 let mut wedge_mask: Option<&'static [u8]> = None;
14868 if comp_group_idx == 1 {
14869 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
14870 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
14871 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
14872 // `av1_wedge_params_lookup`) is true for every square bsize
14873 // this leaf reaches (8x8/16x16/32x32 all have
14874 // `wedge_types > 0`), so `compound_type` always reads a real
14875 // symbol here -- no alphabet collapse to worry about at this
14876 // block-size family.
14877 // lane-mcomp64 r1: `av1_is_wedge_used` is false at 64x64
14878 // (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`),
14879 // so libaom's `read_compound_type` (decodemv.c 1634-1656)
14880 // writes NO `compound_type` symbol there and INFERS
14881 // `COMPOUND_DIFFWTD` -- only the 1-bit `mask_type` literal
14882 // follows. `None` here is exactly that inferred arm.
14883 let wedge_bsize = match side {
14884 8 => Some(3),
14885 16 => Some(6),
14886 32 => Some(9),
14887 _ => None,
14888 };
14889 let compound_type = match wedge_bsize {
14890 Some(b) => dec.symbol(&mut cdfs.compound_type[b]),
14891 None => 1,
14892 };
14893 if let Some(wedge_bsize) = wedge_bsize.filter(|_| compound_type == 0) {
14894 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
14895 // verified vs independent C dump (wedge.rs).
14896 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
14897 let wedge_sign = dec.literal(1);
14898 WEDGE_HITS.with(|c| c.set(c.get() + 1));
14899 wedge_mask = Some(
14900 crate::wedge::wedge_masks()
14901 .codebook(side)
14902 .mask(wedge_sign as usize, wedge_index as usize),
14903 );
14904 } else {
14905 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
14906 let mask_type = dec.literal(1);
14907 diffwtd_mask_type = Some(mask_type as u8);
14908 if wedge_bsize.is_none() {
14909 DIFFWTD_INFERRED_HITS.with(|c| c.set(c.get() + 1));
14910 }
14911 }
14912 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
14913 }
14914 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
14915 // called this a `predict_compound_intermediate`/`combine_compound`
14916 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
14917 // unmasking and running the real gates
14918 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
14919 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
14920 // shows the plain-average blend is bit-exact *most of the time*
14921 // -- `combine_compound`'s two-shift-in-one round2 was proven
14922 // algebraically identical to libaom's separate
14923 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
14924 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
14925 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
14926 // the common case a lag-in-frames GOP's hidden altref frames
14927 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
14928 // for several consecutive frames.
14929 //
14930 // The real defect a live gate run isolated (seed 49,
14931 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
14932 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
14933 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
14934 // byte; decode-order frame 2 -- same shape, same zero MV, only
14935 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
14936 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
14937 // Every later frame up through decode-order 9 also mismatches,
14938 // *including* frame 8, whose four blocks are back to
14939 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
14940 // math is wrong" (that block's own math is proven exact) in
14941 // favour of "the picture sitting in some DPB slot is already
14942 // wrong by the time frame 2 reads it, and the corruption
14943 // propagates through refresh_frame_flags into every later
14944 // reference regardless of which named ref a later block picks".
14945 // Frames 10 through 18 (once the GOP's lineage stops tracing
14946 // back through the bad slot) are bit-exact again. This points at
14947 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
14948 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
14949 // indexing feeding `dist_wtd_comp_weight_assign`) around
14950 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
14951 // mc.rs. Not isolated further within lane-av1blend's budget --
14952 // refuse by name rather than ship a blend that is right only
14953 // sometimes. Ceiling: r13/r14's MC plumbing above this line
14954 // stays -- only the plain-average reconstruct is masked off
14955 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
14956 // per decode-order frame (which slot each `Frame` OBU refreshes,
14957 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
14958 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
14959 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
14960 // frame 2.
14961 //
14962 // r2 (fresh fixture, seed 45, same recipe -- the original r1
14963 // fixture is gitignored and could not be regenerated byte-exact):
14964 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
14965 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
14966 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
14967 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
14968 // is forced 0 on every non-key `show_existing_frame`) turned up
14969 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
14970 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
14971 // isolated a *different, smaller* shape than r1's: decode-order
14972 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
14973 // compound block) is the first to diverge from ffmpeg (worst
14974 // delta 1, luma only, clustered at 32-pixel block edges) even
14975 // though BOTH its compound inputs -- the key frame and
14976 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
14977 // itself proven bit-exact: it is later re-shown via
14978 // `show_existing_frame` and matches ffmpeg exactly) -- are
14979 // independently pixel-exact, and the blend arithmetic is the
14980 // same proven-exact formula. That rules out "wrong slot"/"stale
14981 // picture" for this fixture: the inputs are right, so the defect
14982 // is in decode-order frame 3's *own* per-block decode (entropy
14983 // desync from compound-CDF adaptation carried across a slot, or
14984 // the compound mode/MV read itself) -- not in `ref_slots`/
14985 // `refresh_frame_flags`. Not isolated further within budget.
14986 // Upgrade: bisect decode-order frame 3's tile decode against a
14987 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
14988 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
14989 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
14990 // -- the pre-deblock dump frame-index alignment between this
14991 // crate and that aomdec build is NOT 1:1 on this fixture (23
14992 // dumps here vs 24 there), so calibrate that first.
14993 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
14994 // against an instrumented aomdec build (frame-index alignment
14995 // recalibrated via content-hash matching rather than the raw
14996 // dump count -- the keyframe never calls a pre-deblock dump at
14997 // all, since only `decode_inter_frame_tile` does, which is the
14998 // whole "23 vs 24" gap, not a real bug).
14999 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
15000 // seed 45) is still the first divergence: PRE-deblock differs
15001 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
15002 // luma pixels, clustered where its two compound inputs' pixel
15003 // values disagree by more than a couple of levels -- both
15004 // inputs (the keyframe and decode-order frame 2's own picture)
15005 // are independently proven bit-exact (pre- and post-deblock)
15006 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
15007 // matches this decoder's block loop exactly for every block in
15008 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
15009 // every mismatching pixel against `key`/`bwd` (both known-exact)
15010 // picks out `w0=9, w1=7` for the majority (525/846) with zero
15011 // matches for the plain average this decoder actually emits or
15012 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
15013 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
15014 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
15015 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
15016 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
15017 // decoder's own `dist_wtd_comp_weight_assign` was independently
15018 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
15019 // by hand for these distances and gives the same `(9, 7)`).
15020 // `get_comp_index_context` was checked line-for-line against
15021 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
15022 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
15023 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
15024 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
15025 // `default_compound_idx_cdfs` value-for-value; the read is
15026 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
15027 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
15028 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
15029 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
15030 // either -- some blocks in this frame plausibly decode a
15031 // genuinely different (correct, context-dependent) compound_idx
15032 // than block (0,0)'s own -- so this is not simply "always wrong
15033 // the same way": table/context/gate are all individually
15034 // verified correct, yet the decoded VALUE at this specific
15035 // symbol is wrong at least once in this frame. Not isolated
15036 // further within budget. Upgrade: instrument `dec.symbol`'s own
15037 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
15038 // trace fields) immediately before and after the `compound_idx`
15039 // read specifically, not just the surrounding mode/mv/skip
15040 // trace which does match -- the desync (if any) is local to
15041 // this one read, not a wider stream desync.
15042 //
15043 // r5 (this round): the `resolve_interp_filter` call used to sit
15044 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
15045 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
15046 // `read_compound_type`, not before, so that was a genuine
15047 // ordering bug for a Switchable-filter frame (moved below, past
15048 // the `compound_ctx = Some(...)` line). It does NOT explain this
15049 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
15050 // header carries a *fixed* interpolation filter
15051 // (`interp_fixed = Some(Regular)`, confirmed live via a
15052 // one-off dump), so `resolve_interp_filter` never read a symbol
15053 // in either position -- zero bits moved, decoded values
15054 // unchanged before and after the reorder. Kept anyway: it is a
15055 // real spec-order fix for the next Switchable-filter compound
15056 // stream, independently correct regardless of this fixture.
15057 //
15058 // Also ruled out this round: comparing this crate's own
15059 // `SymbolDecoder::debug_bitpos()` against aomdec's
15060 // `aom_reader_tell()` at the block boundary is NOT a valid
15061 // desync probe -- they are different quantities (raw consumed
15062 // input bits vs. an entropy-cost estimate that advances without
15063 // a literal byte fetch), so equal/unequal bitpos proves nothing
15064 // either way. Do not repeat that comparison; instead trace
15065 // `range`/`value` (this crate) against libaom's own internal
15066 // `dif`/`rng` (needs new instrumentation in both) immediately
15067 // after each read *upstream* of this one in the same block:
15068 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
15069 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
15070 // and the DRL loop. All of those independently decoded the SAME
15071 // values this crate and aomdec both show (ref0=1, ref1=5, mode
15072 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
15073 // miscomputation can still decode the identical symbol value off
15074 // a slightly different CDF, narrowing `range` by a different
15075 // amount than aomdec without changing the decoded value itself,
15076 // and only surface as a wrong decode a few reads later exactly
15077 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
15078 // table were independently re-verified again this round and are
15079 // still correct; the four candidates above were not re-audited
15080 // this round. Refusing here (rather than shipping a value-exact-
15081 // most-of-the-time blend) until one of them is found wrong.
15082 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
15083 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
15084 // comp_bwdref* context reads -- kept, real fix). Unmasking on
15085 // that fix alone and running the wide gate sweep (many seeds,
15086 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
15087 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
15088 // cq-level=45) still mismatches roughly half the time, at
15089 // different frames each run for the SAME seed -- aomenc's own
15090 // cpu-used=0 RD search is run-to-run nondeterministic (noted
15091 // above), so this is a second, still-unfound compound_idx defect,
15092 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
15093 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
15094 // either) already flagged more than one bug here. Re-masking:
15095 // do not ship a blend that is right only sometimes.
15096 // lane-av1idx r1: fixed one real bug this round
15097 // (`switchable_interp_ctx` never folded in libaom's
15098 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
15099 // interp_filter context -- kept). Pinned
15100 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
15101 // gate) still mismatches after that fix (decode-order frame 8
15102 // first, small deltas, worst 1-2, propagating through later
15103 // frames via DPB reference) -- a second, still-unfound bug.
15104 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
15105 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
15106 // for the next round's starting point.
15107 // lane-maskcomp r2: `compound_idx` is only read when
15108 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
15109 // (wedge/diffwtd) block never also carries a distance-weighted
15110 // split. This gate was missing before r2 (dead code: the masked
15111 // path always refused earlier, so it never executed with
15112 // `comp_group_idx == 1` in practice).
15113 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
15114 && !skip_mode
15115 && enable_jnt_comp
15116 {
15117 let idx_ctx = get_comp_index_context(
15118 neighbours,
15119 (rmi, cmi),
15120 side,
15121 order_hint_bits,
15122 order_hint,
15123 ref_order_hints[(ref0 - LAST_FRAME) as usize],
15124 ref_order_hints[(ref1 - LAST_FRAME) as usize],
15125 );
15126 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
15127 if idx == 1 {
15128 (8, 8, 1u8)
15129 } else {
15130 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
15131 order_hint_bits,
15132 order_hint,
15133 ref_order_hints[(ref0 - LAST_FRAME) as usize],
15134 ref_order_hints[(ref1 - LAST_FRAME) as usize],
15135 );
15136 (fwd, bck, 0u8)
15137 }
15138 } else {
15139 (8, 8, 1u8)
15140 };
15141 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
15142 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
15143 eprintln!(
15144 "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={}",
15145 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
15146 );
15147 }
15148
15149 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
15150 // comes AFTER `read_compound_type` (the `comp_group_idx`/
15151 // `compound_idx` reads just above), not before -- moved here
15152 // (lane-av1blend r5) from its old position ahead of those reads,
15153 // which stole their bits for a Switchable-filter compound block
15154 // and desynced every symbol read after it in the tile.
15155 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
15156 // filter is derived (Regular), never read -- same
15157 // conditional-read contract as the WARPED_CAUSAL suppression on
15158 // the single-ref path below.
15159 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
15160 dec,
15161 cdfs,
15162 interp_fixed,
15163 enable_dual_filter,
15164 gm_nontrans || skip_mode,
15165 above_filter_ctx,
15166 left_filter_ctx,
15167 true,
15168 );
15169 block_filter = resolved_filter;
15170
15171 // lane-scaledref r1: each compound tap scales INDEPENDENTLY off
15172 // its own stored reference's luma width (spec 7.11.3.3 derives
15173 // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds
15174 // one `scale_factors` per `ref_frame`), so the two taps can carry
15175 // different ratios in the same block. `REF_NO_SCALE` reduces
15176 // `predict_compound_intermediate`'s walk to the ordinary
15177 // stride-1 one, so the unscaled case is unchanged.
15178 let scale0 = mc::scale_factor(py0.width, frame_width);
15179 let scale1 = mc::scale_factor(py1.width, frame_width);
15180 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
15181 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
15182 }
15183 // lane-scaledref r2: the MIXED case -- one tap scaled, the other
15184 // not -- is the one an all-frames-scaled recipe never produces,
15185 // and the one a single shared scale factor would get wrong.
15186 if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) {
15187 MIXED_SCALE_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
15188 }
15189
15190 let mut inter0_y = vec![0i32; side * side];
15191 mc::predict_compound_intermediate(
15192 &py0.data,
15193 py0.width,
15194 py0.true_width,
15195 py0.true_height,
15196 mv_to_q4(px, mv0.1, true),
15197 mv_to_q4(py, mv0.0, true),
15198 scale0,
15199 side,
15200 side,
15201 h_filter,
15202 v_filter,
15203 &mut inter0_y,
15204 );
15205 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
15206 // translational tap (libaom `av1_warp_plane` with
15207 // `conv_params->is_compound`); the blend below is unchanged.
15208 if let Some(wp) = &warp0 {
15209 crate::warp::warp_affine_compound(
15210 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
15211 py0.width as i32, &mut inter0_y, px as i32, py as i32, side as i32,
15212 side as i32, side as i32, 0, 0,
15213 );
15214 }
15215 let mut inter1_y = vec![0i32; side * side];
15216 mc::predict_compound_intermediate(
15217 &py1.data,
15218 py1.width,
15219 py1.true_width,
15220 py1.true_height,
15221 mv_to_q4(px, mv1.1, true),
15222 mv_to_q4(py, mv1.0, true),
15223 scale1,
15224 side,
15225 side,
15226 h_filter,
15227 v_filter,
15228 &mut inter1_y,
15229 );
15230 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
15231 // translational tap (libaom `av1_warp_plane` with
15232 // `conv_params->is_compound`); the blend below is unchanged.
15233 if let Some(wp) = &warp1 {
15234 crate::warp::warp_affine_compound(
15235 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
15236 py1.width as i32, &mut inter1_y, px as i32, py as i32, side as i32,
15237 side as i32, side as i32, 0, 0,
15238 );
15239 }
15240 let mut pred_y = vec![0u16; side * side];
15241 let mut diffwtd_mask_y = Vec::new();
15242 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
15243 // the wedge codebook lookup (comp_group_idx==1's two mutually
15244 // exclusive branches) -- same [`mc::blend_masked_compound`] call
15245 // either way, only the mask source differs.
15246 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
15247 diffwtd_mask_y = vec![0u8; side * side];
15248 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
15249 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
15250 Some(diffwtd_mask_y.as_slice())
15251 } else {
15252 wedge_mask
15253 };
15254 if let Some(mask_y) = mask_y {
15255 mc::blend_masked_compound(
15256 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
15257 );
15258 } else {
15259 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
15260 }
15261
15262 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
15263 mc::predict_compound_intermediate(
15264 &pu0.data,
15265 pu0.width,
15266 pu0.true_width,
15267 pu0.true_height,
15268 mv_to_q4(cpx, mv0.1, false),
15269 mv_to_q4(cpy, mv0.0, false),
15270 scale0,
15271 chroma_side,
15272 chroma_side,
15273 h_filter,
15274 v_filter,
15275 &mut inter0_u,
15276 );
15277 // `av1_init_warp_params` bails when the PLANE's block is
15278 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
15279 // block of an 8x8 luma block stays translational.
15280 if let Some(wp) = &warp0 {
15281 if chroma_side >= 8 {
15282 crate::warp::warp_affine_compound(
15283 wp, &pu0.data, pu0.true_width as i32, pu0.true_height as i32,
15284 pu0.width as i32, &mut inter0_u, cpx as i32, cpy as i32,
15285 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
15286 );
15287 }
15288 }
15289 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
15290 mc::predict_compound_intermediate(
15291 &pu1.data,
15292 pu1.width,
15293 pu1.true_width,
15294 pu1.true_height,
15295 mv_to_q4(cpx, mv1.1, false),
15296 mv_to_q4(cpy, mv1.0, false),
15297 scale1,
15298 chroma_side,
15299 chroma_side,
15300 h_filter,
15301 v_filter,
15302 &mut inter1_u,
15303 );
15304 // `av1_init_warp_params` bails when the PLANE's block is
15305 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
15306 // block of an 8x8 luma block stays translational.
15307 if let Some(wp) = &warp1 {
15308 if chroma_side >= 8 {
15309 crate::warp::warp_affine_compound(
15310 wp, &pu1.data, pu1.true_width as i32, pu1.true_height as i32,
15311 pu1.width as i32, &mut inter1_u, cpx as i32, cpy as i32,
15312 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
15313 );
15314 }
15315 }
15316 let mut pred_u = vec![0u16; chroma_side * chroma_side];
15317 if let Some(mask_y) = mask_y {
15318 mc::blend_masked_compound(
15319 &inter0_u,
15320 &inter1_u,
15321 mask_y,
15322 side,
15323 chroma_side,
15324 chroma_side,
15325 true,
15326 &mut pred_u,
15327 );
15328 } else {
15329 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
15330 }
15331
15332 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
15333 mc::predict_compound_intermediate(
15334 &pv0.data,
15335 pv0.width,
15336 pv0.true_width,
15337 pv0.true_height,
15338 mv_to_q4(cpx, mv0.1, false),
15339 mv_to_q4(cpy, mv0.0, false),
15340 scale0,
15341 chroma_side,
15342 chroma_side,
15343 h_filter,
15344 v_filter,
15345 &mut inter0_v,
15346 );
15347 // `av1_init_warp_params` bails when the PLANE's block is
15348 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
15349 // block of an 8x8 luma block stays translational.
15350 if let Some(wp) = &warp0 {
15351 if chroma_side >= 8 {
15352 crate::warp::warp_affine_compound(
15353 wp, &pv0.data, pv0.true_width as i32, pv0.true_height as i32,
15354 pv0.width as i32, &mut inter0_v, cpx as i32, cpy as i32,
15355 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
15356 );
15357 }
15358 }
15359 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
15360 mc::predict_compound_intermediate(
15361 &pv1.data,
15362 pv1.width,
15363 pv1.true_width,
15364 pv1.true_height,
15365 mv_to_q4(cpx, mv1.1, false),
15366 mv_to_q4(cpy, mv1.0, false),
15367 scale1,
15368 chroma_side,
15369 chroma_side,
15370 h_filter,
15371 v_filter,
15372 &mut inter1_v,
15373 );
15374 // `av1_init_warp_params` bails when the PLANE's block is
15375 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
15376 // block of an 8x8 luma block stays translational.
15377 if let Some(wp) = &warp1 {
15378 if chroma_side >= 8 {
15379 crate::warp::warp_affine_compound(
15380 wp, &pv1.data, pv1.true_width as i32, pv1.true_height as i32,
15381 pv1.width as i32, &mut inter1_v, cpx as i32, cpy as i32,
15382 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
15383 );
15384 }
15385 }
15386 let mut pred_v = vec![0u16; chroma_side * chroma_side];
15387 if let Some(mask_y) = mask_y {
15388 mc::blend_masked_compound(
15389 &inter0_v,
15390 &inter1_v,
15391 mask_y,
15392 side,
15393 chroma_side,
15394 chroma_side,
15395 true,
15396 &mut pred_v,
15397 );
15398 } else {
15399 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
15400 }
15401
15402 vartx_leaves = read_block_tx_size(
15403 dec,
15404 cdfs,
15405 neighbours,
15406 at_mi,
15407 side,
15408 (mi_cols as usize, mi_rows as usize),
15409 true,
15410 skip,
15411 )?
15412 .1;
15413 if skip {
15414 y.reconstruct_mc_rect(
15415 px,
15416 py,
15417 side,
15418 write_w,
15419 write_h,
15420 &pred_y,
15421 &vec![0i32; side * side],
15422 );
15423 u.reconstruct_mc_rect(
15424 cpx,
15425 cpy,
15426 chroma_side,
15427 write_chroma_w,
15428 write_chroma_h,
15429 &pred_u,
15430 &vec![0i32; chroma_side * chroma_side],
15431 );
15432 v.reconstruct_mc_rect(
15433 cpx,
15434 cpy,
15435 chroma_side,
15436 write_chroma_w,
15437 write_chroma_h,
15438 &pred_v,
15439 &vec![0i32; chroma_side * chroma_side],
15440 );
15441 luma_grid = vec![0i32; side * side];
15442 u_grid = vec![0i32; chroma_side * chroma_side];
15443 v_grid = vec![0i32; chroma_side * chroma_side];
15444 } else {
15445 let around = neighbours.around(at, side);
15446 let luma_tx_type;
15447 if let Some(leaves) = vartx_leaves.clone() {
15448 // spec 5.11.17's transform tree, leaf by leaf in the order
15449 // `read_var_tx_size` coded it: each unit reads its own
15450 // coefficients against the neighbour magnitudes the
15451 // earlier units already wrote, and reconstructs over its
15452 // own slice of the block's motion-compensated predictor.
15453 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
15454 let mut first_tx_type = TxType::DctDct;
15455 for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() {
15456 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
15457 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
15458 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
15459 for rr in 0..tx_px {
15460 let start = (row * MI + rr) * side + col * MI;
15461 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
15462 }
15463 let scan = default_scan(tx_px);
15464 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
15465 let (tu_grid, tu_tx_type) = read_inter_plane(
15466 dec,
15467 cdfs,
15468 inter_txbset_for(tx_px, reduced),
15469 &scan,
15470 0,
15471 neighbours.around_mi(tu_mi, tx_px)[0],
15472 mode_for_tx,
15473 y,
15474 tu_px,
15475 tu_py,
15476 tx_px,
15477 base_q_idx,
15478 &tu_pred,
15479 None,
15480 Some(tu_skip_ctx),
15481 )?;
15482 if idx == 0 {
15483 first_tx_type = tu_tx_type;
15484 }
15485 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
15486 }
15487 // `av1_get_tx_type`'s chroma lookup scales the chroma
15488 // position back to luma, so an inter block's chroma
15489 // inherits the *first* (top-left) luma unit's coded type.
15490 luma_tx_type = first_tx_type;
15491 luma_grid = vec![0i32; side * side];
15492 } else {
15493 (luma_grid, luma_tx_type) = read_inter_plane(
15494 dec,
15495 cdfs,
15496 luma_set_inter,
15497 scan_luma,
15498 0,
15499 around[0],
15500 mode_for_tx,
15501 y,
15502 px,
15503 py,
15504 side,
15505 base_q_idx,
15506 &pred_y,
15507 None,
15508 None,
15509 )?;
15510 }
15511 u_grid = read_inter_plane(
15512 dec,
15513 cdfs,
15514 chroma_set,
15515 scan_chroma,
15516 1,
15517 around[1],
15518 mode_for_tx,
15519 u,
15520 cpx,
15521 cpy,
15522 chroma_side,
15523 base_q_idx,
15524 &pred_u,
15525 Some(luma_tx_type),
15526 None,
15527 )?
15528 .0;
15529 v_grid = read_inter_plane(
15530 dec,
15531 cdfs,
15532 chroma_set,
15533 scan_chroma,
15534 2,
15535 around[2],
15536 mode_for_tx,
15537 v,
15538 cpx,
15539 cpy,
15540 chroma_side,
15541 base_q_idx,
15542 &pred_v,
15543 Some(luma_tx_type),
15544 None,
15545 )?
15546 .0;
15547 }
15548 } else {
15549 let ref_frame =
15550 read_single_ref(
15551 dec,
15552 cdfs,
15553 neighbours.above_ref[cmi],
15554 neighbours.above_ref1[cmi],
15555 neighbours.left_ref[rmi],
15556 neighbours.left_ref1[rmi],
15557 );
15558 ref_frame_for_lf = ref_frame;
15559 if std::env::var_os("EC_AV1_TELL").is_some() {
15560 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
15561 eprintln!(
15562 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
15563 dec.debug_bitpos(), dec.debug_state().0
15564 );
15565 }
15566 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
15567 // stacked defects (lf_level ref/mode-delta forwarding, the
15568 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
15569 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
15570 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
15571 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
15572 // widens this from GOLDEN alone to every reference `read_single_ref`
15573 // can name.
15574 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
15575 (ref_y, ref_u, ref_v)
15576 } else {
15577 match other_refs[ref_frame as usize] {
15578 Some((ry, ru, rv)) => (ry, ru, rv),
15579 None => {
15580 return Err(unsupported(
15581 "a reference frame selected with no picture at this frame's own \
15582 ref_frame_idx slot for it",
15583 ));
15584 }
15585 }
15586 };
15587
15588 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
15589 // lane-rect r2: the mv stack must be queried with the block's
15590 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
15591 // xd->width/xd->height, not a square guess) -- `write_w`/
15592 // `write_h` already name the true HORZ/VERT/HORZ_B strip
15593 // footprint (r1's plumbing), so derive bw4/bh4 from those
15594 // instead of the old `side`-square (HORZ_B-only) heuristic.
15595 let bw4 = write_w / 4;
15596 let bh4 = write_h / 4;
15597 // spec 7.10.2.8: only reached when the frame header set
15598 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
15599 // otherwise) -- `cur_offset_0` is this query block's own resolved
15600 // `ref_frame`'s distance from the current frame (spec 7.9.3),
15601 // recomputed per block since different blocks pick different refs.
15602 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
15603 field: t.field,
15604 cur_offset_0: crate::motion_field::get_relative_dist(
15605 t.order_hint_bits,
15606 t.order_hint,
15607 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
15608 ),
15609 allow_high_precision_mv,
15610 });
15611 let gm_table = build_gm_mv_table(
15612 global_motion,
15613 mi_row,
15614 mi_col,
15615 bw4,
15616 bh4,
15617 allow_high_precision_mv,
15618 force_integer_mv,
15619 );
15620 let stack = find_mv_stack_with_sign_bias(
15621 grid,
15622 mi_row,
15623 mi_col,
15624 bw4,
15625 bh4,
15626 ref_frame,
15627 mi_cols as usize,
15628 mi_rows as usize,
15629 sign_bias_table,
15630 &gm_table,
15631 tpl,
15632 );
15633 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
15634 let mut is_globalmv = false;
15635 let (mv, is_new_mv) = if !not_new {
15636 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
15637 // read at most two `drl_mode` bits, one per stack entry past the
15638 // first, stopping at the first `0`. The chosen index selects
15639 // which stack entry `read_mv`'s base predictor comes from
15640 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
15641 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
15642 let mut idx = 0usize;
15643 while idx < 2 && stack.entries.len() > idx + 1 {
15644 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
15645 break;
15646 }
15647 idx += 1;
15648 }
15649 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
15650 (
15651 read_mv(
15652 dec,
15653 &mut cdfs.mv_comp,
15654 &mut cdfs.mv_joint,
15655 base_mv,
15656 allow_high_precision_mv,
15657 force_integer_mv,
15658 ),
15659 true,
15660 )
15661 } else {
15662 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
15663 is_globalmv = !not_zero;
15664 let mv = if !not_zero {
15665 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
15666 // computed at this block's own position in `gm_table`.
15667 gm_table[(ref_frame - LAST_FRAME) as usize]
15668 } else {
15669 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
15670 if nearest {
15671 stack.nearest_mv
15672 } else {
15673 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
15674 // at 1): read at most two more `drl_mode` bits, one per stack
15675 // entry past the second, stopping at the first `0`.
15676 // `drl_ctx[idx]` is the context between `entries[idx]` and
15677 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
15678 // exactly the pair this index is choosing between.
15679 let mut idx = 1usize;
15680 while idx < 3 && stack.entries.len() > idx + 1 {
15681 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
15682 break;
15683 }
15684 idx += 1;
15685 }
15686 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
15687 }
15688 };
15689 (mv, false)
15690 };
15691 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
15692 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
15693 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
15694 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
15695 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
15696 // TRANSLATION -- IDENTITY counts here -- gating the interp
15697 // filter suppress below). Do NOT unify these.
15698 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
15699 let min_bw_bh4 = bw4.min(bh4);
15700 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
15701 let gm_nontrans =
15702 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
15703 if std::env::var_os("EC_AV1_TELL").is_some() {
15704 eprintln!(
15705 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
15706 dec.debug_bitpos(), dec.debug_state().0
15707 );
15708 }
15709 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
15710 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
15711 // right after `assign_mv` and before `read_motion_mode` below --
15712 // libaom's own sequential order. `is_interintra_allowed_bsize`
15713 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
15714 // single-ref path: `is_interintra_allowed_ref` always holds here
15715 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
15716 // `is_interintra_allowed_mode` always holds (every mode this
15717 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
15718 // `SINGLE_INTER_MODE_START..END` by construction).
15719 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
15720 let mut interintra_mode: Option<u8> = None;
15721 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
15722 if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) {
15723 let bsize_group = if side == 16 { 2 } else { 3 };
15724 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
15725 if interintra {
15726 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
15727 // then -- gated on block size ALONE, never the
15728 // `enable_interintra_wedge` seq bit -- the wedge flag
15729 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
15730 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
15731 let wedge_bsize = if side == 16 { 6 } else { 9 };
15732 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
15733 if wedge {
15734 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
15735 // ADAPTING CDF symbol over the same `wedge_bsize` row;
15736 // NO sign symbol follows -- libaom fixes
15737 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
15738 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
15739 WII_HITS.with(|c| c.set(c.get() + 1));
15740 wedge_mask = Some((
15741 crate::wedge::wedge_masks()
15742 .codebook(side)
15743 .mask(0, wedge_index as usize),
15744 side,
15745 ));
15746 } else {
15747 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
15748 }
15749 interintra_mode = Some(ii);
15750 }
15751 }
15752 if std::env::var_os("EC_AV1_TELL").is_some() {
15753 eprintln!(
15754 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
15755 dec.debug_bitpos(), dec.debug_state().0
15756 );
15757 }
15758 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
15759 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
15760 // placed right after MV assignment and before the switchable
15761 // interp filter read below (`read_mb_interp_filter`, decodemv.c
15762 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
15763 // (`reconinter.h`) reduces, for every block this single-ref path
15764 // reaches, to "does an inter neighbour border the above row or
15765 // left column": `is_motion_variation_allowed_bsize` always holds
15766 // (`side` is never below 16px on this path), `ref_frame[1] !=
15767 // INTRA_FRAME` always holds (no interintra reader here),
15768 // `is_motion_variation_allowed_compound` always holds (this is
15769 // the single-ref branch), and `is_global_mv_block` never
15770 // triggers (this decoder's global motion is always `IDENTITY`,
15771 // so its warp `type` is never `> TRANSLATION`). A stream with
15772 // `allow_warped_motion=1` is refused right at an eligible block
15773 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
15774 // not ported, so this decoder cannot tell a real
15775 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
15776 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
15777 // the header allows warp -- reading the wrong alphabet desyncs
15778 // the tile.
15779 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
15780 // fails libaom's `is_motion_variation_allowed_compound`: the
15781 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
15782 let motion_mode_eligible = switchable_motion_mode
15783 && !skip_mode
15784 && interintra_mode.is_none()
15785 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
15786 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
15787 .is_empty())
15788 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
15789 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
15790 // mv reads no motion_mode/obmc symbol at all -- implicit
15791 // SIMPLE_TRANSLATION.
15792 && !(is_global_mv_block && !force_integer_mv);
15793 let mut obmc_selected = false;
15794 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
15795 // *and* the local warp estimate is valid (`!wm_params.invalid`,
15796 // `av1_find_projection`) -- an invalid estimate falls back to
15797 // this block's own translational mv, same as any other block
15798 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
15799 // fallback here since this decoder's global motion is always
15800 // IDENTITY).
15801 let mut warp_params: Option<crate::warp::WarpParams> = None;
15802 // Tracks the SYMBOL value, not projection validity: libaom's
15803 // `av1_is_interp_needed` suppresses the interp-filter read for
15804 // `motion_mode == WARPED_CAUSAL` even when the projection later
15805 // falls back to translation. Its third suppressor,
15806 // `is_nontrans_global_motion`, matches our unconditional
15807 // `is_globalmv` only because this decoder codes global motion as
15808 // IDENTITY (non-TRANSLATION) and never reads switchable filters
15809 // below 8x8 -- porting TRANSLATION global motion must add the
15810 // wmtype check here.
15811 let mut warped_selected = false;
15812 if motion_mode_eligible {
15813 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
15814 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
15815 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
15816 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
15817 // strip motion_mode read diverged on the square row.
15818 let bsize_idx = if write_w == write_h {
15819 (write_w.trailing_zeros() - 3) as usize
15820 } else if write_w == 16 {
15821 4
15822 } else {
15823 5
15824 };
15825 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
15826 // instead of the 2-symbol `obmc_cdf` exactly when
15827 // `num_proj_ref >= 1` under `allow_warped_motion`.
15828 // lane-scaledref r2 + lane-fimv r1: libaom
15829 // `motion_mode_allowed` (`blockd.h:1484`) requires BOTH
15830 // `!av1_is_scaled(block_ref_scale_factors[0])` and
15831 // `!xd->cur_frame_force_integer_mv` for WARPED_CAUSAL --
15832 // under a scaled reference (superres) OR on a frame whose
15833 // header set `force_integer_mv` (screen content) the block
15834 // reads the 2-symbol `obmc_cdf`, never the 3-symbol
15835 // `motion_mode_cdf`. Reading the wrong alphabet here narrows
15836 // the arithmetic coder by the wrong amount and predicts the
15837 // rest of the tile off a diverged state: silently wrong
15838 // pixels, not a desync error. `force_integer_mv` is the
15839 // per-frame value (spec 5.9.2: coded per frame only when
15840 // `seq_force_integer_mv == SELECT_INTEGER_MV`, threaded from
15841 // `FrameHeader::force_integer_mv`).
15842 // libaom `av1_is_scaled` is `x_scale_fp != REF_NO_SCALE ||
15843 // y_scale_fp != REF_NO_SCALE`; the y half is unreachable here
15844 // because a reference whose height differs from this frame's
15845 // true size is refused before any tile decodes ("a reference
15846 // picture whose height does not match this frame's own true
15847 // size", ~14681). Whoever lifts that refusal adds the y term.
15848 let ref_is_scaled =
15849 mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE;
15850 let proj_ok = num_proj_ref(
15851 grid,
15852 mi_row,
15853 mi_col,
15854 bw4,
15855 bh4,
15856 mi_cols as usize,
15857 mi_rows as usize,
15858 ref_frame,
15859 ) >= 1;
15860 let warp_eligible =
15861 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
15862 if allow_warped_motion && proj_ok && ref_is_scaled {
15863 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1));
15864 }
15865 if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv {
15866 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
15867 }
15868 if warp_eligible {
15869 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
15870 match mode {
15871 0 => {}
15872 1 => {
15873 obmc_selected = true;
15874 OBMC_HITS.with(|c| c.set(c.get() + 1));
15875 }
15876 _ => {
15877 warped_selected = true;
15878 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
15879 let mut samples = find_samples(
15880 grid,
15881 mi_row,
15882 mi_col,
15883 bw4,
15884 bh4,
15885 mi_cols as usize,
15886 mi_rows as usize,
15887 ref_frame,
15888 );
15889 if std::env::var_os("EC_WARP_DEBUG").is_some() {
15890 eprintln!(
15891 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
15892 samples.len()
15893 );
15894 for (i, s) in samples.iter().enumerate() {
15895 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
15896 }
15897 }
15898 if samples.len() > 1 {
15899 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
15900 }
15901 warp_params = crate::warp::find_projection(
15902 &samples,
15903 // lane-rect r2: the block's TRUE dims -- a
15904 // 32x16 strip's model center is not a
15905 // 32x32's (aom av1_find_projection bw/bh).
15906 write_w as i32,
15907 write_h as i32,
15908 mv.1,
15909 mv.0,
15910 mi_row as i32,
15911 mi_col as i32,
15912 );
15913 if std::env::var_os("EC_WARP_DEBUG").is_some() {
15914 eprintln!(
15915 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
15916 samples.len(), mv.0, mv.1, warp_params
15917 );
15918 for (i, s) in samples.iter().enumerate() {
15919 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
15920 }
15921 }
15922 }
15923 }
15924 } else {
15925 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
15926 if obmc_selected {
15927 OBMC_HITS.with(|c| c.set(c.get() + 1));
15928 }
15929 }
15930 }
15931 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
15932 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
15933 // libaom's `av1_init_warp_params` runs for every inter
15934 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
15935 // reachable when `warp_params` is still `None` here: a block
15936 // that read (and got) local `WARPED_CAUSAL` above already has
15937 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
15938 // checks FIRST and short-circuits on -- the global branch is an
15939 // `else if`, never layered on top. `is_global_mv_block` already
15940 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
15941 // >=8px both dims, matching `av1_init_warp_params`'s
15942 // `block_height < 8 || block_width < 8` early return) and, via
15943 // `motion_mode_eligible`'s own suppression above, the
15944 // `force_integer_mv` case never reads a motion_mode symbol at
15945 // all -- checked again here directly since this branch fires
15946 // independent of `motion_mode_eligible`.
15947 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
15948 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
15949 warp_params = crate::warp::global_warp_params(gm_ref.params);
15950 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
15951 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
15952 }
15953 }
15954 if std::env::var_os("EC_AV1_TELL").is_some() {
15955 eprintln!(
15956 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
15957 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
15958 );
15959 }
15960 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
15961 // this block's switchable_interp context when that neighbour coded
15962 // the SAME reference frame this block is about to read -- a
15963 // different-ref neighbour reads as "no neighbour" ([3, 3], the
15964 // sentinel `Neighbours::new` already seeds unset slots with),
15965 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
15966 // block next to a LAST_FRAME one inherits that neighbour's filter
15967 // choice into its own context, corrupting the symbol it reads.
15968 // lane-av1idx r2: also match on the neighbour's SECOND reference
15969 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
15970 // see the 16x16 leaf's own comment above for the spec citation.
15971 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
15972 || neighbours.above_ref1[cmi] == Some(ref_frame)
15973 {
15974 neighbours.above_filter[cmi]
15975 } else {
15976 [3, 3]
15977 };
15978 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
15979 || neighbours.left_ref1[rmi] == Some(ref_frame)
15980 {
15981 neighbours.left_filter[rmi]
15982 } else {
15983 [3, 3]
15984 };
15985 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
15986 dec,
15987 cdfs,
15988 interp_fixed,
15989 enable_dual_filter,
15990 gm_nontrans || warped_selected,
15991 above_filter_ctx,
15992 left_filter_ctx,
15993 false,
15994 );
15995 block_filter = resolved_filter;
15996 globalmv_for_lf = is_globalmv;
15997 if std::env::var_os("EC_AV1_TELL").is_some() {
15998 eprintln!(
15999 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
16000 dec.debug_bitpos(), dec.debug_state().0
16001 );
16002 }
16003 if std::env::var_os("EC_AV1_TRACE").is_some() {
16004 eprintln!(
16005 "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={}",
16006 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()
16007 );
16008 }
16009 // lane-rect r2: see the compound path's matching comment above --
16010 // `grid` must be stamped with the block's true bh4/bw4 span, not
16011 // a square `bw4`x`bw4` guess.
16012 for dr in 0..bh4 {
16013 for dc in 0..bw4 {
16014 grid.set(
16015 mi_row + dr,
16016 mi_col + dc,
16017 MiInfo {
16018 is_inter: true,
16019 ref_frame,
16020 // An interintra block records ref_frame[1] ==
16021 // INTRA_FRAME (0): warp-sample gathering
16022 // (libaom av1_findSamples, mvref_common.c:1155)
16023 // requires ref_frame[1] == NONE_FRAME, so such a
16024 // neighbour must not donate samples or count in
16025 // num_proj_ref.
16026 ref_frame1: interintra_mode.map(|_| 0),
16027 mv1: None,
16028 mv,
16029 is_new_mv,
16030 size: bw4,
16031 size_h: bh4,
16032 is_global_mv0: is_global_mv_block,
16033 is_global_mv1: false,
16034 },
16035 );
16036 }
16037 }
16038 mode_for_tx = 0;
16039 uv_predict_mode = DC_PRED;
16040
16041 // lane-superres r9: spec 7.11.3.3's x_scale_fp comes from LUMA
16042 // widths only (r8's derivation) and applies unchanged to the
16043 // chroma calls below (their x_q4 is already in the chroma
16044 // plane's own pixel units). `mc::predict_scaled` has no warp/OBMC
16045 // /interintra counterpart -- those three combinations are refused
16046 // by name instead of silently sampling a scaled reference wrong
16047 // (warp_params/obmc_selected/interintra_mode are all resolved by
16048 // this point, every symbol for this block already read).
16049 let luma_scale = mc::scale_factor(py_ref.width, frame_width);
16050 if luma_scale != mc::REF_NO_SCALE {
16051 // lane-scaledref r1: libaom `allow_warp`
16052 // (av1/common/reconinter.c:41) suppresses BOTH local and
16053 // global warp under a scaled reference and predicts
16054 // translationally instead -- that fallback is implemented
16055 // below, but the one real aomenc stream this round found
16056 // that reaches it (`--enable-warped-motion=1`,
16057 // `--superres-denominator=16`, seed 47) still mismatches
16058 // ffmpeg at frame 2 luma, so the case stays refused by name
16059 // until it has a green gate rather than shipping wrong
16060 // pixels behind a lifted refusal.
16061 if warp_params.is_some() {
16062 SCALED_WARP_FALLBACK_HITS.with(|c| c.set(c.get() + 1));
16063 return Err(unsupported(
16064 "warp prediction with a scaled reference (superres, unimplemented)",
16065 ));
16066 }
16067 if obmc_selected {
16068 SCALED_OBMC_HITS.with(|c| c.set(c.get() + 1));
16069 }
16070 if interintra_mode.is_some() {
16071 SCALED_INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
16072 }
16073 }
16074
16075 let mut pred_y = vec![0u16; side * side];
16076 let mut pred_u = vec![0u16; chroma_side * chroma_side];
16077 let mut pred_v = vec![0u16; chroma_side * chroma_side];
16078 if luma_scale == mc::REF_NO_SCALE {
16079 mc::predict_with_filters(
16080 &py_ref.data,
16081 py_ref.width,
16082 py_ref.true_width,
16083 py_ref.true_height,
16084 mv_to_q4(px, mv.1, true),
16085 mv_to_q4(py, mv.0, true),
16086 side,
16087 side,
16088 h_filter,
16089 v_filter,
16090 &mut pred_y,
16091 );
16092 mc::predict_with_filters(
16093 &pu_ref.data,
16094 pu_ref.width,
16095 pu_ref.true_width,
16096 pu_ref.true_height,
16097 mv_to_q4(cpx, mv.1, false),
16098 mv_to_q4(cpy, mv.0, false),
16099 chroma_side,
16100 chroma_side,
16101 h_filter,
16102 v_filter,
16103 &mut pred_u,
16104 );
16105 mc::predict_with_filters(
16106 &pv_ref.data,
16107 pv_ref.width,
16108 pv_ref.true_width,
16109 pv_ref.true_height,
16110 mv_to_q4(cpx, mv.1, false),
16111 mv_to_q4(cpy, mv.0, false),
16112 chroma_side,
16113 chroma_side,
16114 h_filter,
16115 v_filter,
16116 &mut pred_v,
16117 );
16118 } else {
16119 mc::predict_scaled(
16120 &py_ref.data,
16121 py_ref.width,
16122 py_ref.true_width,
16123 py_ref.true_height,
16124 mv_to_q4(px, mv.1, true),
16125 mv_to_q4(py, mv.0, true),
16126 luma_scale,
16127 side,
16128 side,
16129 h_filter,
16130 v_filter,
16131 &mut pred_y,
16132 );
16133 mc::predict_scaled(
16134 &pu_ref.data,
16135 pu_ref.width,
16136 pu_ref.true_width,
16137 pu_ref.true_height,
16138 mv_to_q4(cpx, mv.1, false),
16139 mv_to_q4(cpy, mv.0, false),
16140 luma_scale,
16141 chroma_side,
16142 chroma_side,
16143 h_filter,
16144 v_filter,
16145 &mut pred_u,
16146 );
16147 mc::predict_scaled(
16148 &pv_ref.data,
16149 pv_ref.width,
16150 pv_ref.true_width,
16151 pv_ref.true_height,
16152 mv_to_q4(cpx, mv.1, false),
16153 mv_to_q4(cpy, mv.0, false),
16154 luma_scale,
16155 chroma_side,
16156 chroma_side,
16157 h_filter,
16158 v_filter,
16159 &mut pred_v,
16160 );
16161 }
16162
16163 // lane-scaledref r1: libaom `allow_warp` (av1/common/reconinter.c:41)
16164 // opens with `if (av1_is_scaled(sf)) return 0;` -- BOTH local
16165 // (`wm_params`) and global warp fall back to the translational
16166 // prediction above when the reference is scaled, even though the
16167 // motion_mode symbol was still read and warp_params still
16168 // resolved. Suppress the warp, keep every symbol read.
16169 if let Some(params) = warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE) {
16170 crate::warp::warp_affine(
16171 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
16172 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
16173 side as i32, side as i32, 0, 0,
16174 );
16175 // libaom `av1_init_warp_params` (reconinter.c): warp is
16176 // per PLANE and bails out at `block_width < 8 ||
16177 // block_height < 8`, so a plane whose own block is under
16178 // 8x8 keeps the translational prediction built above --
16179 // in 420 that is every chroma plane of a luma block below
16180 // 16x16 (lane-gmaffine r4: chroma-only mismatch of a few
16181 // levels on both 8x8-leaf motion gates).
16182 if chroma_side >= 8 {
16183 crate::warp::warp_affine(
16184 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
16185 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
16186 chroma_side as i32, chroma_side as i32, 1, 1,
16187 );
16188 crate::warp::warp_affine(
16189 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
16190 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
16191 chroma_side as i32, chroma_side as i32, 1, 1,
16192 );
16193 }
16194 }
16195
16196 if obmc_selected {
16197 obmc_blend(
16198 grid,
16199 neighbours,
16200 mi_row,
16201 mi_col,
16202 bw4,
16203 bh4,
16204 mi_rows as usize,
16205 mi_cols as usize,
16206 side,
16207 write_w,
16208 write_h,
16209 chroma_side,
16210 px,
16211 py,
16212 cpx,
16213 cpy,
16214 ref_y,
16215 ref_u,
16216 ref_v,
16217 other_refs,
16218 interp_fixed,
16219 frame_width,
16220 &mut pred_y,
16221 &mut pred_u,
16222 &mut pred_v,
16223 )?;
16224 }
16225
16226 // Mutually exclusive with warp/OBMC (motion_mode is not read for
16227 // an interintra block): blend the intra predictor over the MC
16228 // result, all planes (reconinter.c av1_build_interintra_predictor
16229 // plane loop).
16230 if let Some(ii) = interintra_mode {
16231 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
16232 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
16233 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
16234 }
16235
16236 vartx_leaves = read_block_tx_size(
16237 dec,
16238 cdfs,
16239 neighbours,
16240 at_mi,
16241 side,
16242 (mi_cols as usize, mi_rows as usize),
16243 true,
16244 skip,
16245 )?
16246 .1;
16247 if skip {
16248 y.reconstruct_mc_rect(
16249 px,
16250 py,
16251 side,
16252 write_w,
16253 write_h,
16254 &pred_y,
16255 &vec![0i32; side * side],
16256 );
16257 u.reconstruct_mc_rect(
16258 cpx,
16259 cpy,
16260 chroma_side,
16261 write_chroma_w,
16262 write_chroma_h,
16263 &pred_u,
16264 &vec![0i32; chroma_side * chroma_side],
16265 );
16266 v.reconstruct_mc_rect(
16267 cpx,
16268 cpy,
16269 chroma_side,
16270 write_chroma_w,
16271 write_chroma_h,
16272 &pred_v,
16273 &vec![0i32; chroma_side * chroma_side],
16274 );
16275 luma_grid = vec![0i32; side * side];
16276 u_grid = vec![0i32; chroma_side * chroma_side];
16277 v_grid = vec![0i32; chroma_side * chroma_side];
16278 } else {
16279 let around = neighbours.around(at, side);
16280 let luma_tx_type;
16281 if let Some(leaves) = vartx_leaves.clone() {
16282 // spec 5.11.17's transform tree, leaf by leaf in the order
16283 // `read_var_tx_size` coded it: each unit reads its own
16284 // coefficients against the neighbour magnitudes the
16285 // earlier units already wrote, and reconstructs over its
16286 // own slice of the block's motion-compensated predictor.
16287 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
16288 let mut first_tx_type = TxType::DctDct;
16289 for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() {
16290 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
16291 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
16292 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
16293 for rr in 0..tx_px {
16294 let start = (row * MI + rr) * side + col * MI;
16295 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
16296 }
16297 let scan = default_scan(tx_px);
16298 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
16299 let (tu_grid, tu_tx_type) = read_inter_plane(
16300 dec,
16301 cdfs,
16302 inter_txbset_for(tx_px, reduced),
16303 &scan,
16304 0,
16305 neighbours.around_mi(tu_mi, tx_px)[0],
16306 mode_for_tx,
16307 y,
16308 tu_px,
16309 tu_py,
16310 tx_px,
16311 base_q_idx,
16312 &tu_pred,
16313 None,
16314 Some(tu_skip_ctx),
16315 )?;
16316 if idx == 0 {
16317 first_tx_type = tu_tx_type;
16318 }
16319 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
16320 }
16321 // `av1_get_tx_type`'s chroma lookup scales the chroma
16322 // position back to luma, so an inter block's chroma
16323 // inherits the *first* (top-left) luma unit's coded type.
16324 luma_tx_type = first_tx_type;
16325 luma_grid = vec![0i32; side * side];
16326 } else {
16327 (luma_grid, luma_tx_type) = read_inter_plane(
16328 dec,
16329 cdfs,
16330 luma_set_inter,
16331 scan_luma,
16332 0,
16333 around[0],
16334 mode_for_tx,
16335 y,
16336 px,
16337 py,
16338 side,
16339 base_q_idx,
16340 &pred_y,
16341 None,
16342 None,
16343 )?;
16344 }
16345 u_grid = read_inter_plane(
16346 dec,
16347 cdfs,
16348 chroma_set,
16349 scan_chroma,
16350 1,
16351 around[1],
16352 mode_for_tx,
16353 u,
16354 cpx,
16355 cpy,
16356 chroma_side,
16357 base_q_idx,
16358 &pred_u,
16359 Some(luma_tx_type),
16360 None,
16361 )?
16362 .0;
16363 v_grid = read_inter_plane(
16364 dec,
16365 cdfs,
16366 chroma_set,
16367 scan_chroma,
16368 2,
16369 around[2],
16370 mode_for_tx,
16371 v,
16372 cpx,
16373 cpy,
16374 chroma_side,
16375 base_q_idx,
16376 &pred_v,
16377 Some(luma_tx_type),
16378 None,
16379 )?
16380 .0;
16381 }
16382 }
16383 } else {
16384 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
16385 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
16386 // its own true-width/height edge/predict math, unlike the inter
16387 // skip path above (which only needed a clipped write of an
16388 // already-square-predicted buffer). Named refusal instead of a
16389 // silently wrong square-shaped intra prediction.
16390 if write_w != side || write_h != side {
16391 return Err(unsupported(
16392 "an intra-coded HORZ/VERT strip needs rectangular intra prediction \
16393 this decoder does not code yet",
16394 ));
16395 }
16396 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
16397 if mode >= 13 {
16398 return Err(unsupported(
16399 "an intra mode this decoder does not code (round 2)",
16400 ));
16401 }
16402 if (V_PRED..=D67_PRED).contains(&mode) {
16403 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
16404 if angle != ANGLE_DELTA_ZERO {
16405 return Err(unsupported(
16406 "a nonzero angle delta (this encoder never writes one)",
16407 ));
16408 }
16409 }
16410 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
16411 if (9..=12).contains(&uv_mode) {
16412 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
16413 }
16414 let alpha = if uv_mode == DC_PRED {
16415 None
16416 } else if uv_mode == UV_CFL_PRED {
16417 Some(read_cfl_alphas(dec, cdfs))
16418 } else {
16419 None
16420 };
16421 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
16422 // the angle-delta question, same as [`read_intra_mode`]'s own copy
16423 // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
16424 // `else` branch below is exact for it either way.
16425 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
16426 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
16427 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
16428 } else {
16429 0
16430 };
16431 if angle_delta_uv != 0 {
16432 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
16433 }
16434 uv_predict_mode = if uv_mode == UV_CFL_PRED {
16435 DC_PRED
16436 } else {
16437 uv_mode
16438 };
16439 // lane-chroma r4: same chroma edge-filter-strength neighbour check
16440 // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
16441 // neighbour's own `uv_mode`, not the luma one.
16442 let smooth_neighbor_uv =
16443 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
16444 // `read_palette_mode_info` (decodemv.c:567, called from
16445 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
16446 // gating and same corner-cut as `read_intra_mode`'s own copy above
16447 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
16448 // safe since a nonzero neighbour `palette_size` would already have
16449 // refused the decode that produced it.
16450 if allow_screen_content_tools
16451 && let Some(bsize_ctx) = palette_bsize_ctx(side)
16452 {
16453 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
16454 return Err(unsupported(
16455 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
16456 ));
16457 }
16458 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
16459 return Err(unsupported(
16460 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
16461 ));
16462 }
16463 }
16464 // lane-fiinter r1: `read_filter_intra_mode_info` (libaom `decodemv.c`,
16465 // the tail of `read_intra_block_mode_info`) -- an intra block inside
16466 // an INTER frame reads `use_filter_intra` in exactly the same place a
16467 // key-frame block does, right after the palette syntax. Nothing read
16468 // it here before this round, and aomenc enables filter intra by
16469 // default, so every inter frame carrying one desynced at this symbol.
16470 // `av1_filter_intra_allowed`'s `palette_size[0] == 0` term is implied:
16471 // a real palette-Y block already returned above.
16472 let mut filter_intra = None;
16473 if mode == DC_PRED
16474 && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
16475 && let Some(class) = filter_intra_size_class(side)
16476 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
16477 {
16478 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
16479 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
16480 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
16481 }
16482 mode_for_tx = mode;
16483 block_filter = [3, 3];
16484 ref_frame_for_lf = 0;
16485 globalmv_for_lf = false;
16486 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
16487 for dr in 0..side / 4 {
16488 for dc in 0..side / 4 {
16489 grid.set(
16490 mi_row + dr,
16491 mi_col + dc,
16492 MiInfo {
16493 is_inter: false,
16494 ref_frame: -1,
16495 ref_frame1: None,
16496 mv1: None,
16497 mv: (0, 0),
16498 is_new_mv: false,
16499 size: side / 4,
16500 size_h: side / 4,
16501 is_global_mv0: false,
16502 is_global_mv1: false,
16503 },
16504 );
16505 }
16506 }
16507
16508 // lane-intrainter r1: an intra block in an inter frame reads the same
16509 // `tx_depth` symbol a key-frame block does, and when it splits, the
16510 // block codes one intra prediction + one coefficient set PER
16511 // transform unit (`decode_block`'s multi-TU branch), not one for the
16512 // whole block. The leaf list rides the existing `vartx_leaves` slot,
16513 // whose tail already does the split-block neighbour write-back
16514 // (`record_split_luma`) and the per-TU deblock edges.
16515 vartx_leaves = read_block_tx_size(
16516 dec,
16517 cdfs,
16518 neighbours,
16519 at_mi,
16520 side,
16521 (mi_cols as usize, mi_rows as usize),
16522 false,
16523 skip,
16524 )?
16525 .1;
16526 let reach = Reach::of(side, px, py, y.width, y.height);
16527 let split_luma = vartx_leaves.is_some();
16528 if let Some(leaves) = vartx_leaves.clone() {
16529 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
16530 for &(row, col, tx_px) in &leaves {
16531 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
16532 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
16533 // A transform unit inside a block is not a block at that
16534 // position (class from lane-palette2 r12): top-right /
16535 // bottom-left availability is the block's, narrowed by the
16536 // unit's own offset inside it.
16537 let tu_reach = Reach::of_tu(side, side, col * MI, row * MI, tx_px, tx_px, reach);
16538 let tu_grid = if skip {
16539 y.reconstruct(
16540 tu_px,
16541 tu_py,
16542 tx_px,
16543 mode,
16544 0,
16545 tu_reach,
16546 &vec![0i32; tx_px * tx_px],
16547 None,
16548 filter_intra,
16549 false,
16550 );
16551 vec![0i32; tx_px * tx_px]
16552 } else {
16553 // The unit's bsize is smaller than the block it sits in,
16554 // so `txb_skip_ctx` is the neighbour-magnitude table, not
16555 // the lone-TU 0 (`get_txb_ctx_general`).
16556 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
16557 read_plane(
16558 dec,
16559 cdfs,
16560 txbset_for(tx_px, reduced),
16561 &default_scan(tx_px),
16562 0,
16563 neighbours.around_mi(tu_mi, tx_px)[0],
16564 mode,
16565 mode,
16566 0,
16567 tu_reach,
16568 y,
16569 tu_px,
16570 tu_py,
16571 tx_px,
16572 tx_px,
16573 base_q_idx,
16574 None,
16575 filter_intra,
16576 Some(tu_skip_ctx),
16577 false,
16578 )?
16579 };
16580 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
16581 }
16582 }
16583 if skip {
16584 if !split_luma {
16585 y.reconstruct(
16586 px,
16587 py,
16588 side,
16589 mode,
16590 0,
16591 reach,
16592 &vec![0i32; side * side],
16593 None,
16594 filter_intra,
16595 false,
16596 );
16597 }
16598 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
16599 u.reconstruct(
16600 cpx,
16601 cpy,
16602 chroma_side,
16603 uv_predict_mode,
16604 angle_delta_uv,
16605 reach,
16606 &vec![0i32; chroma_side * chroma_side],
16607 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
16608 None,
16609 smooth_neighbor_uv,
16610 );
16611 v.reconstruct(
16612 cpx,
16613 cpy,
16614 chroma_side,
16615 uv_predict_mode,
16616 angle_delta_uv,
16617 reach,
16618 &vec![0i32; chroma_side * chroma_side],
16619 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
16620 None,
16621 smooth_neighbor_uv,
16622 );
16623 luma_grid = vec![0i32; side * side];
16624 u_grid = vec![0i32; chroma_side * chroma_side];
16625 v_grid = vec![0i32; chroma_side * chroma_side];
16626 } else {
16627 let around = neighbours.around(at, side);
16628 luma_grid = if split_luma {
16629 // Already coded and reconstructed unit by unit above; the
16630 // block-level grid is only the neighbour write-back's input,
16631 // which `record_split_luma` ignores for plane 0.
16632 vec![0i32; side * side]
16633 } else {
16634 read_plane(
16635 dec,
16636 cdfs,
16637 luma_set_intra,
16638 scan_luma,
16639 0,
16640 around[0],
16641 mode,
16642 mode,
16643 0,
16644 reach,
16645 y,
16646 px,
16647 py,
16648 side,
16649 luma_tx,
16650 base_q_idx,
16651 None,
16652 filter_intra,
16653 None,
16654 false,
16655 )?
16656 };
16657 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
16658 u_grid = read_plane(
16659 dec,
16660 cdfs,
16661 chroma_set,
16662 scan_chroma,
16663 1,
16664 around[1],
16665 mode,
16666 uv_predict_mode,
16667 angle_delta_uv,
16668 reach,
16669 u,
16670 cpx,
16671 cpy,
16672 chroma_side,
16673 chroma_tx,
16674 base_q_idx,
16675 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
16676 None,
16677 None,
16678 smooth_neighbor_uv,
16679 )?;
16680 v_grid = read_plane(
16681 dec,
16682 cdfs,
16683 chroma_set,
16684 scan_chroma,
16685 2,
16686 around[2],
16687 mode,
16688 uv_predict_mode,
16689 angle_delta_uv,
16690 reach,
16691 v,
16692 cpx,
16693 cpy,
16694 chroma_side,
16695 chroma_tx,
16696 base_q_idx,
16697 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
16698 None,
16699 None,
16700 smooth_neighbor_uv,
16701 )?;
16702 }
16703 }
16704 // lane-comppin r9: end-of-block checkpoint -- everything between
16705 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
16706 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
16707 // equivalent post-content point (added at the matching call site)
16708 // narrows the ladder to this block's own tail instead of the next
16709 // block's partition read.
16710 if std::env::var_os("EC_AV1_TELL").is_some() {
16711 eprintln!(
16712 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
16713 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
16714 );
16715 }
16716 if vartx_leaves.is_some() {
16717 // Plane 0 is already correct per transform unit
16718 // ([`Neighbours::record_mi_luma`] above); this writes everything else
16719 // [`Neighbours::record_rect`] would (a var-tx block is always square,
16720 // so `write_w == write_h == side`).
16721 neighbours.record_split_luma(at, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]);
16722 } else {
16723 neighbours.record_rect(
16724 at,
16725 write_w,
16726 write_h,
16727 mode_for_tx,
16728 uv_predict_mode,
16729 &[luma_grid, u_grid, v_grid],
16730 );
16731 }
16732 neighbours.record_inter_rect(
16733 at,
16734 write_w,
16735 write_h,
16736 skip,
16737 is_inter,
16738 ref_frame_for_lf,
16739 block_filter,
16740 skip_mode,
16741 );
16742 if let Some((ref1, group_idx, idx)) = compound_ctx {
16743 neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx);
16744 }
16745 neighbours.fill_skip_grid_rect(
16746 (r * (SUB / MI), c * (SUB / MI)),
16747 write_w / MI,
16748 write_h / MI,
16749 skip,
16750 );
16751 neighbours.fill_lf_grid_rect(
16752 (r * (SUB / MI), c * (SUB / MI)),
16753 write_w / MI,
16754 write_h / MI,
16755 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
16756 // single-scalar corner-cut deblocked the strip seam with the wrong
16757 // edge length (1-px chroma drift on rect-flake-1 f17+).
16758 write_w as u8,
16759 write_h as u8,
16760 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
16761 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
16762 if globalmv_for_lf {
16763 -ref_frame_for_lf
16764 } else {
16765 ref_frame_for_lf
16766 },
16767 );
16768 // lane-txselect: a var-tx block's deblock edges follow its own transform
16769 // units, not the block. Chroma still reads `tx_h_grid / 2` (the block's
16770 // uv transform is not split) -- a known corner-cut of this round.
16771 if let Some(leaves) = &vartx_leaves {
16772 for &(row, col, tx_px) in leaves {
16773 neighbours.fill_lf_grid_rect(
16774 (at_mi.0 + row, at_mi.1 + col),
16775 tx_px / MI,
16776 tx_px / MI,
16777 tx_px as u8,
16778 tx_px as u8,
16779 if globalmv_for_lf {
16780 -ref_frame_for_lf
16781 } else {
16782 ref_frame_for_lf
16783 },
16784 );
16785 }
16786 }
16787 Ok(())
16788}
16789
16790/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
16791/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
16792/// exact symbol order: its own skip flag, intra/inter choice and (when
16793/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
16794/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
16795/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
16796/// same as [`decode_leaf8`]'s coefficient layer but with
16797/// motion-compensated prediction instead of intra prediction when inter.
16798/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
16799/// skip/intra-inter context, overridden by `prev_leaf` exactly as
16800/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
16801/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
16802/// and intra/inter choice, for the next leaf or the caller's final
16803/// write-back.
16804#[allow(clippy::too_many_arguments)]
16805fn decode_inter_block8(
16806 dec: &mut SymbolDecoder,
16807 cdfs: &mut Cdfs,
16808 neighbours: &mut Neighbours,
16809 grid: &mut MiGrid,
16810 mi_cols: u32,
16811 mi_rows: u32,
16812 outer_at: (usize, usize),
16813 leaf_mi: (usize, usize),
16814 y: &mut PlaneBuf,
16815 u: &mut PlaneBuf,
16816 v: &mut PlaneBuf,
16817 ref_y: &PlaneBuf,
16818 ref_u: &PlaneBuf,
16819 ref_v: &PlaneBuf,
16820 other_refs: &RefSlots,
16821 base_q_idx: u8,
16822 scan8: &[u16],
16823 scan4: &[u16],
16824 allow_high_precision_mv: bool,
16825 force_integer_mv: bool,
16826 // lane-gmaffine r1: this frame header's own `global_motion` table (spec
16827 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` -- same table
16828 // [`decode_inter_block`] takes, threaded here so the 8x8 leaf can code
16829 // `GLOBALMV` (`gm_get_motion_vector`), fill its mv stack's missing
16830 // candidates with the gm mv (gm r6's root cause) and build a global
16831 // warp prediction.
16832 global_motion: &[ec_av1_syntax::WarpParams; 7],
16833 // lane-gmaffine r1: this sequence header's own `enable_dual_filter` bit,
16834 // for the leaf's own `read_mb_interp_filter` below.
16835 enable_dual_filter: bool,
16836 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
16837 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
16838 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
16839 // context uses that same approximation.
16840 reference_select: bool,
16841 enable_masked_compound: bool,
16842 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
16843 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
16844 // drops the `side` check entirely.
16845 enable_interintra_compound: bool,
16846 enable_jnt_comp: bool,
16847 order_hint_bits: u32,
16848 order_hint: u32,
16849 ref_order_hints: [u32; 7],
16850 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
16851 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
16852 // so its `skip_mode` context reuses the same [`SUB`]-grid
16853 // `above_skip_mode[cmi]`/`left_skip_mode[rmi]` the enclosing 16x16 slot
16854 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
16855 // just above).
16856 skip_mode_present: bool,
16857 skip_mode_frame: [u8; 2],
16858 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
16859 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
16860 reduced_tx_set: bool,
16861 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
16862 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
16863 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
16864 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
16865 // prediction is always `Regular` (documented corner-cut, `mc::predict`
16866 // has no filter param), but an OBMC neighbour can be a real 16x16+
16867 // block that DID resolve a switchable filter.
16868 interp_fixed: Option<mc::InterpFilterKind>,
16869 switchable_motion_mode: bool,
16870 allow_warped_motion: bool,
16871 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
16872 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
16873 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
16874 // `compound_ctx` local, just handed back instead of applied here (this
16875 // fn's `neighbours` recording happens once for the whole straddling
16876 // 16x16 block, after every leaf).
16877 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
16878 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
16879 // eligible (`bsize >= BLOCK_8X8`).
16880 allow_screen_content_tools: bool,
16881 // lane-inter8 r1: the leaf's mv stacks used to be built without the
16882 // frame's sign-bias table (`NO_SIGN_BIAS`), while [`decode_inter_block`]
16883 // one level up passed it -- it changes the candidate list and with it
16884 // `new_mv_ctx`/`ref_mv_ctx`, `drl_ctx` and the number of symbols read.
16885 // Measured: an 8x8 compound NEAR_NEWMV leaf desynced against aomdec's
16886 // EC_MODE ladder at exactly this block (mi 4,14 of the mandelbrot
16887 // 8x8-split gate).
16888 sign_bias_table: &SignBiasTable,
16889 // lane-inter8 r2: the frame's temporal mv field (spec 7.10.2.8), which
16890 // [`decode_inter_block`] one level up has always passed and this leaf
16891 // passed `None` for -- a `use_ref_frame_mvs` frame's stack then holds
16892 // fewer candidates here than in the reference decoder, which changes the
16893 // mode contexts AND the number of `drl_mode` bits read (class parsed
16894 // then discarded).
16895 tpl_frame: Option<&TplFrameArgs>,
16896 // lane-scaledref r1: this frame's own coded luma width (spec 7.11.3.3),
16897 // for the scaled-reference MC this leaf's own single-ref/compound/OBMC
16898 // predictions take when a stored reference was coded at another width
16899 // (`use_superres`) -- mirrors [`decode_inter_block`]'s own param.
16900 frame_width: usize,
16901) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>, [u8; 2], (i8, Option<i8>))> {
16902 const LAST_FRAME: i8 = 1;
16903 // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back
16904 // so the caller stamps them into `Neighbours` instead of the `[3, 3]`
16905 // placeholder. `[3, 3]` is the "intra neighbour, no filter" sentinel: an
16906 // OBMC blend that picks such a neighbour up feeds it to
16907 // `neighbour_filter`, which PANICS on it (`from_switchable_symbol`) --
16908 // that was the warp gate's crash, not an entropy desync. Stays `[3, 3]`
16909 // on the intra and compound paths.
16910 let mut leaf_filter_syms = [3u8; 2];
16911 // lane-gmaffine r1: this leaf's GLOBALMV vector AND the mv stack's
16912 // missing-candidate fallback both come from the frame's global motion
16913 // evaluated at THIS block's centre (gm r6's root cause).
16914 let gm_table = build_gm_mv_table(
16915 global_motion,
16916 leaf_mi.0,
16917 leaf_mi.1,
16918 2,
16919 2,
16920 allow_high_precision_mv,
16921 force_integer_mv,
16922 );
16923 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
16924 const SIZE_GROUP_8: usize = 1;
16925
16926 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
16927 let (cpx, cpy) = (px / 2, py / 2);
16928 // lane-txselect: whether this leaf's `TxMode::Select` var-tx tree took
16929 // the one split a `BLOCK_8X8` can take (`read_block_tx_size` below) --
16930 // read back by the luma residual read and the tail's neighbour/loop-filter
16931 // bookkeeping. Always `false` outside a `TxMode::Select` inter frame.
16932 let mut split8 = false;
16933 const SIDE: usize = 8;
16934 const CHROMA_SIDE: usize = 4;
16935
16936 let (r, c) = outer_at;
16937 let _ = (r, c);
16938 // lane-inter8 r2: this leaf's OWN mi cell, not the enclosing 16x16's --
16939 // leaf (mi_r, mi_c + 2)'s left neighbour is leaf (mi_r, mi_c), and the
16940 // left column of a 16x16's second leaf ROW is the previous 16x16 block's
16941 // bottom leaf, neither of which a SUB-grid slot can name.
16942 let (rmi, cmi) = leaf_mi;
16943 // lane-inter8 r2: no sibling-leaf override any more -- each leaf stamps
16944 // its own 2x2-mi span into the bands right after it decodes (the caller's
16945 // `record_inter_rect_mi`), so a plain mi read already names the correct
16946 // neighbour, including one belonging to the previous 16x16 block.
16947 let above_skip = neighbours.above_skip[cmi];
16948 let left_skip = neighbours.left_skip[rmi];
16949 let above_inter = neighbours.above_inter[cmi];
16950 let left_inter = neighbours.left_inter[rmi];
16951 let above_ref0 = neighbours.above_ref[cmi];
16952 let above_ref1 = neighbours.above_ref1[cmi];
16953 let left_ref0 = neighbours.left_ref[rmi];
16954 let left_ref1 = neighbours.left_ref1[rmi];
16955 let skip_mode_ctx =
16956 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
16957 // Same two `inter_segment_id` positions as [`decode_inter_block`]; this
16958 // leaf is always `BLOCK_8X8`, i.e. 2x2 mi.
16959 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true);
16960 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
16961 if skip_mode {
16962 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
16963 }
16964
16965 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
16966 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
16967 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false);
16968 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
16969 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
16970 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
16971 maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
16972
16973 let (has_above, has_left) = (
16974 leaf_mi.0 > neighbours.tile_row0_mi,
16975 leaf_mi.1 > neighbours.tile_col0_mi,
16976 );
16977 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
16978 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
16979 // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4,
16980 // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder
16981 // diffs line for line against a real aomdec.
16982 if std::env::var_os("EC_TRACE_MODE").is_some() {
16983 eprintln!(
16984 "EC_MODE mi_row={} mi_col={} rng={}",
16985 leaf_mi.0,
16986 leaf_mi.1,
16987 dec.debug_state().0
16988 );
16989 }
16990
16991 let mode_for_tx;
16992 let (luma_grid, u_grid, v_grid);
16993 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
16994 // lane-inter8 r1: this leaf's own resolved references, handed back so the
16995 // NEXT leaf of the same 16x16 can use them as its real above/left
16996 // neighbour (`Neighbours`' arrays only move once per 16x16 block).
16997 // `(0, None)` is intra.
16998 let mut leaf_refs: (i8, Option<i8>) = (0, None);
16999 if is_inter {
17000 if reference_select || skip_mode {
17001 // lane-inter8 r1: the REAL neighbour references, not a
17002 // `LAST_FRAME`-or-intra stand-in. `av1_get_reference_mode_context`
17003 // and `read_compound_ref_frames`' own contexts both ask whether a
17004 // neighbour is COMPOUND, so pretending every inter neighbour is
17005 // single-ref LAST picked the wrong `comp_mode` CDF row -- measured
17006 // as an 8x8 leaf reading single-ref where aomdec read compound
17007 // NEAR_NEWMV (mi 4,14).
17008 let above_nbr = has_above.then(|| NeighbourRef {
17009 is_inter: above_inter,
17010 ref0: if above_inter { above_ref0 } else { 0 },
17011 ref1: above_ref1,
17012 uni: above_ref1.is_some_and(|r1| is_uni_comp_ref(above_ref0, r1)),
17013 });
17014 let left_nbr = has_left.then(|| NeighbourRef {
17015 is_inter: left_inter,
17016 ref0: if left_inter { left_ref0 } else { 0 },
17017 ref1: left_ref1,
17018 uni: left_ref1.is_some_and(|r1| is_uni_comp_ref(left_ref0, r1)),
17019 });
17020 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
17021 let (ref0, ref1) = if skip_mode {
17022 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
17023 } else {
17024 read_compound_ref_frames(
17025 dec,
17026 cdfs,
17027 above_nbr,
17028 left_nbr,
17029 if has_above && above_inter {
17030 LAST_FRAME
17031 } else {
17032 -1
17033 },
17034 if has_left && left_inter {
17035 LAST_FRAME
17036 } else {
17037 -1
17038 },
17039 )
17040 };
17041 leaf_refs = (ref0, Some(ref1));
17042 let (mi_row, mi_col) = leaf_mi;
17043 // spec 7.10.2.8, mirroring [`decode_inter_block`]'s own
17044 // `comp_tpl` build (`use_ref_frame_mvs` frames only).
17045 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
17046 field: t.field,
17047 cur_offset_0: crate::motion_field::get_relative_dist(
17048 t.order_hint_bits,
17049 t.order_hint,
17050 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
17051 ),
17052 cur_offset_1: crate::motion_field::get_relative_dist(
17053 t.order_hint_bits,
17054 t.order_hint,
17055 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
17056 ),
17057 allow_high_precision_mv,
17058 });
17059 // lane-av1comp: this leaf path has neither a real sign-bias
17060 // table nor `tpl_frame` (see this function's own doc on the
17061 // coarse `LAST_FRAME`-or-intra neighbour approximation
17062 // already in force above), matching the plain `find_mv_stack`
17063 // (no bias, no tpl) the leaf's single-ref arm below already
17064 // uses.
17065 let comp_stack = crate::mvstack::find_mv_stack_compound(
17066 grid,
17067 mi_row,
17068 mi_col,
17069 2,
17070 2,
17071 (ref0, ref1),
17072 mi_cols as usize,
17073 mi_rows as usize,
17074 sign_bias_table,
17075 &gm_table,
17076 comp_tpl,
17077 );
17078 let compound_mode = if skip_mode {
17079 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
17080 } else {
17081 read_inter_compound_mode(
17082 dec,
17083 cdfs,
17084 comp_stack.new_mv_ctx,
17085 comp_stack.ref_mv_ctx,
17086 )
17087 };
17088 if std::env::var_os("EC_TRACE_MODE").is_some() {
17089 eprintln!(
17090 "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}",
17091 leaf_mi.0,
17092 leaf_mi.1,
17093 compound_mode + 17,
17094 comp_stack.entries.len(),
17095 comp_stack.new_mv_ctx,
17096 comp_stack.ref_mv_ctx,
17097 dec.debug_state().0
17098 );
17099 }
17100 let (mv0, mv1) = assign_compound_mv(
17101 dec,
17102 cdfs,
17103 &comp_stack,
17104 compound_mode,
17105 allow_high_precision_mv,
17106 force_integer_mv,
17107 // lane-inter8 r1: the real per-ref gm mvs, same as
17108 // [`decode_inter_block`]'s own compound arm.
17109 (
17110 gm_table[(ref0 - LAST_FRAME) as usize],
17111 gm_table[(ref1 - LAST_FRAME) as usize],
17112 ),
17113 );
17114 // lane-inter8 r3: byte-format-identical to the oracle's
17115 // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder
17116 // diffs line for line against a real aomdec.
17117 if std::env::var_os("EC_TRACE_MODE").is_some() {
17118 eprintln!(
17119 "EC_MODE_VAL mi_row={} mi_col={} mode={} ref0={} ref1={} mv0=({},{}) rng={}",
17120 leaf_mi.0,
17121 leaf_mi.1,
17122 compound_mode + 17,
17123 ref0,
17124 ref1,
17125 mv0.0,
17126 mv0.1,
17127 dec.debug_state().0
17128 );
17129 }
17130
17131 // spec 5.11.25: same gating [`decode_inter_block`]'s own
17132 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
17133 // slot -- the only granularity `Neighbours`' comp_group_idx/
17134 // compound_idx arrays track.
17135 let group_ctx = get_comp_group_idx_context(neighbours, leaf_mi, SIDE);
17136 let comp_group_idx = if !skip_mode
17137 && enable_masked_compound
17138 && is_any_masked_compound_used_here(SIDE)
17139 {
17140 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
17141 } else {
17142 0
17143 };
17144 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
17145 // leaf's own comment.
17146 let mut diffwtd_mask_type: Option<u8> = None;
17147 let mut wedge_mask: Option<&'static [u8]> = None;
17148 if comp_group_idx == 1 {
17149 // lane-maskcomp r1: see the 16x16 leaf's own comment
17150 // above -- SIDE==8 here, `wedge_bsize` index 3
17151 // (BLOCK_8X8, `wedge_types > 0`).
17152 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
17153 if compound_type == 0 {
17154 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
17155 // leaf's own comment.
17156 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
17157 let wedge_sign = dec.literal(1);
17158 WEDGE_HITS.with(|c| c.set(c.get() + 1));
17159 wedge_mask = Some(
17160 crate::wedge::wedge_masks()
17161 .codebook(SIDE)
17162 .mask(wedge_sign as usize, wedge_index as usize),
17163 );
17164 } else {
17165 let mask_type = dec.literal(1);
17166 diffwtd_mask_type = Some(mask_type as u8);
17167 }
17168 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
17169 }
17170 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
17171 // reference-slot defect as the 16x16 leaf's own mask above
17172 // (r1: falsified as an MC/blend math bug, isolated to a DPB
17173 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
17174 // that comment.
17175 // r3: same defect as the 16x16 leaf's own mask above -- see
17176 // that comment (compound_idx's decoded value, not the blend
17177 // math or reference-slot bookkeeping). r6/r7: same re-mask
17178 // as the 16x16 leaf above -- one real bug found and fixed
17179 // (mvstack.rs ref_ctx family), a second, still-unfound
17180 // compound_idx defect surfaces on the wide gate sweep.
17181 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
17182 // see that comment.
17183 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
17184 && !skip_mode
17185 && enable_jnt_comp
17186 {
17187 let idx_ctx = get_comp_index_context(
17188 neighbours,
17189 leaf_mi,
17190 SIDE,
17191 order_hint_bits,
17192 order_hint,
17193 ref_order_hints[(ref0 - LAST_FRAME) as usize],
17194 ref_order_hints[(ref1 - LAST_FRAME) as usize],
17195 );
17196 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
17197 if idx == 1 {
17198 (8, 8, 1u8)
17199 } else {
17200 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
17201 order_hint_bits,
17202 order_hint,
17203 ref_order_hints[(ref0 - LAST_FRAME) as usize],
17204 ref_order_hints[(ref1 - LAST_FRAME) as usize],
17205 );
17206 (fwd, bck, 0u8)
17207 }
17208 } else {
17209 (8, 8, 1u8)
17210 };
17211 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
17212 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
17213 eprintln!(
17214 "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={}",
17215 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
17216 );
17217 }
17218
17219 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
17220 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
17221 let scale0 = mc::scale_factor(py0.width, frame_width);
17222 let scale1 = mc::scale_factor(py1.width, frame_width);
17223 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
17224 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
17225 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
17226 }
17227
17228 for dr in 0..2 {
17229 for dc in 0..2 {
17230 grid.set(
17231 mi_row + dr,
17232 mi_col + dc,
17233 MiInfo {
17234 is_inter: true,
17235 ref_frame: ref0,
17236 ref_frame1: Some(ref1),
17237 mv1: Some(mv1),
17238 mv: mv0,
17239 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
17240 size: 2,
17241 size_h: 2,
17242 is_global_mv0: false,
17243 is_global_mv1: false,
17244 },
17245 );
17246 }
17247 }
17248 mode_for_tx = 0;
17249
17250 // lane-av1comp corner-cut, matching this leaf's single-ref
17251 // arm below (`mc::predict`'s own fixed-Regular default):
17252 // `decode_inter_block8` never resolves a switchable filter,
17253 // so both compound taps use `Regular` too.
17254 use mc::InterpFilterKind::Regular;
17255 let mut inter0_y = vec![0i32; SIDE * SIDE];
17256 mc::predict_compound_intermediate(
17257 &py0.data,
17258 py0.width,
17259 py0.true_width,
17260 py0.true_height,
17261 mv_to_q4(px, mv0.1, true),
17262 mv_to_q4(py, mv0.0, true),
17263 scale0,
17264 SIDE,
17265 SIDE,
17266 Regular,
17267 Regular,
17268 &mut inter0_y,
17269 );
17270 let mut inter1_y = vec![0i32; SIDE * SIDE];
17271 mc::predict_compound_intermediate(
17272 &py1.data,
17273 py1.width,
17274 py1.true_width,
17275 py1.true_height,
17276 mv_to_q4(px, mv1.1, true),
17277 mv_to_q4(py, mv1.0, true),
17278 scale1,
17279 SIDE,
17280 SIDE,
17281 Regular,
17282 Regular,
17283 &mut inter1_y,
17284 );
17285 let mut pred_y = vec![0u16; SIDE * SIDE];
17286 let mut diffwtd_mask_y = Vec::new();
17287 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
17288 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
17289 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
17290 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
17291 Some(diffwtd_mask_y.as_slice())
17292 } else {
17293 wedge_mask
17294 };
17295 if let Some(mask_y) = mask_y {
17296 mc::blend_masked_compound(
17297 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
17298 );
17299 } else {
17300 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
17301 }
17302
17303 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17304 mc::predict_compound_intermediate(
17305 &pu0.data,
17306 pu0.width,
17307 pu0.true_width,
17308 pu0.true_height,
17309 mv_to_q4(cpx, mv0.1, false),
17310 mv_to_q4(cpy, mv0.0, false),
17311 scale0,
17312 CHROMA_SIDE,
17313 CHROMA_SIDE,
17314 Regular,
17315 Regular,
17316 &mut inter0_u,
17317 );
17318 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17319 mc::predict_compound_intermediate(
17320 &pu1.data,
17321 pu1.width,
17322 pu1.true_width,
17323 pu1.true_height,
17324 mv_to_q4(cpx, mv1.1, false),
17325 mv_to_q4(cpy, mv1.0, false),
17326 scale1,
17327 CHROMA_SIDE,
17328 CHROMA_SIDE,
17329 Regular,
17330 Regular,
17331 &mut inter1_u,
17332 );
17333 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
17334 if let Some(mask_y) = mask_y {
17335 mc::blend_masked_compound(
17336 &inter0_u,
17337 &inter1_u,
17338 mask_y,
17339 SIDE,
17340 CHROMA_SIDE,
17341 CHROMA_SIDE,
17342 true,
17343 &mut pred_u,
17344 );
17345 } else {
17346 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
17347 }
17348
17349 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17350 mc::predict_compound_intermediate(
17351 &pv0.data,
17352 pv0.width,
17353 pv0.true_width,
17354 pv0.true_height,
17355 mv_to_q4(cpx, mv0.1, false),
17356 mv_to_q4(cpy, mv0.0, false),
17357 scale0,
17358 CHROMA_SIDE,
17359 CHROMA_SIDE,
17360 Regular,
17361 Regular,
17362 &mut inter0_v,
17363 );
17364 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17365 mc::predict_compound_intermediate(
17366 &pv1.data,
17367 pv1.width,
17368 pv1.true_width,
17369 pv1.true_height,
17370 mv_to_q4(cpx, mv1.1, false),
17371 mv_to_q4(cpy, mv1.0, false),
17372 scale1,
17373 CHROMA_SIDE,
17374 CHROMA_SIDE,
17375 Regular,
17376 Regular,
17377 &mut inter1_v,
17378 );
17379 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
17380 if let Some(mask_y) = mask_y {
17381 mc::blend_masked_compound(
17382 &inter0_v,
17383 &inter1_v,
17384 mask_y,
17385 SIDE,
17386 CHROMA_SIDE,
17387 CHROMA_SIDE,
17388 true,
17389 &mut pred_v,
17390 );
17391 } else {
17392 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
17393 }
17394
17395 split8 = read_block_tx_size(
17396 dec,
17397 cdfs,
17398 neighbours,
17399 leaf_mi,
17400 SIDE,
17401 (mi_cols as usize, mi_rows as usize),
17402 true,
17403 skip,
17404 )?
17405 .1
17406 .is_some();
17407 if skip {
17408 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
17409 u.reconstruct_mc(
17410 cpx,
17411 cpy,
17412 CHROMA_SIDE,
17413 &pred_u,
17414 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17415 );
17416 v.reconstruct_mc(
17417 cpx,
17418 cpy,
17419 CHROMA_SIDE,
17420 &pred_v,
17421 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17422 );
17423 luma_grid = vec![0i32; SIDE * SIDE];
17424 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17425 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17426 } else {
17427 let around = neighbours.around_mi(leaf_mi, 8);
17428 let (grid8, luma_tx_type) = read_inter_luma8(
17429 dec,
17430 cdfs,
17431 neighbours,
17432 leaf_mi,
17433 y,
17434 px,
17435 py,
17436 &pred_y,
17437 mode_for_tx,
17438 base_q_idx,
17439 scan8,
17440 scan4,
17441 reduced_tx_set,
17442 split8,
17443 )?;
17444 luma_grid = grid8;
17445 u_grid = read_inter_plane(
17446 dec,
17447 cdfs,
17448 TxbSet::Chroma4,
17449 scan4,
17450 1,
17451 around[1],
17452 mode_for_tx,
17453 u,
17454 cpx,
17455 cpy,
17456 CHROMA_SIDE,
17457 base_q_idx,
17458 &pred_u,
17459 Some(luma_tx_type),
17460 None,
17461 )?
17462 .0;
17463 v_grid = read_inter_plane(
17464 dec,
17465 cdfs,
17466 TxbSet::Chroma4,
17467 scan4,
17468 2,
17469 around[2],
17470 mode_for_tx,
17471 v,
17472 cpx,
17473 cpy,
17474 CHROMA_SIDE,
17475 base_q_idx,
17476 &pred_v,
17477 Some(luma_tx_type),
17478 None,
17479 )?
17480 .0;
17481 }
17482 // lane-inter8 r2: the COMPOUND leaf used to return here
17483 // WITHOUT the end-of-function `record_mi`/`fill_lf_grid` the
17484 // single-ref path falls through to -- so a compound 8x8 leaf
17485 // left `above_side_mi`/`left_side_mi` (the next block's
17486 // partition context), the per-plane coefficient level state
17487 // and the loop-filter grid describing whatever block was
17488 // there before. Every leaf of the gate's stream is compound,
17489 // so the 16x16 below a split block read partition ctx 0
17490 // instead of 1 and mis-read PARTITION_SPLIT as NONE.
17491 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
17492 neighbours.fill_lf_grid(
17493 leaf_mi,
17494 2,
17495 8,
17496 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
17497 );
17498 return Ok((
17499 skip,
17500 is_inter,
17501 skip_mode,
17502 compound_ctx8,
17503 leaf_filter_syms,
17504 leaf_refs,
17505 ));
17506 }
17507 }
17508 // lane-gmaffine r1: the leaf reads the FULL `single_ref` tree
17509 // ([`read_single_ref`], the same one the 16x16+ leaf uses, with the
17510 // real per-neighbour p1..p6 contexts) instead of the old three-symbol
17511 // LAST-only probe plus a refusal -- aomenc picks GOLDEN/ALTREF for
17512 // 8x8 leaves constantly, so that refusal was what every 8x8 gate
17513 // actually stopped at.
17514 let ref_frame = read_single_ref(
17515 dec,
17516 cdfs,
17517 neighbours.above_ref[cmi],
17518 neighbours.above_ref1[cmi],
17519 neighbours.left_ref[rmi],
17520 neighbours.left_ref1[rmi],
17521 );
17522 leaf_refs = (ref_frame, None);
17523 let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
17524
17525 let (mi_row, mi_col) = leaf_mi;
17526 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS
17527 // leaf's own reference (lane-gmaffine r1 taught it non-LAST refs).
17528 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
17529 field: t.field,
17530 cur_offset_0: crate::motion_field::get_relative_dist(
17531 t.order_hint_bits,
17532 t.order_hint,
17533 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
17534 ),
17535 allow_high_precision_mv,
17536 });
17537 let stack = crate::mvstack::find_mv_stack_with_sign_bias(
17538 grid,
17539 mi_row,
17540 mi_col,
17541 2,
17542 2,
17543 ref_frame,
17544 mi_cols as usize,
17545 mi_rows as usize,
17546 sign_bias_table,
17547 &gm_table,
17548 tpl,
17549 );
17550
17551 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
17552 let mut is_globalmv = false;
17553 let (mv, is_new_mv) = if !not_new {
17554 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
17555 // read at most two `drl_mode` bits, one per stack entry past the
17556 // first, stopping at the first `0`. The chosen index selects
17557 // which stack entry `read_mv`'s base predictor comes from
17558 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
17559 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
17560 let mut idx = 0usize;
17561 while idx < 2 && stack.entries.len() > idx + 1 {
17562 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
17563 break;
17564 }
17565 idx += 1;
17566 }
17567 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
17568 (
17569 read_mv(
17570 dec,
17571 &mut cdfs.mv_comp,
17572 &mut cdfs.mv_joint,
17573 base_mv,
17574 allow_high_precision_mv,
17575 force_integer_mv,
17576 ),
17577 true,
17578 )
17579 } else {
17580 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
17581 is_globalmv = !not_zero;
17582 let mv = if !not_zero {
17583 // lane-gmaffine r1: GLOBALMV (spec 7.10.2.1) -- the same
17584 // `gm_get_motion_vector` value the 16x16+ leaf reads out of
17585 // its own `gm_table`, computed at this block's centre.
17586 GLOBALMV_HITS_8.with(|c| c.set(c.get() + 1));
17587 gm_table[(ref_frame - LAST_FRAME) as usize]
17588 } else {
17589 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
17590 if nearest {
17591 stack.nearest_mv
17592 } else {
17593 let mut idx = 1usize;
17594 while idx < 3 && stack.entries.len() > idx + 1 {
17595 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
17596 break;
17597 }
17598 idx += 1;
17599 }
17600 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
17601 }
17602 };
17603 (mv, false)
17604 };
17605 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
17606 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
17607 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
17608 // (compound already returned above), GLOBALMV already refused
17609 // (round 3), so the only real gate left is the header enable bit.
17610 let mut interintra_mode: Option<u8> = None;
17611 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
17612 if enable_interintra_compound && !skip_mode {
17613 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
17614 if interintra {
17615 // lane-interintra r1: same read pair as the 16/32 site;
17616 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
17617 // alone, never the `enable_interintra_wedge` seq bit.
17618 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
17619 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
17620 if wedge {
17621 // lane-wii r2: same adapting `wedge_index` symbol as the
17622 // 16/32 leaf, fixed sign 0 -- see that site's comment.
17623 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
17624 WII_HITS.with(|c| c.set(c.get() + 1));
17625 wedge_mask = Some((
17626 crate::wedge::wedge_masks()
17627 .codebook(SIDE)
17628 .mask(0, wedge_index as usize),
17629 SIDE,
17630 ));
17631 } else {
17632 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
17633 }
17634 interintra_mode = Some(ii);
17635 }
17636 }
17637 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
17638 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
17639 // is the spec's own minimum eligible size, single-ref-only branch,
17640 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
17641 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
17642 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
17643 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
17644 // lane-gmaffine r1: the two libaom predicates, exactly as the
17645 // 16x16+ leaf resolves them (see [`decode_inter_block`]'s own doc):
17646 // `is_global_mv_block` (mode GLOBAL*, model > TRANSLATION, block
17647 // >= 8x8 -- BLOCK_8X8 IS the 8px minimum, so the size predicate is
17648 // always true here) suppresses the motion_mode read entirely and
17649 // turns on the global warp below.
17650 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
17651 let is_global_mv_block = is_globalmv && gm_ref.model as u8 > 1;
17652 let motion_mode_eligible = switchable_motion_mode
17653 && !skip_mode
17654 && interintra_mode.is_none()
17655 && !(is_global_mv_block && !force_integer_mv)
17656 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
17657 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
17658 let mut warp_params: Option<crate::warp::WarpParams> = None;
17659 let mut warped_selected = false;
17660 let mut obmc_selected = false;
17661 if motion_mode_eligible {
17662 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
17663 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
17664 // (grid.set below hardcodes it).
17665 // lane-scaledref r2 sibling of the 16x16+ leaf's fix: libaom
17666 // drops WARPED_CAUSAL eligibility (so this reads `obmc_cdf`)
17667 // when the reference is scaled. Not gated here because an 8x8
17668 // leaf under a scaled reference is refused before this function
17669 // runs (see the block8 refusal below, ~12500) -- whoever lifts
17670 // that refusal must add `&& !ref_is_scaled` here too.
17671 // lane-fimv r1: libaom `motion_mode_allowed` also requires
17672 // `!xd->cur_frame_force_integer_mv`, so a screen-content frame
17673 // that set `force_integer_mv` reads the 2-symbol `obmc_cdf` here
17674 // (class wrong-alphabet-same-value).
17675 let proj_ok =
17676 num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
17677 let warp_eligible = allow_warped_motion && !force_integer_mv && proj_ok;
17678 if allow_warped_motion && proj_ok && force_integer_mv {
17679 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
17680 }
17681 if warp_eligible {
17682 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
17683 match mode {
17684 0 => {}
17685 1 => {
17686 obmc_selected = true;
17687 OBMC_HITS.with(|c| c.set(c.get() + 1));
17688 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
17689 }
17690 _ => {
17691 // lane-gmaffine r1: WARPED_CAUSAL at the 8x8 leaf --
17692 // the same findSamples -> select_samples ->
17693 // av1_find_projection chain the 16x16+ leaf runs,
17694 // with BLOCK_8X8's own 8x8 model centre; an
17695 // unusable projection falls back to the block's
17696 // translational mv (libaom `av1_find_projection`
17697 // returning 1 leaves `wm_params` invalid and
17698 // `build_inter_predictors` skips the warp).
17699 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
17700 let mut samples = find_samples(
17701 grid,
17702 mi_row,
17703 mi_col,
17704 2,
17705 2,
17706 mi_cols as usize,
17707 mi_rows as usize,
17708 ref_frame,
17709 );
17710 if samples.len() > 1 {
17711 crate::warp::select_samples(mv, &mut samples, SIDE as i32, SIDE as i32);
17712 }
17713 warp_params = crate::warp::find_projection(
17714 &samples,
17715 SIDE as i32,
17716 SIDE as i32,
17717 mv.1,
17718 mv.0,
17719 mi_row as i32,
17720 mi_col as i32,
17721 );
17722 warped_selected = true;
17723 if warp_params.is_some() {
17724 WARP_HITS_8.with(|c| c.set(c.get() + 1));
17725 }
17726 }
17727 }
17728 } else {
17729 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
17730 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
17731 if obmc_selected {
17732 OBMC_HITS.with(|c| c.set(c.get() + 1));
17733 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
17734 }
17735 }
17736 }
17737 // lane-gmaffine r1: `read_mb_interp_filter` (spec 5.11.26) at the 8x8
17738 // leaf, in libaom's own order (interintra, motion_mode, THEN the
17739 // filter). Until this round the leaf read no filter symbol at all and
17740 // predicted Regular unconditionally -- correct only for a frame with a
17741 // fixed `interp_filter`, and a silent entropy DESYNC for every
17742 // SWITCHABLE-filter stream that reaches an 8x8 leaf (which is what
17743 // made the interior-split wiring above unusable at first).
17744 // corner-cut: the neighbour filter context is the enclosing 16x16
17745 // block's own coarse `above_filter`/`left_filter` entry (this leaf
17746 // path keeps no per-leaf neighbour array), so all four siblings read
17747 // the same context row. Ceiling: a stream whose 8x8 siblings pick
17748 // DIFFERENT filters decodes the second..fourth leaf's symbol from the
17749 // wrong CDF row. Upgrade: give `Neighbours` a real 8x8-granular
17750 // filter array, same shape as the `[3, 3]` approximation the caller
17751 // records after the leaf loop.
17752 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
17753 || neighbours.above_ref1[cmi] == Some(ref_frame)
17754 {
17755 neighbours.above_filter[cmi]
17756 } else {
17757 [3, 3]
17758 };
17759 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
17760 || neighbours.left_ref1[rmi] == Some(ref_frame)
17761 {
17762 neighbours.left_filter[rmi]
17763 } else {
17764 [3, 3]
17765 };
17766 let gm_nontrans =
17767 is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation;
17768 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
17769 dec,
17770 cdfs,
17771 interp_fixed,
17772 enable_dual_filter,
17773 gm_nontrans || warped_selected || skip_mode,
17774 above_filter_ctx,
17775 left_filter_ctx,
17776 false,
17777 );
17778 leaf_filter_syms = resolved_filter;
17779 if std::env::var_os("EC_TRACE_MODE").is_some() {
17780 eprintln!(
17781 "EC_MODE_VAL8 mi_row={} mi_col={} newmv={is_new_mv} globalmv={is_globalmv} ref0={ref_frame} mv0=({},{}) stack={} rng={}",
17782 leaf_mi.0,
17783 leaf_mi.1,
17784 mv.0,
17785 mv.1,
17786 stack.entries.len(),
17787 dec.debug_state().0
17788 );
17789 }
17790 // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch
17791 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
17792 // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model
17793 // wins (`is_none()` guard); BLOCK_8X8 already satisfies the >=8px
17794 // size predicate baked into `is_global_mv_block`.
17795 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
17796 warp_params = crate::warp::global_warp_params(gm_ref.params);
17797 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
17798 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
17799 }
17800 }
17801 if std::env::var_os("EC_TRACE_MODE").is_some() {
17802 eprintln!(
17803 "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}",
17804 leaf_mi.0,
17805 leaf_mi.1,
17806 warp_params.is_some(),
17807 );
17808 }
17809 for dr in 0..2 {
17810 for dc in 0..2 {
17811 grid.set(
17812 mi_row + dr,
17813 mi_col + dc,
17814 MiInfo {
17815 is_inter: true,
17816 ref_frame,
17817 // INTRA_FRAME marker for interintra blocks -- keeps
17818 // them out of warp-sample gathering (see 16/32 site).
17819 ref_frame1: interintra_mode.map(|_| 0),
17820 mv1: None,
17821 mv,
17822 is_new_mv,
17823 size: 2,
17824 size_h: 2,
17825 is_global_mv0: is_global_mv_block,
17826 is_global_mv1: false,
17827 },
17828 );
17829 }
17830 }
17831 mode_for_tx = 0;
17832
17833 // lane-scaledref r1: this leaf's own prediction is always `Regular`
17834 // (documented corner-cut above); under a scaled reference the same
17835 // fixed kernel runs through spec 7.11.3.3's scaled walk instead.
17836 let luma_scale = mc::scale_factor(sref_y.width, frame_width);
17837 if luma_scale != mc::REF_NO_SCALE {
17838 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
17839 }
17840 let mut pred_y = vec![0u16; SIDE * SIDE];
17841 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
17842 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
17843 // Merge of lane-gmaffine (this leaf's own switchable filters) with
17844 // lane-scaledref (spec 7.11.3.3's scaled walk): same kernels either
17845 // way, only the sample walk differs.
17846 for (plane, x, y, dim, dst) in [
17847 (sref_y, px, py, SIDE, &mut pred_y),
17848 (sref_u, cpx, cpy, CHROMA_SIDE, &mut pred_u),
17849 (sref_v, cpx, cpy, CHROMA_SIDE, &mut pred_v),
17850 ] {
17851 let luma = std::ptr::eq(plane, sref_y);
17852 if luma_scale == mc::REF_NO_SCALE {
17853 mc::predict_with_filters(
17854 &plane.data,
17855 plane.width,
17856 plane.true_width,
17857 plane.true_height,
17858 mv_to_q4(x, mv.1, luma),
17859 mv_to_q4(y, mv.0, luma),
17860 dim,
17861 dim,
17862 h_filter,
17863 v_filter,
17864 dst,
17865 );
17866 } else {
17867 mc::predict_scaled(
17868 &plane.data,
17869 plane.width,
17870 plane.true_width,
17871 plane.true_height,
17872 mv_to_q4(x, mv.1, luma),
17873 mv_to_q4(y, mv.0, luma),
17874 luma_scale,
17875 dim,
17876 dim,
17877 h_filter,
17878 v_filter,
17879 dst,
17880 );
17881 }
17882 }
17883
17884 // lane-gmaffine r1: the warp filter REPLACES the translational
17885 // prediction just built (libaom builds one or the other), same as
17886 // the 16x16+ leaf's own call trio.
17887 if let Some(params) = &warp_params {
17888 crate::warp::warp_affine(
17889 params, &sref_y.data, sref_y.true_width as i32, sref_y.true_height as i32,
17890 sref_y.width as i32, &mut pred_y, px as i32, py as i32, SIDE as i32,
17891 SIDE as i32, SIDE as i32, 0, 0,
17892 );
17893 // `av1_init_warp_params`'s per-plane `block_width/height < 8`
17894 // bail-out: an 8x8 leaf's chroma plane is 4x4 in 420, so it is
17895 // predicted translationally even when the luma warps.
17896 #[allow(clippy::absurd_extreme_comparisons)]
17897 if CHROMA_SIDE >= 8 {
17898 crate::warp::warp_affine(
17899 params, &sref_u.data, sref_u.true_width as i32, sref_u.true_height as i32,
17900 sref_u.width as i32, &mut pred_u, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
17901 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
17902 );
17903 crate::warp::warp_affine(
17904 params, &sref_v.data, sref_v.true_width as i32, sref_v.true_height as i32,
17905 sref_v.width as i32, &mut pred_v, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
17906 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
17907 );
17908 }
17909 }
17910
17911 if obmc_selected {
17912 obmc_blend(
17913 grid,
17914 neighbours,
17915 mi_row,
17916 mi_col,
17917 2,
17918 2,
17919 mi_rows as usize,
17920 mi_cols as usize,
17921 SIDE,
17922 SIDE,
17923 SIDE,
17924 CHROMA_SIDE,
17925 px,
17926 py,
17927 cpx,
17928 cpy,
17929 ref_y,
17930 ref_u,
17931 ref_v,
17932 other_refs,
17933 interp_fixed,
17934 frame_width,
17935 &mut pred_y,
17936 &mut pred_u,
17937 &mut pred_v,
17938 )?;
17939 }
17940
17941 // Non-wedge interintra blend, mutually exclusive with OBMC (the
17942 // motion_mode symbol is not read for an interintra block).
17943 if let Some(ii) = interintra_mode {
17944 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
17945 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
17946 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
17947 }
17948
17949 split8 = read_block_tx_size(
17950 dec,
17951 cdfs,
17952 neighbours,
17953 leaf_mi,
17954 SIDE,
17955 (mi_cols as usize, mi_rows as usize),
17956 true,
17957 skip,
17958 )?
17959 .1
17960 .is_some();
17961 if skip {
17962 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
17963 u.reconstruct_mc(
17964 cpx,
17965 cpy,
17966 CHROMA_SIDE,
17967 &pred_u,
17968 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17969 );
17970 v.reconstruct_mc(
17971 cpx,
17972 cpy,
17973 CHROMA_SIDE,
17974 &pred_v,
17975 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17976 );
17977 luma_grid = vec![0i32; SIDE * SIDE];
17978 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17979 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17980 } else {
17981 let around = neighbours.around_mi(leaf_mi, 8);
17982 let (grid8, luma_tx_type) = read_inter_luma8(
17983 dec,
17984 cdfs,
17985 neighbours,
17986 leaf_mi,
17987 y,
17988 px,
17989 py,
17990 &pred_y,
17991 mode_for_tx,
17992 base_q_idx,
17993 scan8,
17994 scan4,
17995 reduced_tx_set,
17996 split8,
17997 )?;
17998 luma_grid = grid8;
17999 u_grid = read_inter_plane(
18000 dec,
18001 cdfs,
18002 TxbSet::Chroma4,
18003 scan4,
18004 1,
18005 around[1],
18006 mode_for_tx,
18007 u,
18008 cpx,
18009 cpy,
18010 CHROMA_SIDE,
18011 base_q_idx,
18012 &pred_u,
18013 Some(luma_tx_type),
18014 None,
18015 )?
18016 .0;
18017 v_grid = read_inter_plane(
18018 dec,
18019 cdfs,
18020 TxbSet::Chroma4,
18021 scan4,
18022 2,
18023 around[2],
18024 mode_for_tx,
18025 v,
18026 cpx,
18027 cpy,
18028 CHROMA_SIDE,
18029 base_q_idx,
18030 &pred_v,
18031 Some(luma_tx_type),
18032 None,
18033 )?
18034 .0;
18035 }
18036 } else {
18037 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
18038 if mode >= 13 {
18039 return Err(unsupported(
18040 "an intra mode this decoder does not code (round 2)",
18041 ));
18042 }
18043 if (V_PRED..=D67_PRED).contains(&mode) {
18044 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
18045 if angle != ANGLE_DELTA_ZERO {
18046 return Err(unsupported(
18047 "a nonzero angle delta (this encoder never writes one)",
18048 ));
18049 }
18050 }
18051 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
18052 if uv_mode != DC_PRED {
18053 return Err(unsupported(
18054 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
18055 ));
18056 }
18057 // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/
18058 // `uv_mode` are both effectively `DC_PRED`-gated already on this
18059 // leaf (a nonzero `mode` still passes, but `uv_mode` is forced
18060 // `DC_PRED` by the refusal just above), same order as libaom's
18061 // `read_palette_mode_info` call right after `xd->cfl.store_y`.
18062 if allow_screen_content_tools {
18063 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[0][0]) != 0 {
18064 return Err(unsupported(
18065 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
18066 ));
18067 }
18068 if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
18069 return Err(unsupported(
18070 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
18071 ));
18072 }
18073 }
18074 // lane-fiinter r1: `read_filter_intra_mode_info` (libaom `decodemv.c`,
18075 // the tail of `read_intra_block_mode_info`) -- an intra block inside
18076 // an INTER frame reads `use_filter_intra` in exactly the same place a
18077 // key-frame block does, right after the palette syntax. Nothing read
18078 // it here before this round, and aomenc enables filter intra by
18079 // default, so every inter frame carrying one desynced at this symbol.
18080 // `av1_filter_intra_allowed`'s `palette_size[0] == 0` term is implied:
18081 // a real palette-Y block already returned above.
18082 let mut filter_intra = None;
18083 if mode == DC_PRED
18084 && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
18085 && let Some(class) = filter_intra_size_class(SIDE)
18086 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
18087 {
18088 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
18089 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
18090 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
18091 }
18092 mode_for_tx = mode;
18093 let (mi_row, mi_col) = leaf_mi;
18094 for dr in 0..2 {
18095 for dc in 0..2 {
18096 grid.set(
18097 mi_row + dr,
18098 mi_col + dc,
18099 MiInfo {
18100 is_inter: false,
18101 ref_frame: -1,
18102 ref_frame1: None,
18103 mv1: None,
18104 mv: (0, 0),
18105 is_new_mv: false,
18106 size: 2,
18107 size_h: 2,
18108 is_global_mv0: false,
18109 is_global_mv1: false,
18110 },
18111 );
18112 }
18113 }
18114
18115 // lane-intrainter r1: the 8x8 leaf's own intra `tx_depth` can only
18116 // resolve to TX_4X4, whose 2x2 unit grid this leaf path has no
18117 // prediction loop for (the >=16x16 square path above does). Refuse by
18118 // name rather than mis-reconstruct.
18119 if read_block_tx_size(
18120 dec,
18121 cdfs,
18122 neighbours,
18123 leaf_mi,
18124 SIDE,
18125 (mi_cols as usize, mi_rows as usize),
18126 false,
18127 skip,
18128 )?
18129 .1
18130 .is_some()
18131 {
18132 return Err(unsupported(
18133 "an 8x8 intra leaf in an inter frame whose tx_depth splits it into 4x4 \
18134 transform units",
18135 ));
18136 }
18137 let reach = Reach::of(SIDE, px, py, y.width, y.height);
18138 if skip {
18139 y.reconstruct(
18140 px,
18141 py,
18142 SIDE,
18143 mode,
18144 0,
18145 reach,
18146 &vec![0i32; SIDE * SIDE],
18147 None,
18148 filter_intra,
18149 false,
18150 );
18151 u.reconstruct(
18152 cpx,
18153 cpy,
18154 CHROMA_SIDE,
18155 DC_PRED,
18156 0,
18157 reach,
18158 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
18159 None,
18160 None,
18161 false,
18162 );
18163 v.reconstruct(
18164 cpx,
18165 cpy,
18166 CHROMA_SIDE,
18167 DC_PRED,
18168 0,
18169 reach,
18170 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
18171 None,
18172 None,
18173 false,
18174 );
18175 luma_grid = vec![0i32; SIDE * SIDE];
18176 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
18177 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
18178 } else {
18179 let around = neighbours.around_mi(leaf_mi, 8);
18180 luma_grid = read_plane(
18181 dec,
18182 cdfs,
18183 TxbSet::Luma8,
18184 scan8,
18185 0,
18186 around[0],
18187 mode,
18188 mode,
18189 0,
18190 reach,
18191 y,
18192 px,
18193 py,
18194 SIDE,
18195 TX8,
18196 base_q_idx,
18197 None,
18198 filter_intra,
18199 None,
18200 false,
18201 )?;
18202 u_grid = read_plane(
18203 dec,
18204 cdfs,
18205 TxbSet::Chroma4,
18206 scan4,
18207 1,
18208 around[1],
18209 mode,
18210 DC_PRED,
18211 0,
18212 reach,
18213 u,
18214 cpx,
18215 cpy,
18216 CHROMA_SIDE,
18217 TX4,
18218 base_q_idx,
18219 None,
18220 None,
18221 None,
18222 false,
18223 )?;
18224 v_grid = read_plane(
18225 dec,
18226 cdfs,
18227 TxbSet::Chroma4,
18228 scan4,
18229 2,
18230 around[2],
18231 mode,
18232 DC_PRED,
18233 0,
18234 reach,
18235 v,
18236 cpx,
18237 cpy,
18238 CHROMA_SIDE,
18239 TX4,
18240 base_q_idx,
18241 None,
18242 None,
18243 None,
18244 false,
18245 )?;
18246 }
18247 }
18248 // lane-txselect: a split leaf's plane-0 neighbour context is per 4x4
18249 // transform unit (written by `record_mi_luma` inside `read_inter_luma8`),
18250 // but `record_mi` rewrites all three planes of these cells at once -- so
18251 // save plane 0 across it, exactly as `record_split_luma` leaves plane 0
18252 // alone at the bigger block sizes.
18253 let saved_luma_ctx = split8.then(|| {
18254 (
18255 [
18256 neighbours.left[leaf_mi.0][0],
18257 neighbours.left[leaf_mi.0 + 1][0],
18258 ],
18259 [
18260 neighbours.above[leaf_mi.1][0],
18261 neighbours.above[leaf_mi.1 + 1][0],
18262 ],
18263 )
18264 });
18265 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
18266 if let Some((left, above)) = saved_luma_ctx {
18267 for (cell, state) in left.into_iter().enumerate() {
18268 neighbours.left[leaf_mi.0 + cell][0] = state;
18269 }
18270 for (cell, state) in above.into_iter().enumerate() {
18271 neighbours.above[leaf_mi.1 + cell][0] = state;
18272 }
18273 }
18274 // lane-gmaffine r2: the deblock grid's ref id is the leaf's OWN reference
18275 // (r1 taught this leaf non-LAST refs; the hardcoded LAST_FRAME made every
18276 // GOLDEN/ALTREF leaf read as LAST at the loop-filter's ref/mv edge test).
18277 neighbours.fill_lf_grid(
18278 leaf_mi,
18279 2,
18280 if split8 { 4 } else { 8 },
18281 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
18282 );
18283 Ok((
18284 skip,
18285 is_inter,
18286 skip_mode,
18287 compound_ctx8,
18288 leaf_filter_syms,
18289 leaf_refs,
18290 ))
18291}
18292
18293/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
18294/// against `reference` (the previous frame's own decoded picture, at this
18295/// frame's true size -- a decoder's single-slot DPB, matching what this
18296/// crate's encoder always predicts from), returning the picture it
18297/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
18298/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
18299/// `frame_width`/`frame_height` its true render size).
18300///
18301/// # Errors
18302/// Returns an error under the same conditions [`decode_inter_block`] does,
18303/// or when `reference` is not this frame's own true size, or when the tile
18304/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
18305/// refusal [`crate::tile`]'s writer gives its encoder).
18306pub fn decode_inter_frame_tile(
18307 data: &[u8],
18308 mi_cols: u32,
18309 mi_rows: u32,
18310 base_q_idx: u8,
18311 frame_width: u32,
18312 frame_height: u32,
18313 reference: &Picture,
18314 other_refs: [Option<&Picture>; 8],
18315 cdef: &CdefParams,
18316 loop_filter: &LoopFilterParams,
18317 allow_high_precision_mv: bool,
18318 force_integer_mv: bool,
18319 interp_fixed: Option<mc::InterpFilterKind>,
18320 enable_dual_filter: bool,
18321 reference_select: bool,
18322) -> Result<Picture> {
18323 let single_tile = TileInfo {
18324 mi_col_starts: vec![0, mi_cols],
18325 mi_row_starts: vec![0, mi_rows],
18326 ..TileInfo::default()
18327 };
18328 decode_inter_frame_tile_with_cdfs(
18329 &[data],
18330 &single_tile,
18331 mi_cols,
18332 mi_rows,
18333 base_q_idx,
18334 crate::quant::QuantDeltas::default(),
18335 frame_width,
18336 frame_height,
18337 reference,
18338 other_refs,
18339 cdef,
18340 loop_filter,
18341 &LoopRestorationParams::default(),
18342 None,
18343 allow_high_precision_mv,
18344 force_integer_mv,
18345 NO_SIGN_BIAS,
18346 [ec_av1_syntax::WarpParams::default(); 7],
18347 interp_fixed,
18348 enable_dual_filter,
18349 0,
18350 0,
18351 [0; 7],
18352 None,
18353 reference_select,
18354 false,
18355 false,
18356 false,
18357 false,
18358 [0; 2],
18359 true,
18360 // `tx_select`: this raw entry point decodes this crate's own encoder's
18361 // streams, which always write `TxMode::Largest`.
18362 false,
18363 false,
18364 false,
18365 false,
18366 DeltaParams::default(),
18367 // `enable_filter_intra`: this crate's own encoder never writes the
18368 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream
18369 // reaching this entry point reads a `use_filter_intra` symbol.
18370 false,
18371 )
18372 .map(|(picture, _, _)| picture)
18373}
18374
18375/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
18376/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
18377/// end-of-tile table. An inter frame's own header can name
18378/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
18379/// so `None` is a real case here, not only a convenience default.
18380pub(crate) fn decode_inter_frame_tile_with_cdfs(
18381 tiles: &[&[u8]],
18382 tile_info: &TileInfo,
18383 mi_cols: u32,
18384 mi_rows: u32,
18385 base_q_idx: u8,
18386 // lane-sbpart r11: see [`decode_key_frame_tile_with_cdfs`]'s own `deltas`.
18387 deltas: crate::quant::QuantDeltas,
18388 frame_width: u32,
18389 frame_height: u32,
18390 reference: &Picture,
18391 other_refs: [Option<&Picture>; 8],
18392 cdef: &CdefParams,
18393 loop_filter: &LoopFilterParams,
18394 lr: &LoopRestorationParams,
18395 initial_cdfs: Option<Cdfs>,
18396 allow_high_precision_mv: bool,
18397 force_integer_mv: bool,
18398 sign_bias_table: SignBiasTable,
18399 // lane-gm r2: this frame header's own `global_motion` table (spec
18400 // 5.9.24), threaded to every `decode_inter_block` call below.
18401 global_motion: [ec_av1_syntax::WarpParams; 7],
18402 interp_fixed: Option<mc::InterpFilterKind>,
18403 enable_dual_filter: bool,
18404 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
18405 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
18406 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
18407 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
18408 // and the caller ([`crate::stream::decode_stream`]) projected one.
18409 order_hint_bits: u32,
18410 order_hint: u32,
18411 ref_order_hints: [u32; 7],
18412 tpl_field: Option<&crate::motion_field::TplField>,
18413 // lane-av1comp: this frame header's own `reference_select` bit, threaded
18414 // to every `decode_inter_block`/`decode_inter_block8` call below.
18415 reference_select: bool,
18416 // lane-av1comp: `seq_params`' own compound-blend enable bits.
18417 enable_masked_compound: bool,
18418 enable_jnt_comp: bool,
18419 // lane-sb128 r3: this sequence header's own `enable_interintra_compound`
18420 // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call
18421 // below (spec 5.11.24's `interintra` read).
18422 enable_interintra_compound: bool,
18423 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
18424 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
18425 // `decode_inter_block8` call below.
18426 skip_mode_present: bool,
18427 skip_mode_frame: [u8; 2],
18428 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to
18429 // every inter `tx_type` read below (`false` needs the 12-/16-symbol
18430 // `Set1` coefficient tables at 16x16/8x8 rather than the reduced
18431 // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]).
18432 reduced_tx_set: bool,
18433 // lane-txselect: this frame header's own `tx_mode == TxMode::Select`
18434 // bit (spec 5.9.14). Together with `reduced_tx_set` it is stashed in a
18435 // thread-local by [`set_inter_tx_mode`] rather than threaded through
18436 // `decode_inter_block`'s forty parameters -- both are frame-constant, and
18437 // only [`read_block_tx_size`]/the var-tx residual loop read them.
18438 tx_select: bool,
18439 // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/
18440 // `allow_warped_motion` bits, threaded to every `decode_inter_block`/
18441 // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`).
18442 switchable_motion_mode: bool,
18443 allow_warped_motion: bool,
18444 // lane-screen r2: this frame header's own `allow_screen_content_tools`
18445 // bit, threaded to every `decode_inter_block`/`decode_inter_block8`
18446 // call below -- consumes (never reconstructs) the intra-sub-block
18447 // palette syntax libaom's `read_intra_block_mode_info` reads under the
18448 // same `av1_allow_palette` gate as the key-frame path.
18449 allow_screen_content_tools: bool,
18450 // lane-realworld r5: this frame header's own `delta` (spec 5.9.17/5.9.18),
18451 // same contract as [`decode_key_frame_tile_with_cdfs`]'s own `delta`
18452 // param -- only `q_present`/`q_res` are read.
18453 delta: DeltaParams,
18454 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit
18455 // (spec 5.5.2), stashed in a thread-local with `tx_select` rather than
18456 // threaded through `decode_inter_block`'s fifty parameters -- read by the
18457 // intra-in-inter arms' `read_filter_intra_mode_info`.
18458 enable_filter_intra: bool,
18459) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
18460 set_inter_tx_mode(tx_select, reduced_tx_set, enable_filter_intra);
18461 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
18462 field,
18463 order_hint_bits,
18464 order_hint,
18465 ref_order_hints,
18466 });
18467 if mi_cols == 0 || mi_rows == 0 {
18468 return Err(unsupported("a frame with no mode-info grid"));
18469 }
18470 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
18471 // lane-superres r10: a width mismatch alone is no longer refused here --
18472 // `mc::predict_scaled` (spec 7.11.3.3, threaded through
18473 // `decode_inter_block`'s single-ref branch) exists precisely for a
18474 // `use_superres` reference at a different width than this frame's own
18475 // true size. Height must still match: AV1 superres never scales height
18476 // (r8's derivation, `mc.rs`'s own doc), and nothing in this decode path
18477 // has a vertical scaling pass.
18478 if reference.height != true_height {
18479 return Err(unsupported(
18480 "a reference picture whose height does not match this frame's own true size",
18481 ));
18482 }
18483 let (cols, rows) = block_grid(mi_cols, mi_rows);
18484 let sb128 = sb128();
18485 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
18486 CDEF_BITS.with(|c| c.set(cdef.bits));
18487 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
18488 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
18489 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
18490
18491 let ref_y = PlaneBuf {
18492 data: reference.y.iter().map(|&s| s as u16).collect(),
18493 width: reference.width,
18494 height: reference.height,
18495 true_width: reference.width,
18496 true_height: reference.height,
18497 tile_x0: 0,
18498 tile_y0: 0,
18499 tile_x1: reference.width,
18500 tile_y1: reference.height,
18501 };
18502 let ref_u = PlaneBuf {
18503 data: reference.u.iter().map(|&s| s as u16).collect(),
18504 width: reference.width / 2,
18505 height: reference.height / 2,
18506 true_width: reference.width / 2,
18507 true_height: reference.height / 2,
18508 tile_x0: 0,
18509 tile_y0: 0,
18510 tile_x1: reference.width / 2,
18511 tile_y1: reference.height / 2,
18512 };
18513 let ref_v = PlaneBuf {
18514 data: reference.v.iter().map(|&s| s as u16).collect(),
18515 width: reference.width / 2,
18516 height: reference.height / 2,
18517 true_width: reference.width / 2,
18518 true_height: reference.height / 2,
18519 tile_x0: 0,
18520 tile_y0: 0,
18521 tile_x1: reference.width / 2,
18522 tile_y1: reference.height / 2,
18523 };
18524 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
18525 // names a live DPB slot for (lane-av1refs: generalised from the old
18526 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
18527 // now per-reference). `decode_inter_block` refuses by name when the
18528 // block it is decoding selects an index that is still `None` here
18529 // (spec 7.9 requires every *active* reference be a compatible size;
18530 // an inactive one this frame never selects is simply left `None`).
18531 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
18532 other_refs[i]
18533 .filter(|g| g.width == reference.width && g.height == reference.height)
18534 .map(|g| {
18535 (
18536 PlaneBuf {
18537 data: g.y.iter().map(|&s| s as u16).collect(),
18538 width: g.width,
18539 height: g.height,
18540 true_width: g.width,
18541 true_height: g.height,
18542 tile_x0: 0,
18543 tile_y0: 0,
18544 tile_x1: g.width,
18545 tile_y1: g.height,
18546 },
18547 PlaneBuf {
18548 data: g.u.iter().map(|&s| s as u16).collect(),
18549 width: g.width / 2,
18550 height: g.height / 2,
18551 true_width: g.width / 2,
18552 true_height: g.height / 2,
18553 tile_x0: 0,
18554 tile_y0: 0,
18555 tile_x1: g.width / 2,
18556 tile_y1: g.height / 2,
18557 },
18558 PlaneBuf {
18559 data: g.v.iter().map(|&s| s as u16).collect(),
18560 width: g.width / 2,
18561 height: g.height / 2,
18562 true_width: g.width / 2,
18563 true_height: g.height / 2,
18564 tile_x0: 0,
18565 tile_y0: 0,
18566 tile_x1: g.width / 2,
18567 tile_y1: g.height / 2,
18568 },
18569 )
18570 })
18571 });
18572 let ref_slots: RefSlots =
18573 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
18574
18575 let mut y = PlaneBuf {
18576 data: vec![0u16; width * height],
18577 width,
18578 height,
18579 true_width,
18580 true_height,
18581 tile_x0: 0,
18582 tile_y0: 0,
18583 tile_x1: width,
18584 tile_y1: height,
18585 };
18586 let mut u = PlaneBuf {
18587 data: vec![0u16; width * height / 4],
18588 width: width / 2,
18589 height: height / 2,
18590 true_width: true_width / 2,
18591 true_height: true_height / 2,
18592 tile_x0: 0,
18593 tile_y0: 0,
18594 tile_x1: width / 2,
18595 tile_y1: height / 2,
18596 };
18597 let mut v = PlaneBuf {
18598 data: vec![0u16; width * height / 4],
18599 width: width / 2,
18600 height: height / 2,
18601 true_width: true_width / 2,
18602 true_height: true_height / 2,
18603 tile_x0: 0,
18604 tile_y0: 0,
18605 tile_x1: width / 2,
18606 tile_y1: height / 2,
18607 };
18608
18609 let scan32 = default_scan(TX32);
18610 let scan16 = default_scan(TX16);
18611 let scan8 = default_scan(TX8);
18612 let scan4 = default_scan(TX4);
18613
18614 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
18615 let mut result_cdfs = base_cdfs.clone();
18616 // spec `decode_tile`: `CurrentQIndex`/`DeltaLF` reset to the frame's own
18617 // `base_q_idx`/zero at the top of every tile, not once per frame (mirrors
18618 // `decode_key_frame_tile_with_cdfs`'s per-tile reset below); the
18619 // delta_q/delta_lf presence/resolution flags themselves are frame-level
18620 // and set once here.
18621 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
18622 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
18623 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
18624 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
18625 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
18626 let mut neighbours = Neighbours::new(
18627 cols as usize * 2,
18628 rows as usize * 2,
18629 mi_cols as usize,
18630 mi_rows as usize,
18631 );
18632 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
18633 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
18634 let mut lr_reference = [(
18635 crate::restoration::WienerInfo::default(),
18636 crate::restoration::SgrprojInfo::default(),
18637 ); 3];
18638
18639 // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile
18640 // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets
18641 // its own fresh SymbolDecoder over its own byte range and its own fresh
18642 // copy of the frame's initial CDFs; only context_update_tile_id's own
18643 // end-of-tile adapted table becomes the frame's own output.
18644 for (tile_idx, &data) in tiles.iter().enumerate() {
18645 let tile_num = tile_idx as u32;
18646 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
18647 let mi_row0 = tile_info.mi_row_starts[trow as usize];
18648 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
18649 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
18650 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
18651 let (sb_r0, sb_r1) = (
18652 (mi_row0 / SB_MI).min(sb_rows),
18653 mi_row1.div_ceil(SB_MI).min(sb_rows),
18654 );
18655 let (sb_c0, sb_c1) = (
18656 (mi_col0 / SB_MI).min(sb_cols),
18657 mi_col1.div_ceil(SB_MI).min(sb_cols),
18658 );
18659 let mut cdfs = base_cdfs.clone();
18660 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
18661 QUANT_DELTAS.with(|c| c.set(deltas));
18662 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
18663 let mut dec = SymbolDecoder::new(data);
18664 // lane-comppin r9: tile-entry range, the earliest point comparable
18665 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
18666 // first ladder rung before any symbol (partition or otherwise) is read.
18667 if std::env::var_os("EC_AV1_TELL").is_some() {
18668 eprintln!(
18669 "TELL label=tile_init tell={} range={}",
18670 dec.debug_bitpos(),
18671 dec.debug_state().0
18672 );
18673 }
18674 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
18675 y.set_tile_origin(
18676 mi_col0 as usize * 4,
18677 mi_row0 as usize * 4,
18678 (mi_col1 as usize * 4).min(y.width),
18679 (mi_row1 as usize * 4).min(y.height),
18680 );
18681 u.set_tile_origin(
18682 mi_col0 as usize * 2,
18683 mi_row0 as usize * 2,
18684 (mi_col1 as usize * 2).min(u.width),
18685 (mi_row1 as usize * 2).min(u.height),
18686 );
18687 v.set_tile_origin(
18688 mi_col0 as usize * 2,
18689 mi_row0 as usize * 2,
18690 (mi_col1 as usize * 2).min(v.width),
18691 (mi_row1 as usize * 2).min(v.height),
18692 );
18693 // lane-tiles r6: an MV candidate scan (mvstack.rs's grid.get) must
18694 // not reach across a tile boundary any more than intra prediction's
18695 // PlaneBuf reach does -- bounding the shared grid's own read window
18696 // per tile is equivalent to threading tile bounds through every
18697 // find_mv_stack* call site (all four read through this one grid).
18698 grid.set_tile_bounds(
18699 mi_row0 as usize,
18700 mi_col0 as usize,
18701 mi_row1 as usize,
18702 mi_col1 as usize,
18703 );
18704 TILE_HITS.with(|c| c.set(c.get() + 1));
18705
18706 // lane-sb128 r2: at `sb_size == 128` the tile walks each 128x128
18707 // superblock's four 64x64 quadrants in libaom `decode_partition` order
18708 // (TL, TR, BL, BR) and reads the 128 root's own loop-restoration units and
18709 // partition symbol once per superblock -- exactly what the key-frame tile
18710 // loop does; the 64-level body below is unchanged, `read_cdef`'s
18711 // per-64x64-quadrant reset (`CDEF_TRANSMITTED`) already matches libaom's
18712 // `cdef_idx[(mi_row & 16) >> 4 * 2 + (mi_col & 16) >> 4]` slot per quadrant.
18713 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
18714 if row_start {
18715 neighbours.start_row();
18716 }
18717 {
18718 if sb128 && sb_start {
18719 if read_sb128_root(
18720 &mut dec,
18721 &mut cdfs,
18722 &neighbours,
18723 lr,
18724 &mut lr_grid,
18725 &mut lr_reference,
18726 sb_r,
18727 sb_c,
18728 mi_cols,
18729 mi_rows,
18730 )? != PARTITION_SPLIT
18731 {
18732 // lane-sb128b r1 decodes a `PARTITION_NONE` 128 root on
18733 // KEY frames only; an inter 128x128 leaf needs whole-block
18734 // MC, OBMC and compound at a size this path has never run.
18735 return Err(unsupported(
18736 "a 128x128 superblock PARTITION_NONE root on an inter frame (only the key-frame path codes a whole 128x128 block)",
18737 ));
18738 }
18739 }
18740 if !sb128 {
18741 crate::restoration::read_lr(
18742 &mut dec,
18743 &mut cdfs,
18744 lr,
18745 &mut lr_grid,
18746 &mut lr_reference,
18747 sb_r * SB_MI,
18748 sb_c * SB_MI,
18749 SB_MI,
18750 );
18751 }
18752 CDEF_TRANSMITTED.with(|c| c.set(false));
18753 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
18754 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
18755 let (has_cols, has_rows) = (
18756 sb_c * SB_MI + SB_MI / 2 < mi_cols,
18757 sb_r * SB_MI + SB_MI / 2 < mi_rows,
18758 );
18759 // The straddle cases (one or both halves outside the true
18760 // frame) never carry a real alphabet symbol -- spec forces
18761 // SPLIT there (mirrors the intra key-frame tile's own
18762 // three-way write above). Only the (true, true) case can name
18763 // a non-SPLIT value, and this loop below only ever recurses as
18764 // SPLIT -- so a real non-SPLIT part64 here must refuse by name
18765 // instead of silently decoding as SPLIT and desyncing.
18766 let part64 = match (has_cols, has_rows) {
18767 (true, true) => {
18768 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
18769 if std::env::var_os("EC_AV1_TRACE").is_some() {
18770 eprintln!(
18771 "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}",
18772 sb_r * SB_MI,
18773 sb_c * SB_MI
18774 );
18775 }
18776 p
18777 }
18778 (true, false) => {
18779 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
18780 PARTITION_SPLIT
18781 }
18782 (false, true) => {
18783 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
18784 PARTITION_SPLIT
18785 }
18786 (false, false) => PARTITION_SPLIT,
18787 };
18788 if part64 == PARTITION_NONE {
18789 // lane-inter8 r1: the whole superblock as one 64x64 inter
18790 // block. `SB`-sized syntax throughout (size_group 3, same as
18791 // 32x32 -- `size_group_lookup[BLOCK_64X64] == 3`), luma
18792 // coefficients through `TxbSet::Luma64` with the 32-point
18793 // scan (TX_64X64 codes only its top-left corner, spec
18794 // 5.11.40 -- `read_inter_plane` widens the corner back to
18795 // 64x64 before the inverse transform), chroma as a plain
18796 // 32x32 `TxbSet::Chroma32`. TX_64X64 carries no `tx_type`
18797 // symbol at all, so the intra/inter luma sets coincide.
18798 INTER_SB_NONE_HITS.with(|c| c.set(c.get() + 1));
18799 decode_inter_block(
18800 &mut dec,
18801 &mut cdfs,
18802 &mut neighbours,
18803 &mut grid,
18804 sb_at,
18805 SB,
18806 mi_cols,
18807 mi_rows,
18808 &mut y,
18809 &mut u,
18810 &mut v,
18811 &ref_y,
18812 &ref_u,
18813 &ref_v,
18814 &ref_slots,
18815 &sign_bias_table,
18816 &global_motion,
18817 base_q_idx,
18818 TxbSet::Luma64,
18819 TxbSet::Luma64,
18820 TxbSet::Chroma32,
18821 TX32,
18822 TX32,
18823 &scan32,
18824 &scan32,
18825 3,
18826 allow_high_precision_mv,
18827 force_integer_mv,
18828 interp_fixed,
18829 enable_dual_filter,
18830 tpl_frame.as_ref(),
18831 reference_select,
18832 enable_masked_compound,
18833 enable_interintra_compound,
18834 enable_jnt_comp,
18835 order_hint_bits,
18836 order_hint,
18837 ref_order_hints,
18838 skip_mode_present,
18839 skip_mode_frame,
18840 switchable_motion_mode,
18841 allow_warped_motion,
18842 false,
18843 SB,
18844 SB,
18845 allow_screen_content_tools,
18846 frame_width as usize,
18847 )?;
18848 continue;
18849 }
18850 if part64 != PARTITION_SPLIT {
18851 return Err(unsupported(
18852 "an inter SB-level partition type other than NONE or SPLIT (this decoder's \
18853 inter tile path recurses a superblock only as SPLIT)",
18854 ));
18855 }
18856
18857 for quadrant in 0..4 {
18858 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
18859 if r32 >= rows || c32 >= cols {
18860 continue;
18861 }
18862 let at = (r32 as usize * 2, c32 as usize * 2);
18863 let ctx32 = neighbours.partition_ctx(at, BLOCK);
18864 let (has_cols32, has_rows32) = (
18865 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
18866 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
18867 );
18868 let part32 = if has_cols32 && has_rows32 {
18869 if std::env::var_os("EC_AV1_TRACE").is_some() {
18870 eprintln!(
18871 "TRACE part32_pre mi=({},{}) rng={}",
18872 r32 * BLOCK_MI,
18873 c32 * BLOCK_MI,
18874 dec.debug_state().0
18875 );
18876 }
18877 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
18878 if std::env::var_os("EC_AV1_TRACE").is_some() {
18879 eprintln!(
18880 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
18881 r32 * BLOCK_MI,
18882 c32 * BLOCK_MI
18883 );
18884 }
18885 p
18886 } else {
18887 match (has_cols32, has_rows32) {
18888 (true, false) => {
18889 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
18890 }
18891 (false, true) => {
18892 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
18893 }
18894 _ => {}
18895 }
18896 PARTITION_SPLIT
18897 };
18898 match part32 {
18899 PARTITION_NONE => {
18900 decode_inter_block(
18901 &mut dec,
18902 &mut cdfs,
18903 &mut neighbours,
18904 &mut grid,
18905 at,
18906 BLOCK,
18907 mi_cols,
18908 mi_rows,
18909 &mut y,
18910 &mut u,
18911 &mut v,
18912 &ref_y,
18913 &ref_u,
18914 &ref_v,
18915 &ref_slots,
18916 &sign_bias_table,
18917 &global_motion,
18918 base_q_idx,
18919 TxbSet::Luma32,
18920 TxbSet::Luma32Inter,
18921 TxbSet::Chroma16,
18922 TX32,
18923 TX16,
18924 &scan32,
18925 &scan16,
18926 3,
18927 allow_high_precision_mv,
18928 force_integer_mv,
18929 interp_fixed,
18930 enable_dual_filter,
18931 tpl_frame.as_ref(),
18932 reference_select,
18933 enable_masked_compound,
18934 enable_interintra_compound,
18935 enable_jnt_comp,
18936 order_hint_bits,
18937 order_hint,
18938 ref_order_hints,
18939 skip_mode_present,
18940 skip_mode_frame,
18941 switchable_motion_mode,
18942 allow_warped_motion,
18943 false,
18944 BLOCK,
18945 BLOCK,
18946 allow_screen_content_tools,
18947 frame_width as usize,
18948 )?;
18949 }
18950 PARTITION_SPLIT => {
18951 for sub in 0..4 {
18952 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
18953 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
18954 continue;
18955 }
18956 let (has_cols16, has_rows16) = (
18957 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
18958 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
18959 );
18960 if !has_cols16 && !has_rows16 {
18961 return Err(unsupported(
18962 "a 16x16 inter block whose true edge cuts through both \
18963 axes needs a rectangular transform this decoder does \
18964 not code yet",
18965 ));
18966 }
18967 let at16 = (sr, sc);
18968 let ctx16 = neighbours.partition_ctx(at16, SUB);
18969 // lane-inter8 r1: a straddling 16x16 cannot name a
18970 // value (spec forces SPLIT, one gathered bit); an
18971 // interior one reads the real alphabet, and
18972 // `PARTITION_SPLIT` now recurses into four 8x8
18973 // inter leaves through the very same loop the
18974 // straddling case has always used.
18975 let part16 = if has_cols16 && has_rows16 {
18976 let p = dec.symbol(&mut cdfs.partition_w16[ctx16]);
18977 if std::env::var_os("EC_AV1_TRACE").is_some() {
18978 let (rng, _) = dec.debug_state();
18979 eprintln!(
18980 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={p} rng={rng}",
18981 sr as u32 * SUB_MI,
18982 sc as u32 * SUB_MI
18983 );
18984 }
18985 p
18986 } else {
18987 if has_cols16 {
18988 dec.symbol_fixed(&gather(
18989 &cdfs.partition_w16[ctx16],
18990 VERT_ALIKE,
18991 ));
18992 } else {
18993 dec.symbol_fixed(&gather(
18994 &cdfs.partition_w16[ctx16],
18995 HORZ_ALIKE,
18996 ));
18997 }
18998 PARTITION_SPLIT
18999 };
19000 if part16 == PARTITION_NONE {
19001 decode_inter_block(
19002 &mut dec,
19003 &mut cdfs,
19004 &mut neighbours,
19005 &mut grid,
19006 at16,
19007 SUB,
19008 mi_cols,
19009 mi_rows,
19010 &mut y,
19011 &mut u,
19012 &mut v,
19013 &ref_y,
19014 &ref_u,
19015 &ref_v,
19016 &ref_slots,
19017 &sign_bias_table,
19018 &global_motion,
19019 base_q_idx,
19020 TxbSet::Luma16,
19021 if reduced_tx_set {
19022 TxbSet::Luma16Inter
19023 } else {
19024 TxbSet::Luma16InterSet1
19025 },
19026 TxbSet::Chroma8,
19027 TX16,
19028 TX8,
19029 &scan16,
19030 &scan8,
19031 2,
19032 allow_high_precision_mv,
19033 force_integer_mv,
19034 interp_fixed,
19035 enable_dual_filter,
19036 tpl_frame.as_ref(),
19037 reference_select,
19038 enable_masked_compound,
19039 enable_interintra_compound,
19040 enable_jnt_comp,
19041 order_hint_bits,
19042 order_hint,
19043 ref_order_hints,
19044 skip_mode_present,
19045 skip_mode_frame,
19046 switchable_motion_mode,
19047 allow_warped_motion,
19048 false,
19049 SUB,
19050 SUB,
19051 allow_screen_content_tools,
19052 frame_width as usize,
19053 )?;
19054 } else if part16 != PARTITION_SPLIT {
19055 return Err(unsupported(
19056 "an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet)",
19057 ));
19058 } else {
19059 if has_cols16 && has_rows16 {
19060 INTER_SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
19061 }
19062 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
19063 let leaf_positions: Vec<(u32, u32)> = (0..4)
19064 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
19065 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
19066 .collect();
19067 // lane-scaledref r1: `decode_inter_block8` IS
19068 // threaded for a scaled reference now (its
19069 // single-ref, compound and OBMC MC all take
19070 // spec 7.11.3.3's scaled walk), but the one
19071 // recipe that reaches this path at all -- a
19072 // 64x72 superres fixture whose bottom 16-row
19073 // band straddles the true edge, so the
19074 // gathered split bit lands on 8x8 leaves --
19075 // DESYNCS inside the leaf itself
19076 // (`from_switchable_symbol` handed a 4th
19077 // symbol, mc.rs:200), the same
19078 // below-8x8 desync lane-sub8 r2 left open and
19079 // unrelated to scaling. So the scaled MC here
19080 // is unproven: refuse by name rather than
19081 // ship a capability claim no gate exercises.
19082 // Deleting these six lines is the whole lift
19083 // once the leaf8 desync is fixed.
19084 if ref_y.width != frame_width as usize
19085 || ref_slots.iter().flatten().any(|(py, _, _)| {
19086 py.width != frame_width as usize
19087 })
19088 {
19089 return Err(unsupported(
19090 "an 8x8 partition leaf under a scaled reference (superres, unimplemented)",
19091 ));
19092 }
19093 let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option<i8>)> = Vec::new();
19094 for (mr, mc) in leaf_positions {
19095 let leaf_mi = (mr as usize, mc as usize);
19096 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
19097 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
19098 if part8 != PARTITION_NONE {
19099 return Err(unsupported(
19100 "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)",
19101 ));
19102 }
19103 let (
19104 skip,
19105 is_inter,
19106 skip_mode_leaf,
19107 compound_ctx8,
19108 leaf_filter,
19109 leaf_refs,
19110 ) = decode_inter_block8(
19111 &mut dec,
19112 &mut cdfs,
19113 &mut neighbours,
19114 &mut grid,
19115 mi_cols,
19116 mi_rows,
19117 at16,
19118 leaf_mi,
19119 &mut y,
19120 &mut u,
19121 &mut v,
19122 &ref_y,
19123 &ref_u,
19124 &ref_v,
19125 &ref_slots,
19126 base_q_idx,
19127 &scan8,
19128 &scan4,
19129 allow_high_precision_mv,
19130 force_integer_mv,
19131 &global_motion,
19132 enable_dual_filter,
19133 reference_select,
19134 enable_masked_compound,
19135 enable_interintra_compound,
19136 enable_jnt_comp,
19137 order_hint_bits,
19138 order_hint,
19139 ref_order_hints,
19140 skip_mode_present,
19141 skip_mode_frame,
19142 reduced_tx_set,
19143 interp_fixed,
19144 switchable_motion_mode,
19145 allow_warped_motion,
19146 allow_screen_content_tools,
19147 &sign_bias_table,
19148 tpl_frame.as_ref(),
19149 frame_width as usize,
19150 )?;
19151 prev_leaves.push((leaf_mi, skip, is_inter, leaf_refs.0, leaf_refs.1));
19152 // lane-inter8 r2: stamp THIS leaf's own
19153 // 2x2-mi span before the next leaf reads
19154 // it as a neighbour -- the whole-16x16
19155 // stamp below only ever described the
19156 // last leaf, so three quarters of the
19157 // block carried the wrong skip/ref/inter
19158 // state into the next block's contexts
19159 // (class context-read-from-one-cell).
19160 // lane-gmaffine r3: with the mi-granular
19161 // band, the leaf's OWN switchable-filter
19162 // symbols go in here -- the `[3, 3]`
19163 // ("intra, no filter") sentinel this used
19164 // to stamp made `obmc_blend`'s
19165 // `neighbour_filter` PANIC as soon as a
19166 // sibling leaf blended one of these.
19167 neighbours.record_inter_rect_mi(
19168 leaf_mi,
19169 2,
19170 2,
19171 skip,
19172 is_inter,
19173 leaf_refs.0,
19174 leaf_filter,
19175 skip_mode_leaf,
19176 );
19177 if let Some(ref1) = leaf_refs.1
19178 && let Some((_, _, group_idx, idx)) = compound_ctx8
19179 {
19180 neighbours.record_compound_ctx_rect_mi(
19181 leaf_mi, 2, 2, ref1, group_idx, idx,
19182 );
19183 }
19184 }
19185 // lane-inter8 r2: the four per-leaf
19186 // `record_inter_rect_mi` stamps above replace
19187 // the single whole-16x16 one that used to run
19188 // here with the LAST leaf's state.
19189 }
19190 }
19191 }
19192 PARTITION_HORZ_B => {
19193 // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip +
19194 // 16x16 bottom-left + 16x16 bottom-right. aomenc
19195 // carves static regions into it; the strip is
19196 // decoded as a square 32x32 block: for a `skip`
19197 // block the symbol stream is identical to the true
19198 // 32x16 coding (no residual, no motion_mode/warp
19199 // symbol), and the square stamps it leaves over the
19200 // bottom half (neighbour arrays, skip/lf grids) are
19201 // re-stamped by the C/D leaves right after. The
19202 // mi-granular `left_side_mi` rows of a last-block-in-
19203 // tile strip leak 32-vs-16 only until the per-tile
19204 // `Neighbours::new` reset.
19205 EXTENDED_PARTITION_HITS.with(|c| c.set(c.get() + 1));
19206 let at32 = at;
19207 decode_inter_block(
19208 &mut dec,
19209 &mut cdfs,
19210 &mut neighbours,
19211 &mut grid,
19212 at32,
19213 BLOCK,
19214 mi_cols,
19215 mi_rows,
19216 &mut y,
19217 &mut u,
19218 &mut v,
19219 &ref_y,
19220 &ref_u,
19221 &ref_v,
19222 &ref_slots,
19223 &sign_bias_table,
19224 &global_motion,
19225 base_q_idx,
19226 TxbSet::Luma32,
19227 TxbSet::Luma32Inter,
19228 TxbSet::Chroma16,
19229 TX32,
19230 TX16,
19231 &scan32,
19232 &scan16,
19233 3,
19234 allow_high_precision_mv,
19235 force_integer_mv,
19236 interp_fixed,
19237 enable_dual_filter,
19238 tpl_frame.as_ref(),
19239 reference_select,
19240 enable_masked_compound,
19241 enable_interintra_compound,
19242 enable_jnt_comp,
19243 order_hint_bits,
19244 order_hint,
19245 ref_order_hints,
19246 skip_mode_present,
19247 skip_mode_frame,
19248 switchable_motion_mode,
19249 allow_warped_motion,
19250 true,
19251 // lane-rect r2: the top strip's TRUE 32x16
19252 // footprint (was BLOCK,BLOCK -- the same square
19253 // corner-cut rect-flake-1 exposed on HORZ).
19254 BLOCK,
19255 SUB,
19256 allow_screen_content_tools,
19257 frame_width as usize,
19258 )?;
19259 if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows {
19260 decode_inter_block(
19261 &mut dec,
19262 &mut cdfs,
19263 &mut neighbours,
19264 &mut grid,
19265 (r32 as usize * 2 + 1, c32 as usize * 2),
19266 SUB,
19267 mi_cols,
19268 mi_rows,
19269 &mut y,
19270 &mut u,
19271 &mut v,
19272 &ref_y,
19273 &ref_u,
19274 &ref_v,
19275 &ref_slots,
19276 &sign_bias_table,
19277 &global_motion,
19278 base_q_idx,
19279 TxbSet::Luma16,
19280 if reduced_tx_set {
19281 TxbSet::Luma16Inter
19282 } else {
19283 TxbSet::Luma16InterSet1
19284 },
19285 TxbSet::Chroma8,
19286 TX16,
19287 TX8,
19288 &scan16,
19289 &scan8,
19290 2,
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 false,
19308 SUB,
19309 SUB,
19310 allow_screen_content_tools,
19311 frame_width as usize,
19312 )?;
19313 if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols {
19314 decode_inter_block(
19315 &mut dec,
19316 &mut cdfs,
19317 &mut neighbours,
19318 &mut grid,
19319 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
19320 SUB,
19321 mi_cols,
19322 mi_rows,
19323 &mut y,
19324 &mut u,
19325 &mut v,
19326 &ref_y,
19327 &ref_u,
19328 &ref_v,
19329 &ref_slots,
19330 &sign_bias_table,
19331 &global_motion,
19332 base_q_idx,
19333 TxbSet::Luma16,
19334 if reduced_tx_set {
19335 TxbSet::Luma16Inter
19336 } else {
19337 TxbSet::Luma16InterSet1
19338 },
19339 TxbSet::Chroma8,
19340 TX16,
19341 TX8,
19342 &scan16,
19343 &scan8,
19344 2,
19345 allow_high_precision_mv,
19346 force_integer_mv,
19347 interp_fixed,
19348 enable_dual_filter,
19349 tpl_frame.as_ref(),
19350 reference_select,
19351 enable_masked_compound,
19352 enable_interintra_compound,
19353 enable_jnt_comp,
19354 order_hint_bits,
19355 order_hint,
19356 ref_order_hints,
19357 skip_mode_present,
19358 skip_mode_frame,
19359 switchable_motion_mode,
19360 allow_warped_motion,
19361 false,
19362 SUB,
19363 SUB,
19364 allow_screen_content_tools,
19365 frame_width as usize,
19366 )?;
19367 }
19368 }
19369 }
19370 PARTITION_HORZ => {
19371 // lane-rect r2: two true 32x16 strips. Both read at
19372 // `side=BLOCK` (CDF/size-class selection stays square,
19373 // matching HORZ_B's accepted corner-cut) but bw4/bh4
19374 // (mvstack.rs, `motion_mode_eligible`) now derive from
19375 // `write_w`/`write_h`'s true 32x16 footprint -- the
19376 // pin's fix (r1's finding).
19377 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
19378 decode_inter_block(
19379 &mut dec,
19380 &mut cdfs,
19381 &mut neighbours,
19382 &mut grid,
19383 at,
19384 BLOCK,
19385 mi_cols,
19386 mi_rows,
19387 &mut y,
19388 &mut u,
19389 &mut v,
19390 &ref_y,
19391 &ref_u,
19392 &ref_v,
19393 &ref_slots,
19394 &sign_bias_table,
19395 &global_motion,
19396 base_q_idx,
19397 TxbSet::Luma32,
19398 TxbSet::Luma32Inter,
19399 TxbSet::Chroma16,
19400 TX32,
19401 TX16,
19402 &scan32,
19403 &scan16,
19404 3,
19405 allow_high_precision_mv,
19406 force_integer_mv,
19407 interp_fixed,
19408 enable_dual_filter,
19409 tpl_frame.as_ref(),
19410 reference_select,
19411 enable_masked_compound,
19412 enable_interintra_compound,
19413 enable_jnt_comp,
19414 order_hint_bits,
19415 order_hint,
19416 ref_order_hints,
19417 skip_mode_present,
19418 skip_mode_frame,
19419 switchable_motion_mode,
19420 allow_warped_motion,
19421 true,
19422 BLOCK,
19423 SUB,
19424 allow_screen_content_tools,
19425 frame_width as usize,
19426 )?;
19427 decode_inter_block(
19428 &mut dec,
19429 &mut cdfs,
19430 &mut neighbours,
19431 &mut grid,
19432 (r32 as usize * 2 + 1, c32 as usize * 2),
19433 BLOCK,
19434 mi_cols,
19435 mi_rows,
19436 &mut y,
19437 &mut u,
19438 &mut v,
19439 &ref_y,
19440 &ref_u,
19441 &ref_v,
19442 &ref_slots,
19443 &sign_bias_table,
19444 &global_motion,
19445 base_q_idx,
19446 TxbSet::Luma32,
19447 TxbSet::Luma32Inter,
19448 TxbSet::Chroma16,
19449 TX32,
19450 TX16,
19451 &scan32,
19452 &scan16,
19453 3,
19454 allow_high_precision_mv,
19455 force_integer_mv,
19456 interp_fixed,
19457 enable_dual_filter,
19458 tpl_frame.as_ref(),
19459 reference_select,
19460 enable_masked_compound,
19461 enable_interintra_compound,
19462 enable_jnt_comp,
19463 order_hint_bits,
19464 order_hint,
19465 ref_order_hints,
19466 skip_mode_present,
19467 skip_mode_frame,
19468 switchable_motion_mode,
19469 allow_warped_motion,
19470 true,
19471 BLOCK,
19472 SUB,
19473 allow_screen_content_tools,
19474 frame_width as usize,
19475 )?;
19476 }
19477 PARTITION_VERT => {
19478 // lane-rect r2: mirror of PARTITION_HORZ above with
19479 // width/height swapped.
19480 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
19481 decode_inter_block(
19482 &mut dec,
19483 &mut cdfs,
19484 &mut neighbours,
19485 &mut grid,
19486 at,
19487 BLOCK,
19488 mi_cols,
19489 mi_rows,
19490 &mut y,
19491 &mut u,
19492 &mut v,
19493 &ref_y,
19494 &ref_u,
19495 &ref_v,
19496 &ref_slots,
19497 &sign_bias_table,
19498 &global_motion,
19499 base_q_idx,
19500 TxbSet::Luma32,
19501 TxbSet::Luma32Inter,
19502 TxbSet::Chroma16,
19503 TX32,
19504 TX16,
19505 &scan32,
19506 &scan16,
19507 3,
19508 allow_high_precision_mv,
19509 force_integer_mv,
19510 interp_fixed,
19511 enable_dual_filter,
19512 tpl_frame.as_ref(),
19513 reference_select,
19514 enable_masked_compound,
19515 enable_interintra_compound,
19516 enable_jnt_comp,
19517 order_hint_bits,
19518 order_hint,
19519 ref_order_hints,
19520 skip_mode_present,
19521 skip_mode_frame,
19522 switchable_motion_mode,
19523 allow_warped_motion,
19524 true,
19525 SUB,
19526 BLOCK,
19527 allow_screen_content_tools,
19528 frame_width as usize,
19529 )?;
19530 decode_inter_block(
19531 &mut dec,
19532 &mut cdfs,
19533 &mut neighbours,
19534 &mut grid,
19535 (r32 as usize * 2, c32 as usize * 2 + 1),
19536 BLOCK,
19537 mi_cols,
19538 mi_rows,
19539 &mut y,
19540 &mut u,
19541 &mut v,
19542 &ref_y,
19543 &ref_u,
19544 &ref_v,
19545 &ref_slots,
19546 &sign_bias_table,
19547 &global_motion,
19548 base_q_idx,
19549 TxbSet::Luma32,
19550 TxbSet::Luma32Inter,
19551 TxbSet::Chroma16,
19552 TX32,
19553 TX16,
19554 &scan32,
19555 &scan16,
19556 3,
19557 allow_high_precision_mv,
19558 force_integer_mv,
19559 interp_fixed,
19560 enable_dual_filter,
19561 tpl_frame.as_ref(),
19562 reference_select,
19563 enable_masked_compound,
19564 enable_interintra_compound,
19565 enable_jnt_comp,
19566 order_hint_bits,
19567 order_hint,
19568 ref_order_hints,
19569 skip_mode_present,
19570 skip_mode_frame,
19571 switchable_motion_mode,
19572 allow_warped_motion,
19573 true,
19574 SUB,
19575 BLOCK,
19576 allow_screen_content_tools,
19577 frame_width as usize,
19578 )?;
19579 }
19580 PARTITION_HORZ_A => {
19581 // lane-partab r1: two 16x16 squares on top + a true
19582 // 32x16 strip below (libaom decode_partition
19583 // PARTITION_HORZ_A: TL, TR, bottom strip).
19584 PARTAB_HITS.with(|c| c.set(c.get() + 1));
19585 decode_inter_block(
19586 &mut dec,
19587 &mut cdfs,
19588 &mut neighbours,
19589 &mut grid,
19590 at,
19591 SUB,
19592 mi_cols,
19593 mi_rows,
19594 &mut y,
19595 &mut u,
19596 &mut v,
19597 &ref_y,
19598 &ref_u,
19599 &ref_v,
19600 &ref_slots,
19601 &sign_bias_table,
19602 &global_motion,
19603 base_q_idx,
19604 TxbSet::Luma16,
19605 if reduced_tx_set {
19606 TxbSet::Luma16Inter
19607 } else {
19608 TxbSet::Luma16InterSet1
19609 },
19610 TxbSet::Chroma8,
19611 TX16,
19612 TX8,
19613 &scan16,
19614 &scan8,
19615 2,
19616 allow_high_precision_mv,
19617 force_integer_mv,
19618 interp_fixed,
19619 enable_dual_filter,
19620 tpl_frame.as_ref(),
19621 reference_select,
19622 enable_masked_compound,
19623 enable_interintra_compound,
19624 enable_jnt_comp,
19625 order_hint_bits,
19626 order_hint,
19627 ref_order_hints,
19628 skip_mode_present,
19629 skip_mode_frame,
19630 switchable_motion_mode,
19631 allow_warped_motion,
19632 false,
19633 SUB,
19634 SUB,
19635 allow_screen_content_tools,
19636 frame_width as usize,
19637 )?;
19638 decode_inter_block(
19639 &mut dec,
19640 &mut cdfs,
19641 &mut neighbours,
19642 &mut grid,
19643 (r32 as usize * 2, c32 as usize * 2 + 1),
19644 SUB,
19645 mi_cols,
19646 mi_rows,
19647 &mut y,
19648 &mut u,
19649 &mut v,
19650 &ref_y,
19651 &ref_u,
19652 &ref_v,
19653 &ref_slots,
19654 &sign_bias_table,
19655 &global_motion,
19656 base_q_idx,
19657 TxbSet::Luma16,
19658 if reduced_tx_set {
19659 TxbSet::Luma16Inter
19660 } else {
19661 TxbSet::Luma16InterSet1
19662 },
19663 TxbSet::Chroma8,
19664 TX16,
19665 TX8,
19666 &scan16,
19667 &scan8,
19668 2,
19669 allow_high_precision_mv,
19670 force_integer_mv,
19671 interp_fixed,
19672 enable_dual_filter,
19673 tpl_frame.as_ref(),
19674 reference_select,
19675 enable_masked_compound,
19676 enable_interintra_compound,
19677 enable_jnt_comp,
19678 order_hint_bits,
19679 order_hint,
19680 ref_order_hints,
19681 skip_mode_present,
19682 skip_mode_frame,
19683 switchable_motion_mode,
19684 allow_warped_motion,
19685 false,
19686 SUB,
19687 SUB,
19688 allow_screen_content_tools,
19689 frame_width as usize,
19690 )?;
19691 decode_inter_block(
19692 &mut dec,
19693 &mut cdfs,
19694 &mut neighbours,
19695 &mut grid,
19696 (r32 as usize * 2 + 1, c32 as usize * 2),
19697 BLOCK,
19698 mi_cols,
19699 mi_rows,
19700 &mut y,
19701 &mut u,
19702 &mut v,
19703 &ref_y,
19704 &ref_u,
19705 &ref_v,
19706 &ref_slots,
19707 &sign_bias_table,
19708 &global_motion,
19709 base_q_idx,
19710 TxbSet::Luma32,
19711 TxbSet::Luma32Inter,
19712 TxbSet::Chroma16,
19713 TX32,
19714 TX16,
19715 &scan32,
19716 &scan16,
19717 3,
19718 allow_high_precision_mv,
19719 force_integer_mv,
19720 interp_fixed,
19721 enable_dual_filter,
19722 tpl_frame.as_ref(),
19723 reference_select,
19724 enable_masked_compound,
19725 enable_interintra_compound,
19726 enable_jnt_comp,
19727 order_hint_bits,
19728 order_hint,
19729 ref_order_hints,
19730 skip_mode_present,
19731 skip_mode_frame,
19732 switchable_motion_mode,
19733 allow_warped_motion,
19734 true,
19735 BLOCK,
19736 SUB,
19737 allow_screen_content_tools,
19738 frame_width as usize,
19739 )?;
19740 }
19741 PARTITION_VERT_A => {
19742 // lane-partab r1: mirror of PARTITION_HORZ_A with
19743 // width/height swapped (TL, BL, right 16x32 strip).
19744 PARTAB_HITS.with(|c| c.set(c.get() + 1));
19745 let _vert_ab = crate::encode::Reach::vert_ab_partition();
19746 decode_inter_block(
19747 &mut dec,
19748 &mut cdfs,
19749 &mut neighbours,
19750 &mut grid,
19751 at,
19752 SUB,
19753 mi_cols,
19754 mi_rows,
19755 &mut y,
19756 &mut u,
19757 &mut v,
19758 &ref_y,
19759 &ref_u,
19760 &ref_v,
19761 &ref_slots,
19762 &sign_bias_table,
19763 &global_motion,
19764 base_q_idx,
19765 TxbSet::Luma16,
19766 if reduced_tx_set {
19767 TxbSet::Luma16Inter
19768 } else {
19769 TxbSet::Luma16InterSet1
19770 },
19771 TxbSet::Chroma8,
19772 TX16,
19773 TX8,
19774 &scan16,
19775 &scan8,
19776 2,
19777 allow_high_precision_mv,
19778 force_integer_mv,
19779 interp_fixed,
19780 enable_dual_filter,
19781 tpl_frame.as_ref(),
19782 reference_select,
19783 enable_masked_compound,
19784 enable_interintra_compound,
19785 enable_jnt_comp,
19786 order_hint_bits,
19787 order_hint,
19788 ref_order_hints,
19789 skip_mode_present,
19790 skip_mode_frame,
19791 switchable_motion_mode,
19792 allow_warped_motion,
19793 false,
19794 SUB,
19795 SUB,
19796 allow_screen_content_tools,
19797 frame_width as usize,
19798 )?;
19799 decode_inter_block(
19800 &mut dec,
19801 &mut cdfs,
19802 &mut neighbours,
19803 &mut grid,
19804 (r32 as usize * 2 + 1, c32 as usize * 2),
19805 SUB,
19806 mi_cols,
19807 mi_rows,
19808 &mut y,
19809 &mut u,
19810 &mut v,
19811 &ref_y,
19812 &ref_u,
19813 &ref_v,
19814 &ref_slots,
19815 &sign_bias_table,
19816 &global_motion,
19817 base_q_idx,
19818 TxbSet::Luma16,
19819 if reduced_tx_set {
19820 TxbSet::Luma16Inter
19821 } else {
19822 TxbSet::Luma16InterSet1
19823 },
19824 TxbSet::Chroma8,
19825 TX16,
19826 TX8,
19827 &scan16,
19828 &scan8,
19829 2,
19830 allow_high_precision_mv,
19831 force_integer_mv,
19832 interp_fixed,
19833 enable_dual_filter,
19834 tpl_frame.as_ref(),
19835 reference_select,
19836 enable_masked_compound,
19837 enable_interintra_compound,
19838 enable_jnt_comp,
19839 order_hint_bits,
19840 order_hint,
19841 ref_order_hints,
19842 skip_mode_present,
19843 skip_mode_frame,
19844 switchable_motion_mode,
19845 allow_warped_motion,
19846 false,
19847 SUB,
19848 SUB,
19849 allow_screen_content_tools,
19850 frame_width as usize,
19851 )?;
19852 decode_inter_block(
19853 &mut dec,
19854 &mut cdfs,
19855 &mut neighbours,
19856 &mut grid,
19857 (r32 as usize * 2, c32 as usize * 2 + 1),
19858 BLOCK,
19859 mi_cols,
19860 mi_rows,
19861 &mut y,
19862 &mut u,
19863 &mut v,
19864 &ref_y,
19865 &ref_u,
19866 &ref_v,
19867 &ref_slots,
19868 &sign_bias_table,
19869 &global_motion,
19870 base_q_idx,
19871 TxbSet::Luma32,
19872 TxbSet::Luma32Inter,
19873 TxbSet::Chroma16,
19874 TX32,
19875 TX16,
19876 &scan32,
19877 &scan16,
19878 3,
19879 allow_high_precision_mv,
19880 force_integer_mv,
19881 interp_fixed,
19882 enable_dual_filter,
19883 tpl_frame.as_ref(),
19884 reference_select,
19885 enable_masked_compound,
19886 enable_interintra_compound,
19887 enable_jnt_comp,
19888 order_hint_bits,
19889 order_hint,
19890 ref_order_hints,
19891 skip_mode_present,
19892 skip_mode_frame,
19893 switchable_motion_mode,
19894 allow_warped_motion,
19895 true,
19896 SUB,
19897 BLOCK,
19898 allow_screen_content_tools,
19899 frame_width as usize,
19900 )?;
19901 }
19902 PARTITION_VERT_B => {
19903 // lane-partab r1: true 16x32 strip on the left + two
19904 // 16x16 squares on the right (libaom decode_partition
19905 // PARTITION_VERT_B: left strip, TR, BR).
19906 PARTAB_HITS.with(|c| c.set(c.get() + 1));
19907 let _vert_ab = crate::encode::Reach::vert_ab_partition();
19908 decode_inter_block(
19909 &mut dec,
19910 &mut cdfs,
19911 &mut neighbours,
19912 &mut grid,
19913 at,
19914 BLOCK,
19915 mi_cols,
19916 mi_rows,
19917 &mut y,
19918 &mut u,
19919 &mut v,
19920 &ref_y,
19921 &ref_u,
19922 &ref_v,
19923 &ref_slots,
19924 &sign_bias_table,
19925 &global_motion,
19926 base_q_idx,
19927 TxbSet::Luma32,
19928 TxbSet::Luma32Inter,
19929 TxbSet::Chroma16,
19930 TX32,
19931 TX16,
19932 &scan32,
19933 &scan16,
19934 3,
19935 allow_high_precision_mv,
19936 force_integer_mv,
19937 interp_fixed,
19938 enable_dual_filter,
19939 tpl_frame.as_ref(),
19940 reference_select,
19941 enable_masked_compound,
19942 enable_interintra_compound,
19943 enable_jnt_comp,
19944 order_hint_bits,
19945 order_hint,
19946 ref_order_hints,
19947 skip_mode_present,
19948 skip_mode_frame,
19949 switchable_motion_mode,
19950 allow_warped_motion,
19951 true,
19952 SUB,
19953 BLOCK,
19954 allow_screen_content_tools,
19955 frame_width as usize,
19956 )?;
19957 decode_inter_block(
19958 &mut dec,
19959 &mut cdfs,
19960 &mut neighbours,
19961 &mut grid,
19962 (r32 as usize * 2, c32 as usize * 2 + 1),
19963 SUB,
19964 mi_cols,
19965 mi_rows,
19966 &mut y,
19967 &mut u,
19968 &mut v,
19969 &ref_y,
19970 &ref_u,
19971 &ref_v,
19972 &ref_slots,
19973 &sign_bias_table,
19974 &global_motion,
19975 base_q_idx,
19976 TxbSet::Luma16,
19977 if reduced_tx_set {
19978 TxbSet::Luma16Inter
19979 } else {
19980 TxbSet::Luma16InterSet1
19981 },
19982 TxbSet::Chroma8,
19983 TX16,
19984 TX8,
19985 &scan16,
19986 &scan8,
19987 2,
19988 allow_high_precision_mv,
19989 force_integer_mv,
19990 interp_fixed,
19991 enable_dual_filter,
19992 tpl_frame.as_ref(),
19993 reference_select,
19994 enable_masked_compound,
19995 enable_interintra_compound,
19996 enable_jnt_comp,
19997 order_hint_bits,
19998 order_hint,
19999 ref_order_hints,
20000 skip_mode_present,
20001 skip_mode_frame,
20002 switchable_motion_mode,
20003 allow_warped_motion,
20004 false,
20005 SUB,
20006 SUB,
20007 allow_screen_content_tools,
20008 frame_width as usize,
20009 )?;
20010 decode_inter_block(
20011 &mut dec,
20012 &mut cdfs,
20013 &mut neighbours,
20014 &mut grid,
20015 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
20016 SUB,
20017 mi_cols,
20018 mi_rows,
20019 &mut y,
20020 &mut u,
20021 &mut v,
20022 &ref_y,
20023 &ref_u,
20024 &ref_v,
20025 &ref_slots,
20026 &sign_bias_table,
20027 &global_motion,
20028 base_q_idx,
20029 TxbSet::Luma16,
20030 if reduced_tx_set {
20031 TxbSet::Luma16Inter
20032 } else {
20033 TxbSet::Luma16InterSet1
20034 },
20035 TxbSet::Chroma8,
20036 TX16,
20037 TX8,
20038 &scan16,
20039 &scan8,
20040 2,
20041 allow_high_precision_mv,
20042 force_integer_mv,
20043 interp_fixed,
20044 enable_dual_filter,
20045 tpl_frame.as_ref(),
20046 reference_select,
20047 enable_masked_compound,
20048 enable_interintra_compound,
20049 enable_jnt_comp,
20050 order_hint_bits,
20051 order_hint,
20052 ref_order_hints,
20053 skip_mode_present,
20054 skip_mode_frame,
20055 switchable_motion_mode,
20056 allow_warped_motion,
20057 false,
20058 SUB,
20059 SUB,
20060 allow_screen_content_tools,
20061 frame_width as usize,
20062 )?;
20063 }
20064 _ => {
20065 return Err(unsupported(format!(
20066 "an INTER 32x32 partition type this decoder does not code (value={part32})"
20067 )));
20068 }
20069 }
20070 }
20071 }
20072 }
20073
20074 if tile_num == tile_info.context_update_tile_id {
20075 result_cdfs = cdfs;
20076 }
20077 }
20078
20079 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
20080 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
20081 // that isolate whether a decode-order frame's mismatch already exists
20082 // in reconstruction (this dump) vs is introduced by the loop filter
20083 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
20084 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
20085 use std::io::Write;
20086 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
20087 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
20088 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
20089 let _ = f.write_all(&narrow(&y));
20090 let _ = f.write_all(&narrow(&u));
20091 let _ = f.write_all(&narrow(&v));
20092 }
20093 } else {
20094 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
20095 }
20096 apply_deblock(
20097 &mut y,
20098 &mut u,
20099 &mut v,
20100 loop_filter,
20101 &neighbours,
20102 frame_width as usize,
20103 frame_height as usize,
20104 );
20105 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
20106 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
20107 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
20108 // dump above these bisect WHICH filter stage introduced a mismatch.
20109 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
20110 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
20111 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
20112 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
20113
20114 let motion_field = build_motion_field(
20115 &grid,
20116 mi_cols as usize,
20117 mi_rows as usize,
20118 order_hint,
20119 ref_order_hints,
20120 );
20121
20122 let (fw, fh) = (frame_width as usize, frame_height as usize);
20123 if fw == width && fh == height {
20124 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
20125 return Ok((
20126 Picture {
20127 width,
20128 height,
20129 y: y.data,
20130 u: u.data,
20131 v: v.data,
20132 },
20133 result_cdfs,
20134 motion_field,
20135 ));
20136 }
20137 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
20138 let mut out = Vec::with_capacity(w * h);
20139 for row in 0..h {
20140 out.extend(plane.data[row * plane.width..][..w].iter().copied());
20141 }
20142 out
20143 };
20144 // lane-superres r10 (fixed r9): same real-margin stash as
20145 // `decode_key_frame_tile_with_cdfs` (see that function's comment) -- the
20146 // real reconstructed extent is the mi-aligned `true_width`/`true_height`
20147 // (`mi_cols`/`mi_rows` * 4), NOT the superblock-padded `width`/`height`
20148 // this branch was reading before: columns `[true_width, width)` were
20149 // never actually coded (the last partial superblock stops at
20150 // `true_width`), so stashing out to `width` handed the chroma upscale's
20151 // right-edge replicate a slice of uninitialized/stale buffer one column
20152 // early -- the same shorten-vs-replicate shape as `av1-truesize`. The
20153 // key-frame branch above already used `true_width`/`true_height`; this
20154 // just matches it.
20155 LAST_FRAME_WIDE_MARGIN.with(|m| {
20156 *m.borrow_mut() = if true_width > fw || true_height > fh {
20157 Some(Picture {
20158 width: true_width,
20159 height: true_height,
20160 y: crop(&y, true_width, true_height),
20161 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
20162 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
20163 })
20164 } else {
20165 None
20166 }
20167 });
20168 Ok((
20169 Picture {
20170 width: fw,
20171 height: fh,
20172 y: crop(&y, fw, fh),
20173 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
20174 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
20175 },
20176 result_cdfs,
20177 motion_field,
20178 ))
20179}
20180
20181#[cfg(test)]
20182mod tests {
20183
20184 /// lane-fistrip r1 (class `enumerate-the-table-domain`): every block
20185 /// shape this decoder can hand [`filter_intra_size_class_rect`], against
20186 /// `av1_filter_intra_allowed_bsize` (`block_size_wide <= 32 &&
20187 /// block_size_high <= 32`) and `default_filter_intra_cdfs`
20188 /// (entropymode.c) row by row. A class that exists must carry ITS OWN
20189 /// bsize's default probability -- a wrong row is a silently different
20190 /// symbol, not a decode error. The shapes with no class are listed here
20191 /// with their reason so the residue is pinned rather than implied.
20192 #[test]
20193 fn filter_intra_classes_carry_their_own_libaom_default_row() {
20194 // `default_filter_intra_cdfs[bsize]`, BLOCK_SIZES_ALL order, as
20195 // (width, height, default, refused_by) for the shapes <= 32 on both
20196 // axes. The first three fields are GENERATED from the oracle by
20197 // `scripts/extract-filter-intra-cdfs.py` (it reads BLOCK_SIZES_ALL's
20198 // order from enums.h and the table from entropymode.c, so no hand
20199 // transcription can drift -- lane-fistrip r1 listed the four 1:4
20200 // shapes as 16384 out of exactly that kind of guess; their real rows
20201 // are 12770/10368/20229/18101). `refused_by` is `None` for a shape
20202 // this decoder's partition tree reaches today -- it must own a class,
20203 // and that class must carry exactly this row -- and the refusal
20204 // string that blocks the shape otherwise. Either way the row is
20205 // pinned HERE, so the round that lifts one of those refusals cannot
20206 // land a wrong CDF row for the shape it unlocks.
20207 const PART16: &str = "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes \
20208 only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)";
20209 let libaom: &[(usize, usize, u16, Option<&str>)] = &[
20210 (4, 4, 4621, None),
20211 (4, 8, 6743, None),
20212 (8, 4, 5893, None),
20213 (8, 8, 7866, None),
20214 (8, 16, 12551, None),
20215 (16, 8, 9394, None),
20216 (16, 16, 12408, None),
20217 (16, 32, 14301, None),
20218 (32, 16, 12756, None),
20219 (32, 32, 22343, None),
20220 // The 1:4 strips: a 16x16-level PARTITION_HORZ_4/VERT_4 gives
20221 // 4x16/16x4 (still refused by name before any leaf is coded),
20222 // a 32x32-level one 8x32/32x8.
20223 (4, 16, 12770, Some(PART16)),
20224 (16, 4, 10368, Some(PART16)),
20225 // lane-fi32x8 r1: the 32-level pair is coded (four 32x8/8x32
20226 // strips per `PARTITION_HORZ_4`/`VERT_4`) and now owns classes
20227 // 10/11; only the 16-level pair is still refused before any leaf.
20228 (8, 32, 20229, None),
20229 (32, 8, 18101, None),
20230 ];
20231 let mut classes_seen = std::collections::BTreeSet::new();
20232 for &(bw, bh, default, refused_by) in libaom {
20233 match filter_intra_size_class_rect(bw, bh) {
20234 Some(class) => {
20235 assert!(
20236 refused_by.is_none(),
20237 "{bw}x{bh} has a CDF class but is listed as refused by {refused_by:?} -- \
20238 one of the two is stale"
20239 );
20240 assert_eq!(
20241 crate::cdf::FILTER_INTRA[class][0],
20242 default,
20243 "{bw}x{bh} (class {class}) must carry default_filter_intra_cdfs' own row"
20244 );
20245 assert_eq!(
20246 &crate::cdf::FILTER_INTRA[class][1..],
20247 &[32768u16, 0][..],
20248 "{bw}x{bh} (class {class}) is a 2-symbol CDF: {{p, 32768, count}}"
20249 );
20250 assert!(
20251 classes_seen.insert(class),
20252 "class {class} is claimed by two shapes -- one of them reads the other's \
20253 probability"
20254 );
20255 }
20256 None => {
20257 let why = refused_by.unwrap_or_else(|| {
20258 panic!(
20259 "{bw}x{bh} is inside av1_filter_intra_allowed_bsize and reachable, \
20260 but has no CDF class -- its use_filter_intra symbol is never read"
20261 )
20262 });
20263 assert!(!why.is_empty(), "{bw}x{bh}'s refusal string must name the blocker");
20264 }
20265 }
20266 }
20267 // The other direction: every row of `cdf::FILTER_INTRA` was claimed
20268 // by exactly one shape above, so no row can be left over (or shared)
20269 // once a class is added or removed.
20270 assert_eq!(
20271 classes_seen.len(),
20272 crate::cdf::FILTER_INTRA.len(),
20273 "cdf::FILTER_INTRA has {} rows but only {:?} are claimed by an allowed shape",
20274 crate::cdf::FILTER_INTRA.len(),
20275 classes_seen
20276 );
20277 // Past the bound on either axis: no symbol at all (spec
20278 // `filter_intra_mode_info` never reads one).
20279 for (bw, bh) in [(64, 64), (64, 32), (32, 64)] {
20280 assert!(
20281 filter_intra_size_class_rect(bw, bh).is_none(),
20282 "{bw}x{bh} is past av1_filter_intra_allowed_bsize's <=32 bound"
20283 );
20284 }
20285 }
20286 use super::*;
20287
20288 /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR --
20289 /// `SCAN_4X16[i]` must name the transpose of the position
20290 /// `SCAN_16X4[i]` names (class scan-weights-cross-axis: a naive copy of
20291 /// libaom's column-major `default_scan_*` installs the transpose and only
20292 /// an asymmetric check catches it). Also pins both as permutations, and
20293 /// pins the same relation for the 32x8/8x32 luma pair this arm reuses.
20294 #[test]
20295 fn the_rect4_scans_are_transposed_pairs() {
20296 for (a, b, w, h) in [
20297 (&SCAN_16X4[..], &SCAN_4X16[..], 16usize, 4usize),
20298 (&SCAN_32X8[..], &SCAN_8X32[..], 32, 8),
20299 ] {
20300 let mut seen_a: Vec<u16> = a.to_vec();
20301 seen_a.sort_unstable();
20302 assert_eq!(
20303 seen_a,
20304 (0..(w * h) as u16).collect::<Vec<_>>(),
20305 "{w}x{h} scan is not a permutation of its positions"
20306 );
20307 for (i, (&pa, &pb)) in a.iter().zip(b.iter()).enumerate() {
20308 let (row, col) = (pa as usize / w, pa as usize % w);
20309 assert_eq!(
20310 pb as usize,
20311 col * w.min(h) + row,
20312 "scan step {i}: {w}x{h} visits (row {row}, col {col}) but its transpose \
20313 visits position {pb}"
20314 );
20315 }
20316 }
20317 }
20318
20319 /// lane-rectsplit r4 (class `enumerate-table-domain`): [`base_ctx`]'s
20320 /// `TX_CLASS_2D` arm must, over the WHOLE 5x5 domain of both rect shapes
20321 /// and the square one, return exactly what libaom's
20322 /// `av1_nz_map_ctx_offset[tx_size][coeff_idx]` holds -- the flat tables
20323 /// transcribed in [`cdf`], read at libaom's own COLUMN-major
20324 /// `coeff_idx = col * 32 + row`, i.e. `table[col][row]`. r1..r3 read them
20325 /// `[row][col]`, which is the transpose (the OTHER shape's rule, with 11
20326 /// and 16 swapped): it desynced the first superblock strip whose luma
20327 /// corner held a coefficient off the first row/column.
20328 #[test]
20329 fn base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain() {
20330 let grid = [0i32; 32 * 32];
20331 for (shape, table) in [
20332 (Some((64usize, 32usize)), &cdf::NZ_MAP_CTX_OFFSET_64X32),
20333 (Some((32, 64)), &cdf::NZ_MAP_CTX_OFFSET_32X64),
20334 (None, &cdf::NZ_MAP_CTX_OFFSET_32),
20335 ] {
20336 for row in 0..5usize {
20337 for col in 0..5usize {
20338 // An all-zero neighbourhood makes the magnitude term 0,
20339 // so `base_ctx` returns the offset itself.
20340 let got = base_ctx(&grid, 32, row, col, TxClass::TwoD, shape);
20341 let want = if row == 0 && col == 0 {
20342 0
20343 } else {
20344 table[col][row] as usize
20345 };
20346 assert_eq!(got, want, "{shape:?} at (row {row}, col {col})");
20347 }
20348 }
20349 }
20350 }
20351
20352 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
20353 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
20354 // single-purpose writers with their own skip-context rule (keyed to
20355 // superblock position, not the neighbour-tracked one every real block
20356 // uses), never reached by `encode_key_frame_with_modes` — decoding them
20357 // would need a second, throwaway context convention next to the real
20358 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
20359 // this decoder's one target, and the round-trip test below is against
20360 // that path with real quantised residual, not a synthetic all-DC frame.
20361
20362 /// [`SCAN_8X4`]/[`SCAN_4X8`] (lane-rectx r2): a bijection check alone
20363 /// cannot catch a transposed pair -- a swap of two orientation tables is
20364 /// still a bijection over the same 32 positions. This pins BOTH arrays
20365 /// at once, element-for-element, against literal transcriptions of
20366 /// libaom's real `default_scan_4x8`/`default_scan_8x4` in
20367 /// `av1/common/scan.c` (`~/.cache/aom-oracle/src`, read directly for
20368 /// this test, not re-derived from the zigzag formula). The two source
20369 /// sequences are themselves different in their own right (not equal to
20370 /// each other), so this is asymmetric in the two axes: if the repo's
20371 /// `SCAN_8X4`/`SCAN_4X8` were swapped with each other, one side of this
20372 /// assert pair would fail even though each individual array would still
20373 /// pass a same-orientation bijection test.
20374 #[test]
20375 fn scan_8x4_and_4x8_are_not_transposed_against_each_other() {
20376 // libaom `default_scan_4x8` verbatim (scan.c:29-32) -- this repo
20377 // names it `SCAN_8X4` under the established w/h axis swap (see
20378 // `SCAN_8X4`'s own doc comment).
20379 const LIBAOM_DEFAULT_SCAN_4X8: [u16; 32] = [
20380 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21,
20381 14, 7, 29, 22, 15, 30, 23, 31,
20382 ];
20383 // libaom `default_scan_8x4` verbatim (scan.c:44-47) -- this repo's
20384 // `SCAN_4X8`.
20385 const LIBAOM_DEFAULT_SCAN_8X4: [u16; 32] = [
20386 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22,
20387 25, 28, 23, 26, 29, 27, 30, 31,
20388 ];
20389 assert_ne!(
20390 LIBAOM_DEFAULT_SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4,
20391 "the two libaom source sequences must differ, or this pin would \
20392 pass regardless of a swap"
20393 );
20394 assert_eq!(SCAN_8X4, LIBAOM_DEFAULT_SCAN_4X8, "SCAN_8X4 vs libaom default_scan_4x8");
20395 assert_eq!(SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4, "SCAN_4X8 vs libaom default_scan_8x4");
20396 }
20397
20398 /// lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= 32",
20399 /// so a DC_PRED 16x8/8x16 strip reads a `use_filter_intra` flag exactly
20400 /// like a square 16x16 does. [`filter_intra_size_class_rect`] returned
20401 /// `None` at those two sizes, so the symbol was never read and the tile
20402 /// desynced from that block on (root-caused against an instrumented
20403 /// aomdec `EC_TRACE_COEFF` ladder on a real stream: identical `mode=0`/
20404 /// `uv_mode=9` values, our range 34808 vs the oracle's 40668 at the very
20405 /// next transform block).
20406 ///
20407 /// The two rows are ASYMMETRIC (9394 for 16x8, 12551 for 8x16), so this
20408 /// pin fails if the pair is ever transposed -- the shape the repo's
20409 /// scan tables already carry (`SCAN_8X4` == libaom `default_scan_4x8`).
20410 #[test]
20411 fn a_rect_strip_below_16x16_reads_its_own_filter_intra_cdf_row() {
20412 // `default_filter_intra_cdfs` (entropymode.c), indexed by BLOCK_SIZES_ALL:
20413 // [4] = BLOCK_8X16, [5] = BLOCK_16X8, [7] = BLOCK_16X32, [8] = BLOCK_32X16.
20414 const LIBAOM_8X16: u16 = 12551;
20415 const LIBAOM_16X8: u16 = 9394;
20416 let c16x8 = filter_intra_size_class_rect(16, 8).expect("16x8 reads use_filter_intra");
20417 let c8x16 = filter_intra_size_class_rect(8, 16).expect("8x16 reads use_filter_intra");
20418 assert_ne!(c16x8, c8x16, "the two orientations must not share a CDF row");
20419 assert_eq!(cdf::FILTER_INTRA[c16x8][0], LIBAOM_16X8, "16x8 filter_intra row");
20420 assert_eq!(cdf::FILTER_INTRA[c8x16][0], LIBAOM_8X16, "8x16 filter_intra row");
20421 // The sizes one class up keep their own distinct rows (lane-intradisp).
20422 assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(32, 16).unwrap()][0], 12756);
20423 assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(16, 32).unwrap()][0], 14301);
20424 // A size with a side over 32 is genuinely not allowed the flag.
20425 assert_eq!(filter_intra_size_class_rect(64, 32), None);
20426 }
20427
20428 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
20429 /// when both references sit on the same temporal side -- the three
20430 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
20431 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
20432 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
20433 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
20434 /// not just the three enumerated syntax pairs).
20435 #[test]
20436 fn is_uni_comp_ref_matches_forward_backward_sides() {
20437 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
20438 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
20439 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
20440 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
20441 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
20442 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
20443 }
20444
20445 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
20446 /// with the real second reference (lane-av1comp round 12: previously
20447 /// always cleared to `None` by `record_inter`, so the next block's own
20448 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
20449 /// -- could never see a real compound neighbour).
20450 #[test]
20451 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
20452 let mut n = Neighbours::new(4, 4, 16, 16);
20453 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
20454 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
20455 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
20456 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
20457 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
20458 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
20459 }
20460
20461 /// A below-16px leaf must clear the palette neighbour state over its own
20462 /// cell: before lane-palette2 r8 `record_palette_y_rect`'s `w / SUB` loops
20463 /// ran zero times for any sub-16 span, so `decode_leaf_rect` /
20464 /// `decode_leaf8` left a previous block's palette size and colours in the
20465 /// above/left arrays and the NEXT block read `palette_y_mode` off the
20466 /// wrong CDF row with a stale colour cache (class
20467 /// [[cdf-row-held-constant]]).
20468 #[test]
20469 fn a_sub16_leaf_after_a_palette_block_yields_palette_ctx_zero() {
20470 let mut n = Neighbours::new(4, 4, 16, 16);
20471 // A real 16x16 palette block covering SUB cell (1, 1).
20472 n.record_palette_y_rect((1, 1), 16, 16, 2, [7, 9, 0, 0, 0, 0, 0, 0]);
20473 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
20474 assert_eq!(ctx, 2, "the palette block itself must be visible");
20475 assert_eq!(cache, vec![7, 9]);
20476 // An 8x8 non-palette leaf in that same cell.
20477 n.record_palette_y_rect((1, 1), 8, 8, 0, [0u16; 8]);
20478 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
20479 assert_eq!(ctx, 0, "a sub-16 non-palette leaf must clear its own cell");
20480 assert!(cache.is_empty(), "and its stale colour cache with it");
20481 // Same for the chroma half.
20482 n.record_palette_uv_rect((1, 1), 16, 16, 2, [1, 2, 0, 0, 0, 0, 0, 0]);
20483 assert_eq!(n.palette_uv_cache((1, 1)), vec![1, 2]);
20484 n.record_palette_uv_rect((1, 1), 8, 8, 0, [0u16; 8]);
20485 assert!(n.palette_uv_cache((1, 1)).is_empty());
20486 }
20487
20488 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
20489 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
20490 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
20491 /// -- a few corner and interior points, not the whole 6x6 grid.
20492 #[test]
20493 fn compound_mode_ctx_map_matches_libaom_corners() {
20494 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
20495 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
20496 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
20497 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
20498 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
20499 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
20500 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
20501 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
20502 // exactly the ranges `find_mv_stack_compound` produces.
20503 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
20504 }
20505
20506 #[test]
20507 fn a_frame_with_no_mode_info_grid_is_refused() {
20508 assert!(
20509 decode_key_frame_tile(
20510 &[0u8; 4],
20511 0,
20512 32,
20513 32,
20514 0,
20515 128,
20516 false,
20517 &CdefParams::default(),
20518 &LoopFilterParams::default(),
20519 false,
20520 true,
20521 false,
20522 false,
20523 )
20524 .is_err()
20525 );
20526 }
20527
20528 /// Encodes and decodes one picture with `modes`, asserting the decoder's
20529 /// planes are byte-exact against the encoder's own reconstruction.
20530 fn round_trips(w: usize, h: usize, modes: &[u8]) {
20531 use crate::encode::{Encoded, Picture as Pic};
20532 let mut source = vec![0u16; w * h];
20533 for row in 0..h {
20534 for col in 0..w {
20535 source[row * w + col] = ((row * 3 + col * 5) % 251) as u16;
20536 }
20537 }
20538 let picture = Pic {
20539 width: w,
20540 height: h,
20541 y: source,
20542 u: vec![128; w * h / 4],
20543 v: vec![128; w * h / 4],
20544 };
20545 let Encoded {
20546 tile,
20547 reconstruction,
20548 mi_cols,
20549 mi_rows,
20550 base_q_idx,
20551 ..
20552 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
20553 let decoded = decode_key_frame_tile(
20554 &tile,
20555 mi_cols,
20556 mi_rows,
20557 base_q_idx,
20558 w as u32,
20559 h as u32,
20560 false,
20561 &CdefParams::default(),
20562 &LoopFilterParams::default(),
20563 false,
20564 true,
20565 false,
20566 false,
20567 )
20568 .unwrap();
20569 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
20570 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
20571 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
20572 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
20573 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
20574 }
20575
20576 #[test]
20577 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
20578 for (w, h) in [(128usize, 128usize), (192, 128)] {
20579 round_trips(w, h, &[DC_PRED as u8]);
20580 }
20581 }
20582
20583 /// Every one of the thirteen key-frame intra modes, at their base angle,
20584 /// on real (non-flat) content: the mode search picks whichever wins each
20585 /// block, so this exercises the directional edge/reach plumbing this
20586 /// decoder round adds, not just `DC_PRED`.
20587 #[test]
20588 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
20589 for (w, h) in [(128usize, 128usize), (192, 128)] {
20590 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
20591 }
20592 }
20593
20594 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
20595 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
20596 /// this decoder round adds.
20597 #[test]
20598 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
20599 for (w, h) in [(854usize, 480usize), (216, 96)] {
20600 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
20601 }
20602 }
20603
20604 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
20605 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
20606 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
20607 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
20608 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
20609 /// bit, `partition_w8` leaves).
20610 #[test]
20611 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
20612 for (w, h) in [(40usize, 32usize), (640, 360)] {
20613 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
20614 }
20615 }
20616
20617 /// A skipped block codes no residual syntax at all (spec 5.11.34):
20618 /// straight prediction on every plane. The real key-frame writer never
20619 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
20620 /// `0`), so this constructs the exact symbol sequence a writer that did
20621 /// emit it would produce, by hand, and asserts the decoded reconstruction
20622 /// is pure DC prediction (mid-grey, with no neighbours) rather than
20623 /// refusing.
20624 #[test]
20625 fn a_skipped_block_decodes_to_pure_prediction() {
20626 use crate::msac::SymbolEncoder;
20627 let mut cdfs = Cdfs::new(q_ctx_of(40));
20628 let mut enc = SymbolEncoder::new();
20629 // One whole, unsplit 64x64 superblock, coded skip = true.
20630 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
20631 enc.symbol(1, &mut cdfs.skip[0]);
20632 enc.symbol(
20633 DC_PRED,
20634 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
20635 );
20636 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
20637 let data = enc.finish();
20638 let decoded = decode_key_frame_tile(
20639 &data,
20640 16,
20641 16,
20642 40,
20643 64,
20644 64,
20645 false,
20646 &CdefParams::default(),
20647 &LoopFilterParams::default(),
20648 false,
20649 true,
20650 false,
20651 false,
20652 )
20653 .unwrap();
20654 assert!(
20655 decoded.y.iter().all(|&s| s == 128),
20656 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
20657 );
20658 }
20659
20660 /// An inter tile's SB-level `part64` used to be read and thrown away
20661 /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real
20662 /// non-SPLIT value there silently desynced the whole tile instead of
20663 /// refusing. Hand-writes a single whole superblock's `part64 = HORZ`
20664 /// symbol (never produced by this crate's own encoder, which only ever
20665 /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can)
20666 /// and asserts this decoder refuses by name rather than decoding garbage.
20667 #[test]
20668 fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
20669 use crate::msac::SymbolEncoder;
20670 let mut cdfs = Cdfs::new(q_ctx_of(40));
20671 let mut enc = SymbolEncoder::new();
20672 enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]);
20673 let data = enc.finish();
20674 let reference = crate::encode::Picture::grey(64, 64);
20675 let err = decode_inter_frame_tile(
20676 &data,
20677 16,
20678 16,
20679 40,
20680 64,
20681 64,
20682 &reference,
20683 [None; 8],
20684 &CdefParams::default(),
20685 &LoopFilterParams::default(),
20686 false,
20687 false,
20688 Some(mc::InterpFilterKind::Regular),
20689 false,
20690 false,
20691 )
20692 .unwrap_err();
20693 let msg = err.to_string();
20694 assert!(
20695 msg.contains("SPLIT"),
20696 "expected the named inter-SB-partition refusal, got: {msg}"
20697 );
20698 }
20699
20700 // ffmpeg cross-oracle: an independent decoder (not this crate's own
20701 // encoder-side reconstruction) agrees with what this module decodes,
20702 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
20703 // name (that module is another lane's territory this round, and the
20704 // helpers are `#[cfg(test)]`-private to it).
20705 use std::io::Write;
20706 use std::process::{Command, Stdio};
20707
20708 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
20709 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
20710 /// aomenc gate decodes its stream through ffmpeg and is meaningless
20711 /// without it -- turns it into a hard failure. Without this the require
20712 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
20713 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
20714 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
20715 fn have_ffmpeg() -> bool {
20716 let present = Command::new("ffmpeg")
20717 .arg("-version")
20718 .stdout(Stdio::null())
20719 .stderr(Stdio::null())
20720 .status()
20721 .is_ok_and(|s| s.success());
20722 assert!(
20723 present
20724 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
20725 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
20726 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
20727 );
20728 present
20729 }
20730
20731 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
20732 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
20733 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
20734 let mut child = Command::new("ffmpeg")
20735 .args([
20736 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
20737 ])
20738 .stdin(Stdio::piped())
20739 .stdout(Stdio::piped())
20740 .stderr(Stdio::piped())
20741 .spawn()
20742 .expect("ffmpeg failed to start");
20743 child
20744 .stdin
20745 .take()
20746 .expect("ffmpeg stdin")
20747 .write_all(stream)
20748 .expect("writing the stream to ffmpeg");
20749 let out = child.wait_with_output().expect("ffmpeg failed to run");
20750 assert!(
20751 out.status.success(),
20752 "ffmpeg refused the stream: {}",
20753 String::from_utf8_lossy(&out.stderr)
20754 );
20755 let (luma, chroma) = (width * height, width * height / 4);
20756 assert_eq!(
20757 out.stdout.len(),
20758 luma + 2 * chroma,
20759 "expected one 4:2:0 frame"
20760 );
20761 Picture {
20762 width,
20763 height,
20764 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
20765 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
20766 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
20767 }
20768 }
20769
20770 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
20771 fn ffmpeg_decode_sequence(
20772 stream: &[u8],
20773 width: usize,
20774 height: usize,
20775 frames: usize,
20776 ) -> Vec<Picture> {
20777 let mut child = Command::new("ffmpeg")
20778 .args([
20779 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
20780 ])
20781 .stdin(Stdio::piped())
20782 .stdout(Stdio::piped())
20783 .stderr(Stdio::piped())
20784 .spawn()
20785 .expect("ffmpeg failed to start");
20786 child
20787 .stdin
20788 .take()
20789 .expect("ffmpeg stdin")
20790 .write_all(stream)
20791 .expect("writing the stream to ffmpeg");
20792 let out = child.wait_with_output().expect("ffmpeg failed to run");
20793 assert!(
20794 out.status.success(),
20795 "ffmpeg refused the stream: {}",
20796 String::from_utf8_lossy(&out.stderr)
20797 );
20798 let (luma, chroma) = (width * height, width * height / 4);
20799 let frame_bytes = luma + 2 * chroma;
20800 assert_eq!(
20801 out.stdout.len(),
20802 frame_bytes * frames,
20803 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
20804 String::from_utf8_lossy(&out.stderr)
20805 );
20806 (0..frames)
20807 .map(|i| {
20808 let base = i * frame_bytes;
20809 Picture {
20810 width,
20811 height,
20812 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
20813 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
20814 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
20815 }
20816 })
20817 .collect()
20818 }
20819
20820 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
20821 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
20822 /// test binary runs callers on parallel threads, and a shared name lets
20823 /// one test's cleanup race another's still-reading ffprobe --
20824 /// pid-keyed-temp-path class).
20825 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
20826 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20827 let path = std::env::temp_dir().join(format!(
20828 "ec-av1-decode-probe-{}-{}.obu",
20829 std::process::id(),
20830 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20831 ));
20832 let _ = std::fs::remove_file(&path);
20833 std::fs::write(&path, stream).expect("writing the probe stream");
20834 let out = Command::new("ffprobe")
20835 .args([
20836 "-v",
20837 "error",
20838 "-f",
20839 "obu",
20840 "-select_streams",
20841 "v:0",
20842 "-show_entries",
20843 "stream=width,height",
20844 "-of",
20845 "csv=p=0",
20846 ])
20847 .arg(&path)
20848 .output()
20849 .expect("ffprobe failed to run");
20850 let _ = std::fs::remove_file(&path);
20851 assert!(
20852 out.status.success(),
20853 "ffprobe refused the stream: {}",
20854 String::from_utf8_lossy(&out.stderr)
20855 );
20856 let text = String::from_utf8_lossy(&out.stdout);
20857 let mut fields = text.trim().split(',');
20858 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
20859 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
20860 (width, height)
20861 }
20862
20863 /// This module's own decoder against an independent one (ffmpeg), not
20864 /// just against this crate's encoder-side reconstruction: both decoders
20865 /// read the identical tile bytes, so agreement here rules out a bug this
20866 /// crate's own writer and reader could otherwise share.
20867 #[test]
20868 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
20869 if !have_ffmpeg() {
20870 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
20871 return;
20872 }
20873 use crate::encode::encode_key_frame;
20874 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
20875 let picture = round_trip_test_card(width, height);
20876 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
20877 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
20878 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
20879 let ours = decode_key_frame_tile(
20880 &encoded.tile,
20881 encoded.mi_cols,
20882 encoded.mi_rows,
20883 encoded.base_q_idx,
20884 coded_w,
20885 coded_h,
20886 false,
20887 &CdefParams::default(),
20888 &LoopFilterParams::default(),
20889 false,
20890 true,
20891 false,
20892 false,
20893 )
20894 .unwrap();
20895 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
20896 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
20897 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
20898 }
20899 }
20900
20901 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
20902 let mut picture = crate::encode::Picture::grey(width, height);
20903 for row in 0..height {
20904 for col in 0..width {
20905 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
20906 }
20907 }
20908 for row in 0..height / 2 {
20909 for col in 0..width / 2 {
20910 let i = row * width / 2 + col;
20911 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
20912 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
20913 }
20914 }
20915 picture
20916 }
20917
20918 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
20919 let mut picture = crate::encode::Picture::grey(width, height);
20920 for y in 0..height {
20921 for x in 0..width {
20922 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
20923 let gradient = sx * 200.0 / width as f64;
20924 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
20925 }
20926 }
20927 for y in 0..height / 2 {
20928 for x in 0..width / 2 {
20929 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
20930 let i = y * width / 2 + x;
20931 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
20932 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
20933 }
20934 }
20935 picture
20936 }
20937
20938 /// A GOP (one key frame plus several inter frames, each panned so its
20939 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
20940 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
20941 /// reconstruction, frame by frame, chaining each decoded frame straight
20942 /// into the next as its reference -- exactly the single-slot DPB
20943 /// [`crate::encode::encode_sequence`] itself threads.
20944 fn gop_round_trips(width: usize, height: usize) {
20945 use crate::encode::encode_sequence;
20946 let pictures: Vec<_> = (0..4)
20947 .map(|i| panned_test_card(width, height, i * 3))
20948 .collect();
20949 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
20950 assert_eq!(encoded.frames.len(), 4);
20951
20952 let key = &encoded.frames[0];
20953 let mut reference = decode_key_frame_tile(
20954 &key.tile,
20955 key.mi_cols,
20956 key.mi_rows,
20957 key.base_q_idx,
20958 width as u32,
20959 height as u32,
20960 false,
20961 &CdefParams::default(),
20962 &LoopFilterParams::default(),
20963 false,
20964 true,
20965 false,
20966 false,
20967 )
20968 .unwrap();
20969 assert_eq!(
20970 reference.y, key.reconstruction.y,
20971 "{width}x{height} frame 0 luma"
20972 );
20973 assert_eq!(
20974 reference.u, key.reconstruction.u,
20975 "{width}x{height} frame 0 U"
20976 );
20977 assert_eq!(
20978 reference.v, key.reconstruction.v,
20979 "{width}x{height} frame 0 V"
20980 );
20981
20982 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
20983 let decoded = decode_inter_frame_tile(
20984 &frame.tile,
20985 frame.mi_cols,
20986 frame.mi_rows,
20987 frame.base_q_idx,
20988 width as u32,
20989 height as u32,
20990 &reference,
20991 [None; 8],
20992 &CdefParams::default(),
20993 &LoopFilterParams::default(),
20994 false,
20995 false,
20996 Some(mc::InterpFilterKind::Regular),
20997 false,
20998 false,
20999 )
21000 .unwrap();
21001 assert_eq!(
21002 decoded.y, frame.reconstruction.y,
21003 "{width}x{height} frame {i} luma"
21004 );
21005 assert_eq!(
21006 decoded.u, frame.reconstruction.u,
21007 "{width}x{height} frame {i} U"
21008 );
21009 assert_eq!(
21010 decoded.v, frame.reconstruction.v,
21011 "{width}x{height} frame {i} V"
21012 );
21013 reference = decoded;
21014 }
21015 }
21016
21017 #[test]
21018 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
21019 gop_round_trips(128, 64);
21020 }
21021
21022 /// Same claim, at a size that is not a whole number of 32x32 blocks
21023 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
21024 /// split path is exercised too.
21025 #[test]
21026 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
21027 gop_round_trips(216, 96);
21028 }
21029
21030 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
21031 /// this module does, frame for frame.
21032 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
21033 /// MV stack's *second* candidate (`near_mv`), not its first
21034 /// (`nearest_mv`) -- a hand-built symbol stream drives
21035 /// [`decode_inter_block`] directly, since this crate's own encoder never
21036 /// writes NEARMV (round 3: it never chooses the mode).
21037 #[test]
21038 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
21039 use crate::msac::SymbolEncoder;
21040 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
21041
21042 const LAST_FRAME: i8 = 1;
21043 let (mi_cols, mi_rows) = (12u32, 12u32);
21044 let side = 16usize; // one 16x16 leaf block
21045 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
21046 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
21047 let bw4 = side / 4;
21048
21049 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
21050 let (above_mv, left_mv) = ((4, 4), (8, 8));
21051 let neighbour = |mv| MiInfo {
21052 is_inter: true,
21053 ref_frame: LAST_FRAME,
21054 ref_frame1: None,
21055 mv1: None,
21056 mv,
21057 is_new_mv: false,
21058 size: 1,
21059 size_h: 1,
21060 is_global_mv0: false,
21061 is_global_mv1: false,
21062 };
21063 for col in mi_col..mi_col + bw4 {
21064 grid.set(mi_row - 1, col, neighbour(above_mv));
21065 }
21066 for row in mi_row..mi_row + bw4 {
21067 grid.set(row, mi_col - 1, neighbour(left_mv));
21068 }
21069
21070 let stack = find_mv_stack(
21071 &grid,
21072 mi_row,
21073 mi_col,
21074 bw4,
21075 bw4,
21076 LAST_FRAME,
21077 mi_cols as usize,
21078 mi_rows as usize,
21079 );
21080 // Sanity on the test's own setup, not the code under test: two equal-
21081 // weight candidates keep scan order (above, then left -- module doc).
21082 assert_eq!(stack.entries.len(), 2);
21083 assert_eq!(stack.nearest_mv, above_mv);
21084 assert_eq!(stack.near_mv, left_mv);
21085
21086 let (skip_ctx, ii_ctx, sr_ctx) = (
21087 0usize,
21088 intra_inter_ctx(true, true, false, false),
21089 single_ref_ctx(false),
21090 );
21091
21092 let mut cdfs = Cdfs::new(q_ctx_of(100));
21093 let mut enc = SymbolEncoder::new();
21094 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
21095 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
21096 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
21097 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
21098 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
21099 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
21100 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
21101 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
21102 let data = enc.finish();
21103
21104 let (width, height) = (64usize, 64usize);
21105 let ref_pattern: Vec<u16> = (0..width * height).map(|i| (i % 251) as u16).collect();
21106 let ref_plane = |scale: usize| PlaneBuf {
21107 data: ref_pattern
21108 .iter()
21109 .step_by(scale.max(1))
21110 .take((width / scale) * (height / scale))
21111 .copied()
21112 .collect(),
21113 width: width / scale,
21114 height: height / scale,
21115 true_width: width / scale,
21116 true_height: height / scale,
21117 tile_x0: 0,
21118 tile_y0: 0,
21119 tile_x1: width / scale,
21120 tile_y1: height / scale,
21121 };
21122 let ref_y = PlaneBuf {
21123 data: ref_pattern.clone(),
21124 width,
21125 height,
21126 true_width: width,
21127 true_height: height,
21128 tile_x0: 0,
21129 tile_y0: 0,
21130 tile_x1: width,
21131 tile_y1: height,
21132 };
21133 let ref_u = ref_plane(2);
21134 let ref_v = ref_plane(2);
21135
21136 let mut y = PlaneBuf {
21137 data: vec![0u16; width * height],
21138 width,
21139 height,
21140 true_width: width,
21141 true_height: height,
21142 tile_x0: 0,
21143 tile_y0: 0,
21144 tile_x1: width,
21145 tile_y1: height,
21146 };
21147 let mut u = PlaneBuf {
21148 data: vec![0u16; (width / 2) * (height / 2)],
21149 width: width / 2,
21150 height: height / 2,
21151 true_width: width / 2,
21152 true_height: height / 2,
21153 tile_x0: 0,
21154 tile_y0: 0,
21155 tile_x1: width / 2,
21156 tile_y1: height / 2,
21157 };
21158 let mut v = PlaneBuf {
21159 data: vec![0u16; (width / 2) * (height / 2)],
21160 width: width / 2,
21161 height: height / 2,
21162 true_width: width / 2,
21163 true_height: height / 2,
21164 tile_x0: 0,
21165 tile_y0: 0,
21166 tile_x1: width / 2,
21167 tile_y1: height / 2,
21168 };
21169
21170 let mut cdfs = Cdfs::new(q_ctx_of(100));
21171 let mut dec = SymbolDecoder::new(&data);
21172 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
21173 decode_inter_block(
21174 &mut dec,
21175 &mut cdfs,
21176 &mut neighbours,
21177 &mut grid,
21178 (r, c),
21179 side,
21180 mi_cols,
21181 mi_rows,
21182 &mut y,
21183 &mut u,
21184 &mut v,
21185 &ref_y,
21186 &ref_u,
21187 &ref_v,
21188 &[None; 8],
21189 &NO_SIGN_BIAS,
21190 &[ec_av1_syntax::WarpParams::default(); 7],
21191 100,
21192 TxbSet::Luma16,
21193 TxbSet::Luma16Inter,
21194 TxbSet::Chroma8,
21195 TX16,
21196 TX8,
21197 &[],
21198 &[],
21199 0,
21200 false,
21201 false,
21202 Some(mc::InterpFilterKind::Regular),
21203 false,
21204 None,
21205 false,
21206 false,
21207 false,
21208 false,
21209 0,
21210 0,
21211 [0; 7],
21212 false,
21213 [0; 2],
21214 false,
21215 false,
21216 false,
21217 side,
21218 side,
21219 false,
21220 width,
21221 )
21222 .unwrap();
21223
21224 let (px, py) = (c * SUB, r * SUB);
21225 let mut want_near = vec![0u16; side * side];
21226 crate::mc::predict(
21227 &ref_y.data,
21228 ref_y.width,
21229 ref_y.true_width,
21230 ref_y.true_height,
21231 mv_to_q4(px, left_mv.1, true),
21232 mv_to_q4(py, left_mv.0, true),
21233 side,
21234 side,
21235 &mut want_near,
21236 );
21237 let mut want_nearest = vec![0u16; side * side];
21238 crate::mc::predict(
21239 &ref_y.data,
21240 ref_y.width,
21241 ref_y.true_width,
21242 ref_y.true_height,
21243 mv_to_q4(px, above_mv.1, true),
21244 mv_to_q4(py, above_mv.0, true),
21245 side,
21246 side,
21247 &mut want_nearest,
21248 );
21249 assert_ne!(
21250 want_near, want_nearest,
21251 "test setup: the two candidate MVs must predict differently"
21252 );
21253
21254 let mut got = vec![0u16; side * side];
21255 for row in 0..side {
21256 got[row * side..(row + 1) * side].copy_from_slice(
21257 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
21258 );
21259 }
21260 assert_eq!(
21261 got, want_near,
21262 "NEARMV predicted from the wrong stack entry"
21263 );
21264 }
21265
21266 #[test]
21267 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
21268 if !have_ffmpeg() {
21269 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
21270 return;
21271 }
21272 use crate::encode::encode_sequence;
21273 let (width, height) = (128usize, 64usize);
21274 let pictures: Vec<_> = (0..3)
21275 .map(|i| panned_test_card(width, height, i * 3))
21276 .collect();
21277 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
21278 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
21279 let ffmpeg_frames =
21280 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
21281
21282 let key = &encoded.frames[0];
21283 let mut reference = decode_key_frame_tile(
21284 &key.tile,
21285 key.mi_cols,
21286 key.mi_rows,
21287 key.base_q_idx,
21288 coded_w,
21289 coded_h,
21290 false,
21291 &CdefParams::default(),
21292 &LoopFilterParams::default(),
21293 false,
21294 true,
21295 false,
21296 false,
21297 )
21298 .unwrap();
21299 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
21300
21301 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
21302 let decoded = decode_inter_frame_tile(
21303 &frame.tile,
21304 frame.mi_cols,
21305 frame.mi_rows,
21306 frame.base_q_idx,
21307 coded_w,
21308 coded_h,
21309 &reference,
21310 [None; 8],
21311 &CdefParams::default(),
21312 &LoopFilterParams::default(),
21313 false,
21314 false,
21315 Some(mc::InterpFilterKind::Regular),
21316 false,
21317 false,
21318 )
21319 .unwrap();
21320 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
21321 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
21322 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
21323 reference = decoded;
21324 }
21325 }
21326}
21327
21328#[cfg(test)]
21329mod tx4x8_table_tests {
21330 use super::*;
21331
21332 /// Asymmetric gate on the two new scan tables (class
21333 /// `reference-layout-not-spec`): a transposed pair of tables passes any
21334 /// "is a permutation" check, so this pins the pair AGAINST each other --
21335 /// `SCAN_8X4[k]` must be `SCAN_4X8[k]` reflected across the diagonal, and
21336 /// both must be bijections of `0..32` in our own row-major indexing.
21337 #[test]
21338 fn the_rect_4x8_scans_are_each_other_transposed() {
21339 let mut seen_a = [false; 32];
21340 let mut seen_b = [false; 32];
21341 for k in 0..32usize {
21342 let a = SCAN_4X8[k] as usize;
21343 let b = SCAN_8X4[k] as usize;
21344 assert!(!seen_a[a] && !seen_b[b], "scan position {k} repeats");
21345 seen_a[a] = true;
21346 seen_b[b] = true;
21347 let (row, col) = (a / 4, a % 4);
21348 assert_eq!(b, col * 8 + row, "SCAN_8X4[{k}] is not SCAN_4X8[{k}] transposed");
21349 }
21350 assert!(seen_a.iter().all(|&s| s) && seen_b.iter().all(|&s| s));
21351 }
21352
21353 /// `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/`mcol_scan_8x4`
21354 /// (libaom `scan.c`), converted out of their column-major encoding by
21355 /// `(p % h) * w + p / h` -- the head of each, pinned so the rect
21356 /// `V_DCT`/`H_DCT` walk cannot silently transpose.
21357 #[test]
21358 fn the_rect_class1_scans_match_libaom() {
21359 assert_eq!(
21360 class_scan_table_wh(4, 8, TxClass::Vert),
21361 (0..32u16).collect::<Vec<_>>()
21362 );
21363 assert_eq!(
21364 &class_scan_table_wh(4, 8, TxClass::Horiz)[..8],
21365 &[0u16, 4, 8, 12, 16, 20, 24, 28]
21366 );
21367 assert_eq!(
21368 class_scan_table_wh(8, 4, TxClass::Vert),
21369 (0..32u16).collect::<Vec<_>>()
21370 );
21371 assert_eq!(
21372 &class_scan_table_wh(8, 4, TxClass::Horiz)[..8],
21373 &[0u16, 8, 16, 24, 1, 9, 17, 25]
21374 );
21375 }
21376
21377 /// The 32-position `eob_pt` alphabet: six symbols (one more than the
21378 /// 16-position table, one fewer than the 64-position one), strictly
21379 /// increasing, terminated at 32768 with the adaptation counter after it.
21380 #[test]
21381 fn the_32_position_eob_tables_are_well_formed() {
21382 for table in [
21383 &cdf::EOB_PT_32_LUMA_Q0,
21384 &cdf::EOB_PT_32_LUMA_Q1,
21385 &cdf::EOB_PT_32_LUMA,
21386 &cdf::EOB_PT_32_LUMA_Q3,
21387 &cdf::EOB_PT_32_LUMA_CLASS1_Q0,
21388 &cdf::EOB_PT_32_LUMA_CLASS1_Q1,
21389 &cdf::EOB_PT_32_LUMA_CLASS1,
21390 &cdf::EOB_PT_32_LUMA_CLASS1_Q3,
21391 ] {
21392 assert_eq!(table.len(), 7);
21393 assert_eq!(table[5], 32768);
21394 assert_eq!(table[6], 0);
21395 for w in table[..6].windows(2) {
21396 assert!(w[0] < w[1], "{table:?} is not increasing");
21397 }
21398 }
21399 }
21400
21401 /// `Reach::of_rect` must read libaom's own `has_tr_4x8`/`has_tr_8x4`
21402 /// rows, not the 32x16 pair the two existing rect strips use: the two
21403 /// shapes disagree at a position inside the superblock, which is what
21404 /// makes this an asymmetric check rather than a tautology.
21405 #[test]
21406 fn the_sub8_rect_reach_tables_are_shape_specific() {
21407 let a = Reach::of_rect(4, 8, 4, 8, 64, 64);
21408 let b = Reach::of_rect(8, 4, 8, 4, 64, 64);
21409 assert!(
21410 a.above_right != b.above_right || a.below_left != b.below_left,
21411 "4x8 and 8x4 reach identically at mirrored positions -- one table is unused"
21412 );
21413 }
21414}