forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB231663eTahinli3 months ago1475 commits

decode.rs20653 lines, 884.4 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).
81fn 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-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
132// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
133// frame-level flag through the recursive block decode -- `0` (the default)
134// makes every call a true no-op, matching every existing gate stream's
135// `cdef_bits == 0` behaviour exactly.
136thread_local! {
137 static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
138}
139// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
140// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
141// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
142// blocks every non-8-bit stream from reaching a decode call, so this is `8`
143// on every path that runs today -- threading it now (rather than the literal
144// `8`) is stage 1 of widening past that refusal without re-deriving every
145// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
146// depth (this decoder's own internal choice, matches dav1d/libaom).
147thread_local! {
148 static BIT_DEPTH: std::cell::Cell<u8> = const { std::cell::Cell::new(8) };
149}
150/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
151/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
152pub(crate) fn sample_max() -> i32 {
153 (1i32 << BIT_DEPTH.with(std::cell::Cell::get)) - 1
154}
155/// The current stream's bit depth, for callers (e.g. dequant) that need the
156/// raw value rather than the derived clamp bound.
157pub(crate) fn bit_depth() -> u8 {
158 BIT_DEPTH.with(std::cell::Cell::get)
159}
160/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
161/// [`crate::stream`]'s decode loop.
162pub(crate) fn set_bit_depth(bit_depth: u8) {
163 BIT_DEPTH.with(|c| c.set(bit_depth));
164}
165// Whether this superblock's single CDEF unit (this decoder has no 128x128
166// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
167// read -- reset to `false` at the top of each superblock in the two tile
168// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
169thread_local! {
170 static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
171}
172// Number of superblock columns in the current tile's grid, so
173// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
174// [`CDEF_IDX_GRID`].
175thread_local! {
176 static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
177}
178// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
179// which of the header's `1 << cdef.bits` strength pairs applies to that
180// superblock's samples.
181thread_local! {
182 static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
183}
184// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
185// has read, across every call on the current thread -- the gate's proof that a
186// `cdef_bits > 0` stream actually reached the new reader rather than every
187// superblock coincidentally being all-skip.
188thread_local! {
189 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
190}
191
192/// Current value of [`CDEF_IDX_HITS`].
193pub(crate) fn cdef_idx_hits() -> usize {
194 CDEF_IDX_HITS.with(|c| c.get())
195}
196
197// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
198// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
199// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
200// true no-op, matching every existing gate stream's `delta_q_present == 0`
201// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
202thread_local! {
203 static DELTA_Q_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
204 static DELTA_Q_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
205}
206// The running quantizer index (spec `CurrentQIndex`, libaom
207// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
208// top of every tile (spec `decode_tile`), carried across superblocks within
209// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
210// dequantization call sites instead of the frame-constant `base_q_idx`.
211thread_local! {
212 static CURRENT_Q_IDX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
213}
214// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
215// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
216// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
217// back at every dequantization call site keyed on which plane it is doing.
218thread_local! {
219 static QUANT_DELTAS: std::cell::Cell<crate::quant::QuantDeltas> = const {
220 std::cell::Cell::new(crate::quant::QuantDeltas {
221 y_dc: 0,
222 u_dc: 0,
223 u_ac: 0,
224 v_dc: 0,
225 v_ac: 0,
226 })
227 };
228}
229// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
230// read, across every call on the current thread -- the gate's proof that a
231// `delta_q_present` stream actually reached the new reader.
232thread_local! {
233 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
234}
235
236/// Current value of [`DELTA_Q_HITS`].
237pub(crate) fn delta_q_hits() -> usize {
238 DELTA_Q_HITS.with(|c| c.get())
239}
240
241/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
242/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
243/// one), so it is always `0` here.
244fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
245 let d = QUANT_DELTAS.with(|c| c.get());
246 match plane_idx {
247 0 => (d.y_dc, 0),
248 1 => (d.u_dc, d.u_ac),
249 _ => (d.v_dc, d.v_ac),
250 }
251}
252
253/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
254/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
255/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
256/// A no-op when `delta_q_present` is unset, or when this block is not at the
257/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
258/// libaom, collapsed here to a position check since a partition tree's
259/// top-left leaf is the only block that can ever land there), or when that
260/// leaf both *is* the whole superblock and is `skip` (the one case libaom
261/// itself skips the read, state carrying over unchanged).
262fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
263 if !DELTA_Q_PRESENT.with(|c| c.get()) {
264 return;
265 }
266 let sb_mi = sb_mi_cur() as usize;
267 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
268 return;
269 }
270 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, which
271 // it computes against the 64x64 root; under a 128 superblock no leaf this
272 // decoder codes can be the whole superblock (the root is always SPLIT).
273 if is_whole_sb && !sb128() && skip {
274 return;
275 }
276 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
277 const DELTA_Q_SMALL: i32 = 3;
278 if abs >= DELTA_Q_SMALL {
279 let rem_bits = dec.literal(3) + 1;
280 let thr = (1i32 << rem_bits) + 1;
281 abs = dec.literal(rem_bits) as i32 + thr;
282 }
283 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
284 let reduced = if sign_negative { -abs } else { abs };
285 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
286 let res = DELTA_Q_RES.with(|c| c.get());
287 CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
288}
289
290// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
291// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
292thread_local! {
293 static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
294 static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
295 static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
296}
297// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
298// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
299// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
300// updates index 0 and every reader treats that as the value for all 4
301// indices (spec `read_delta_lf_params`'s own single-cdf branch).
302thread_local! {
303 static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
304}
305// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
306// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
307thread_local! {
308 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
309}
310
311/// Current value of [`DELTA_LF_HITS`].
312pub(crate) fn delta_lf_hits() -> usize {
313 DELTA_LF_HITS.with(|c| c.get())
314}
315
316/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
317/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
318/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
319/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
320/// read once into index 0 otherwise.
321fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
322 if !DELTA_LF_PRESENT.with(|c| c.get()) {
323 return;
324 }
325 let sb_mi = sb_mi_cur() as usize;
326 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
327 return;
328 }
329 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, which
330 // it computes against the 64x64 root; under a 128 superblock no leaf this
331 // decoder codes can be the whole superblock (the root is always SPLIT).
332 if is_whole_sb && !sb128() && skip {
333 return;
334 }
335 let multi = DELTA_LF_MULTI.with(|c| c.get());
336 let res = DELTA_LF_RES.with(|c| c.get());
337 let count = if multi { 4 } else { 1 };
338 let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
339 for i in 0..count {
340 let mut abs = if multi {
341 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
342 } else {
343 dec.symbol(&mut cdfs.delta_lf) as i32
344 };
345 const DELTA_LF_SMALL: i32 = 3;
346 if abs >= DELTA_LF_SMALL {
347 let rem_bits = dec.literal(3) + 1;
348 let thr = (1i32 << rem_bits) + 1;
349 abs = dec.literal(rem_bits) as i32 + thr;
350 }
351 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
352 let reduced = if sign_negative { -abs } else { abs };
353 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
354 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
355 }
356 CURRENT_DELTA_LF.with(|c| c.set(cur));
357}
358
359/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
360/// after `skip` is known at every block-decode call site. A no-op at
361/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
362/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
363/// `allow_intrabc`, so neither needs a separate check here. Reads once per
364/// superblock, at the first non-skip block.
365fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
366 let bits = CDEF_BITS.with(|c| c.get());
367 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
368 return;
369 }
370 let idx = dec.literal(u32::from(bits)) as u8;
371 CDEF_TRANSMITTED.with(|c| c.set(true));
372 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
373 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
374 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
375 if sb_cols > 0 {
376 CDEF_IDX_GRID.with(|g| {
377 let mut g = g.borrow_mut();
378 let i = sb_r * sb_cols + sb_c;
379 if i < g.len() {
380 g[i] = idx;
381 }
382 });
383 }
384}
385
386// ---------------------------------------------------------------------------
387// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
388// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
389// the two consumers a real stream exercises: the per-segment quantizer index
390// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
391// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
392// `read_intra_segment_id`/`read_inter_segment_id` and
393// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
394// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
395// is what the oracle every gate here compares against actually does.
396thread_local! {
397 static SEG: std::cell::RefCell<SegmentationParams> =
398 std::cell::RefCell::new(SegmentationParams::default());
399 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
400 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
401 static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
402 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
403 /// this frame has no primary reference (spec `load_previous_segment_ids`).
404 static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
405 /// `(mi_rows, mi_cols)` for both maps above.
406 static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
407 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
408 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
409 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
410 static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
411 static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
412 /// The block currently being decoded -- read back by [`block_q_idx`].
413 static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
414 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
415 static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
416 /// How many real `segment_id` symbols were read, and the set of segment
417 /// ids any block ended up with -- the gate's proof the feature fired.
418 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
419 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
420 /// How many `seg_id_predicted` symbols were read (temporal update).
421 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
422}
423
424/// Installs this frame's segmentation parameters and allocates its map, with
425/// `prev` the primary reference frame's saved map (spec
426/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
427/// slot). Called once per frame, whether or not segmentation is enabled.
428pub(crate) fn set_segmentation(
429 seg: SegmentationParams,
430 mi_rows: usize,
431 mi_cols: usize,
432 prev: Option<&[u8]>,
433) {
434 SEG.with(|s| *s.borrow_mut() = seg);
435 SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));
436 SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
437 PREV_SEG_IDS.with(|m| {
438 let mut m = m.borrow_mut();
439 m.clear();
440 if let Some(p) = prev {
441 if p.len() == mi_rows * mi_cols {
442 m.extend_from_slice(p);
443 }
444 }
445 });
446 ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
447 LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
448 CUR_SEGMENT_ID.with(|c| c.set(0));
449}
450
451/// This frame's decoded segment map, to be stored into whichever reference
452/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
453pub(crate) fn take_segment_ids() -> Vec<u8> {
454 SEG_IDS.with(|m| m.borrow().clone())
455}
456
457/// How many `segment_id` symbols have been read (never reset per frame).
458pub(crate) fn segment_id_hits() -> usize {
459 SEG_ID_HITS.with(|c| c.get())
460}
461
462/// How many distinct segment ids any decoded block has carried.
463pub(crate) fn segment_ids_seen() -> usize {
464 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
465}
466
467/// How many `seg_id_predicted` symbols have been read (temporal update).
468pub(crate) fn segment_pred_hits() -> usize {
469 SEG_PRED_HITS.with(|c| c.get())
470}
471
472/// Resets the segmentation hit counters (gate setup).
473pub(crate) fn reset_segment_hits() {
474 SEG_ID_HITS.with(|c| c.set(0));
475 SEG_IDS_SEEN.with(|c| c.set(0));
476 SEG_PRED_HITS.with(|c| c.set(0));
477}
478
479/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
480/// being decoded, with its `FeatureData` value.
481fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
482 SEG.with(|s| {
483 let s = s.borrow();
484 s.feature_active(segment_id, feature)
485 .then(|| i32::from(s.feature_data[segment_id][feature]))
486 })
487}
488
489/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
490/// `av1_get_qindex`) for the block currently being decoded: the running
491/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
492/// Every dequant call site reads the block's quantizer through here.
493fn block_q_idx() -> i32 {
494 let base = CURRENT_Q_IDX.with(|c| c.get());
495 let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
496 match seg_feature(seg_id, SEG_LVL_ALT_Q) {
497 Some(data) => (base + data).clamp(0, 255),
498 None => base,
499 }
500}
501
502/// The segment id recorded for one mi cell of the current frame's map.
503fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {
504 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
505 if mi_r >= mi_rows || mi_c >= mi_cols {
506 return 0;
507 }
508 SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
509}
510
511/// `set_segment_id`: stamps `id` over every mi cell this block covers.
512fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {
513 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
514 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
515 SEG_IDS.with(|m| {
516 let mut m = m.borrow_mut();
517 for y in 0..y_mis {
518 for x in 0..x_mis {
519 m[(mi_r + y) * mi_cols + mi_c + x] = id;
520 }
521 }
522 });
523 CUR_SEGMENT_ID.with(|c| c.set(id));
524 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
525}
526
527/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
528/// `last_frame_seg_map`): the minimum previous-frame segment id over the
529/// block's own mi footprint. `0` when there is no previous map.
530fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {
531 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
532 PREV_SEG_IDS.with(|m| {
533 let m = m.borrow();
534 if m.is_empty() {
535 return 0;
536 }
537 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
538 let mut id = u8::MAX;
539 for y in 0..y_mis {
540 for x in 0..x_mis {
541 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
542 }
543 }
544 if id == u8::MAX { 0 } else { id }
545 })
546}
547
548/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
549fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
550 if reference == 0 {
551 return diff;
552 }
553 if reference >= max - 1 {
554 return max - diff - 1;
555 }
556 let half = if 2 * reference < max {
557 diff <= 2 * reference
558 } else {
559 diff <= 2 * (max - reference - 1)
560 };
561 if half {
562 return if diff & 1 != 0 {
563 reference + ((diff + 1) >> 1)
564 } else {
565 reference - (diff >> 1)
566 };
567 }
568 if 2 * reference < max { diff } else { max - (diff + 1) }
569}
570
571/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
572/// frame's already-decoded above/left/above-left neighbours.
573fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
574 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
575 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
576 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));
577 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
578 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
579 let ctx = match prev_ul {
580 None => 0,
581 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
582 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
583 Some(_) => 0,
584 };
585 let pred = match (prev_u, prev_l) {
586 (None, l) => l.unwrap_or(0),
587 (Some(u), None) => u,
588 (Some(u), Some(l)) => {
589 if prev_ul == Some(u) {
590 u
591 } else {
592 l
593 }
594 }
595 };
596 (pred, ctx)
597}
598
599/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
600/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
601/// that prediction. Does NOT write the map -- callers do.
602fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {
603 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
604 if skip {
605 return pred as u8;
606 }
607 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
608 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
609 let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));
610 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
611}
612
613/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
614/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
615/// caller decides which by passing `pre_skip`).
616fn intra_segment_id(
617 dec: &mut SymbolDecoder,
618 cdfs: &mut Cdfs,
619 mi_r: usize,
620 mi_c: usize,
621 w_mi: usize,
622 h_mi: usize,
623 skip: bool,
624) {
625 if !SEG.with(|s| s.borrow().enabled) {
626 return;
627 }
628 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
629 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
630}
631
632/// Whether this frame's intra blocks read their `segment_id` before `skip`
633/// (`SegIdPreSkip`); `false` also when segmentation is off.
634fn seg_id_pre_skip() -> bool {
635 SEG.with(|s| {
636 let s = s.borrow();
637 s.enabled && s.seg_id_pre_skip
638 })
639}
640
641/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
642/// Called at both spec positions of an inter frame's block: `pre_skip = true`
643/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
644fn inter_segment_id(
645 dec: &mut SymbolDecoder,
646 cdfs: &mut Cdfs,
647 mi_r: usize,
648 mi_c: usize,
649 w_mi: usize,
650 h_mi: usize,
651 skip: bool,
652 pre_skip: bool,
653) {
654 let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
655 let s = s.borrow();
656 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
657 });
658 if !enabled {
659 return;
660 }
661 if !update_map {
662 // The map is inherited wholesale from the previous frame.
663 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
664 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
665 return;
666 }
667 if pre_skip && !pre_skip_frame {
668 return;
669 }
670 if !pre_skip && skip {
671 // libaom: a skipped block never codes `seg_id_predicted`, and its
672 // segment id is the spatial prediction.
673 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
674 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
675 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
676 return;
677 }
678 let id = if temporal_update {
679 let ctx = seg_pred_ctx(mi_r, mi_c);
680 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
681 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
682 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));
683 if predicted {
684 predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
685 } else {
686 read_segment_id(dec, cdfs, mi_r, mi_c, false)
687 }
688 } else {
689 read_segment_id(dec, cdfs, mi_r, mi_c, false)
690 };
691 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
692}
693
694/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
695fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
696 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
697 // so contribute 0) outside the tile -- the availability check here is
698 // what keeps a previous tile's stamps out of this tile's context.
699 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
700 let above = if mi_r > row0 {
701 ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
702 } else {
703 0
704 };
705 let left = if mi_c > col0 {
706 LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
707 } else {
708 0
709 };
710 usize::from(above + left)
711}
712
713/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
714fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {
715 ABOVE_SEG_PRED.with(|m| {
716 let mut m = m.borrow_mut();
717 for i in 0..w_mi {
718 if let Some(cell) = m.get_mut(mi_c + i) {
719 *cell = value;
720 }
721 }
722 });
723 LEFT_SEG_PRED.with(|m| {
724 let mut m = m.borrow_mut();
725 for i in 0..h_mi {
726 if let Some(cell) = m.get_mut(mi_r + i) {
727 *cell = value;
728 }
729 }
730 });
731}
732
733// How many key-frame luma blocks resolved `smooth_neighbor` (spec
734// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
735// counter, proving a stream actually put a directional block next to a
736// smooth-predicted neighbour rather than every block reading the (previously
737// hardcoded `false`) edge-filter strength bucket unchanged.
738thread_local! {
739 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
740 const { std::cell::Cell::new(0) };
741}
742
743/// Current value of [`SMOOTH_LUMA_HITS`].
744pub(crate) fn smooth_luma_hits() -> usize {
745 SMOOTH_LUMA_HITS.with(|c| c.get())
746}
747
748thread_local! {
749 /// lane-band46 r1: how many split-transform units answered their intra
750 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
751 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
752 /// apply to them (class reach-is-per-transform-unit). Every hit is a
753 /// transform unit whose above-right / below-left reference samples would
754 /// be wrong without that fix.
755 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
756 const { std::cell::Cell::new(0) };
757}
758
759/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
760pub(crate) fn split_tu_reach_fix_hits() -> usize {
761 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
762}
763
764/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
765/// answer differs from the standalone-block answer the call sites used before
766/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
767/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
768/// block's top-left `(px, py)`.
769#[allow(clippy::too_many_arguments)]
770fn tu_reach(
771 bw: usize,
772 bh: usize,
773 col_off: usize,
774 row_off: usize,
775 tx: usize,
776 block: Reach,
777 px: usize,
778 py: usize,
779 width: usize,
780 height: usize,
781) -> Reach {
782 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, block);
783 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height);
784 if fixed != standalone {
785 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));
786 }
787 fixed
788}
789
790// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
791// across every call on the current thread -- lane-chroma r3's own before/after
792// counter, proving a stream actually exercised chroma's smooth/paeth
793// predictor (the previously-refused round-2 gap) rather than every block
794// landing on DC/CFL/directional.
795thread_local! {
796 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
797 const { std::cell::Cell::new(0) };
798}
799
800/// Current value of [`SMOOTH_UV_HITS`].
801pub(crate) fn smooth_uv_hits() -> usize {
802 SMOOTH_UV_HITS.with(|c| c.get())
803}
804
805// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
806// full superblock walk over, across every call on the current thread --
807// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
808// multi-tile stream must prove more than one tile actually fired, not just
809// that the stream carried tile_info.cols > 1.
810thread_local! {
811 static TILE_HITS: std::cell::Cell<usize> =
812 const { std::cell::Cell::new(0) };
813}
814/// Current value of [`TILE_HITS`].
815pub(crate) fn tile_hits() -> usize {
816 TILE_HITS.with(|c| c.get())
817}
818
819// How many 4-pixel deblocking edge groups [`edge_params`] has actually
820// selected for filtering, across every call on the current thread -- the same
821// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
822// exercised `apply_deblock` rather than every edge landing on level 0.
823thread_local! {
824 static DEBLOCK_HITS: std::cell::Cell<usize> =
825 const { std::cell::Cell::new(0) };
826}
827/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
828/// mirroring stream.rs's `pictures_decoded` so the two dumps index
829/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
830static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
831 std::sync::atomic::AtomicUsize::new(0);
832
833/// Current value of [`DEBLOCK_HITS`].
834pub(crate) fn deblock_hits() -> usize {
835 DEBLOCK_HITS.with(|c| c.get())
836}
837
838// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
839// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
840// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
841// stream built with `--enable-onesided-comp=1` really exercised the
842// `uni_comp_ref` alphabet rather than only bidirectional pairs.
843thread_local! {
844 static UNI_COMP_HITS: std::cell::Cell<usize> =
845 const { std::cell::Cell::new(0) };
846}
847
848/// Current value of [`UNI_COMP_HITS`].
849pub(crate) fn uni_comp_hits() -> usize {
850 UNI_COMP_HITS.with(|c| c.get())
851}
852
853// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
854// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
855// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
856// blend and not only the wedge arm.
857thread_local! {
858 static DIFFWTD_HITS: std::cell::Cell<usize> =
859 const { std::cell::Cell::new(0) };
860}
861
862/// Current value of [`DIFFWTD_HITS`].
863pub(crate) fn diffwtd_hits() -> usize {
864 DIFFWTD_HITS.with(|c| c.get())
865}
866
867// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
868// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
869// this decoder's square inter path reaches), so no `compound_type` symbol is
870// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
871// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
872thread_local! {
873 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
874 const { std::cell::Cell::new(0) };
875}
876
877/// Current value of [`DIFFWTD_INFERRED_HITS`].
878pub(crate) fn diffwtd_inferred_hits() -> usize {
879 DIFFWTD_INFERRED_HITS.with(|c| c.get())
880}
881
882// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
883// with `show_frame == 0`, output later by a `show_existing_frame` header
884// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
885// `stream::decode_stream`, which is where the frame header is consumed; the
886// gate's proof that the on-value really reached the bitstream rather than
887// being dropped by the rate control.
888thread_local! {
889 static FWD_KF_HITS: std::cell::Cell<usize> =
890 const { std::cell::Cell::new(0) };
891}
892
893/// Current value of [`FWD_KF_HITS`].
894pub(crate) fn fwd_kf_hits() -> usize {
895 FWD_KF_HITS.with(|c| c.get())
896}
897
898/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
899pub(crate) fn note_fwd_kf() {
900 FWD_KF_HITS.with(|c| c.set(c.get() + 1));
901}
902
903// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
904// the block's own side, across every call on the current thread -- the same
905// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
906// actually exercised a *split* transform under `TxMode::Select` rather than
907// every block coincidentally resolving `depth=0` (indistinguishable from
908// `TxMode::Largest` pixel-wise).
909thread_local! {
910 static TX_DEPTH_HITS: std::cell::Cell<usize> =
911 const { std::cell::Cell::new(0) };
912}
913
914// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
915// transform smaller than their own side (`tx_depth != 0`) while coding a
916// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
917// only exercises with aomenc's tx-size search left ON (its default), which
918// every older recipe in this file pins off. Counted at the block, so a stream
919// where RD happened to give every split-transform block a DC chroma mode
920// reads as zero rather than silently passing for free.
921thread_local! {
922 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
923 const { std::cell::Cell::new(0) };
924}
925
926/// Current value of [`SQ_CHROMA_TX_HITS`].
927pub(crate) fn sq_chroma_tx_hits() -> usize {
928 SQ_CHROMA_TX_HITS.with(|c| c.get())
929}
930
931/// Current value of [`TX_DEPTH_HITS`].
932pub(crate) fn tx_depth_hits() -> usize {
933 TX_DEPTH_HITS.with(|c| c.get())
934}
935
936// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
937// read, and how many of those actually took the split, on the current thread
938// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
939// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
940// coincidentally coding one whole-block transform.
941thread_local! {
942 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
943 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
944 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
945 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
946 // `decode_inter_block` already carries forty parameters and both are
947 // frame-constant.
948 static TX_SELECT_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
949 static REDUCED_TX_SET_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
950}
951
952/// Current value of [`TXFM_SPLIT_READS`].
953pub(crate) fn txfm_split_reads() -> usize {
954 TXFM_SPLIT_READS.with(|c| c.get())
955}
956
957/// Current value of [`TXFM_SPLIT_HITS`].
958pub(crate) fn txfm_split_hits() -> usize {
959 TXFM_SPLIT_HITS.with(|c| c.get())
960}
961
962/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`].
963pub(crate) fn set_inter_tx_mode(tx_select: bool, reduced_tx_set: bool) {
964 TX_SELECT_INTER.with(|c| c.set(tx_select));
965 REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));
966}
967
968// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
969// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
970// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
971// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
972// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
973// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
974// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
975// path above).
976thread_local! {
977 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
978 const { std::cell::Cell::new(0) };
979}
980
981/// Current value of [`VERT_B_INTRA_HITS`].
982pub(crate) fn vert_b_intra_hits() -> usize {
983 VERT_B_INTRA_HITS.with(|c| c.get())
984}
985
986// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
987// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
988// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
989// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
990// every arm separately so a run where aomenc's RD only picked one cannot
991// pass as proof of four.
992thread_local! {
993 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
994}
995
996/// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
997thread_local! {
998 /// 4x4 transform units decoded inside an 8x8 square of a
999 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1000 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1001 /// a real `--enable-tx-size-search=1` stream reaches it.
1002 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1003}
1004
1005pub(crate) fn vert_ab_tx4_hits() -> usize {
1006 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1007}
1008
1009pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1010 AB16_HITS.with(std::cell::Cell::get)
1011}
1012
1013fn bump_ab16(arm: usize) {
1014 AB16_HITS.with(|c| {
1015 let mut v = c.get();
1016 v[arm] += 1;
1017 c.set(v);
1018 });
1019}
1020
1021// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1022// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1023// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1024// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1025// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1026// superblock's z-order recursion, not raster mi position).
1027thread_local! {
1028 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1029 const { std::cell::Cell::new(0) };
1030}
1031
1032/// Current value of [`HORZ_VERT_INTRA_HITS`].
1033pub(crate) fn horz_vert_intra_hits() -> usize {
1034 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1035}
1036
1037// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1038// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1039// the case every rect path here refused by name before, and the first
1040// refusal the user's ReelB extract (600s in) stops at.
1041thread_local! {
1042 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1043 const { std::cell::Cell::new(0) };
1044}
1045
1046/// Current value of [`RECT_SPLIT_TX_HITS`].
1047pub(crate) fn rect_split_tx_hits() -> usize {
1048 RECT_SPLIT_TX_HITS.with(|c| c.get())
1049}
1050
1051// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1052// side 64) AND split past the first depth, i.e. tiled more than one unit in
1053// each axis -- the only shape with a transform unit that has neighbours on
1054// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1055// no gate fired before lane-rectsplit r2 (the shared counter above also
1056// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1057thread_local! {
1058 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1059 const { std::cell::Cell::new(0) };
1060}
1061
1062/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1063pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1064 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1065}
1066
1067// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1068// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1069// chroma half takes that had no coefficient tables before (index order:
1070// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1071// proves the pair it happens to hit cannot catch a transposed scan/context
1072// table (class scan-weights-cross-axis).
1073thread_local! {
1074 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1075 const { std::cell::Cell::new([0; 4]) };
1076}
1077
1078/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1079pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1080 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1081}
1082
1083// How many HORZ/VERT intra strips actually predicted with filter intra
1084// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1085// ("this decoder predicts square-only") until `predict_filter_intra` took
1086// `bw`x`bh`.
1087thread_local! {
1088 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1089 const { std::cell::Cell::new(0) };
1090}
1091
1092/// Current value of [`FILTER_INTRA_RECT_HITS`].
1093pub(crate) fn filter_intra_rect_hits() -> usize {
1094 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1095}
1096
1097// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1098// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1099// was never read at all before that round, so a gate needs to prove the flag
1100// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1101// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1102// carry different probabilities (18101 vs 20229), so a transposed pair is
1103// only caught by a gate that sees the flag fire on BOTH shapes (class
1104// scan-weights-cross-axis).
1105thread_local! {
1106 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1107 const { std::cell::Cell::new(0) };
1108 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1109 const { std::cell::Cell::new(0) };
1110}
1111
1112/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1113pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1114 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1115}
1116
1117/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1118pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1119 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1120}
1121
1122// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1123// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1124// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1125// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1126// prove nothing about the new shapes.
1127thread_local! {
1128 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1129 const { std::cell::Cell::new(0) };
1130}
1131
1132/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1133pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1134 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1135}
1136
1137// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1138// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1139// counter would be satisfied by a 16x8 strip and prove nothing here.
1140thread_local! {
1141 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1142 const { std::cell::Cell::new(0) };
1143}
1144
1145/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1146pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1147 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1148}
1149
1150// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1151// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1152// call on the current thread -- the same before/after counter pattern as
1153// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1154// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1155// landing on `DCT_DCT`.
1156thread_local! {
1157 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1158 const { std::cell::Cell::new(0) };
1159}
1160
1161// How many `uv_mode` reads resolved to a directional chroma mode (neither
1162// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1163// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1164// actually exercised chroma's own directional predictor.
1165thread_local! {
1166 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1167 const { std::cell::Cell::new(0) };
1168}
1169
1170/// Current value of [`DIRECTIONAL_UV_HITS`].
1171pub(crate) fn directional_uv_hits() -> usize {
1172 DIRECTIONAL_UV_HITS.with(|c| c.get())
1173}
1174
1175// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1176// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1177// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1178// proving a stream actually exercised a nonzero angle delta.
1179thread_local! {
1180 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1181 const { std::cell::Cell::new(0) };
1182}
1183
1184// How many [`read_single_ref`] reads resolved to a reference other than
1185// `LAST_FRAME`, across every call on the current thread -- the same before/after
1186// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1187// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1188// only other supported one so far) rather than every block coincidentally
1189// resolving `LAST_FRAME`.
1190thread_local! {
1191 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1192 const { std::cell::Cell::new(0) };
1193}
1194
1195/// Current value of [`NON_LAST_REF_HITS`].
1196pub(crate) fn non_last_ref_hits() -> usize {
1197 NON_LAST_REF_HITS.with(|c| c.get())
1198}
1199
1200// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1201// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1202// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1203// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1204// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1205// `GOLDEN_FRAME` draw it did not ask for.
1206thread_local! {
1207 static LAST2_HITS: std::cell::Cell<usize> =
1208 const { std::cell::Cell::new(0) };
1209}
1210thread_local! {
1211 static LAST3_HITS: std::cell::Cell<usize> =
1212 const { std::cell::Cell::new(0) };
1213}
1214thread_local! {
1215 static GOLDEN_HITS: std::cell::Cell<usize> =
1216 const { std::cell::Cell::new(0) };
1217}
1218thread_local! {
1219 static BWDREF_HITS: std::cell::Cell<usize> =
1220 const { std::cell::Cell::new(0) };
1221}
1222thread_local! {
1223 static ALTREF2_HITS: std::cell::Cell<usize> =
1224 const { std::cell::Cell::new(0) };
1225}
1226thread_local! {
1227 static ALTREF_HITS: std::cell::Cell<usize> =
1228 const { std::cell::Cell::new(0) };
1229}
1230
1231// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1232// -- proves a `reference_select` stream actually reached a block that picked
1233// compound, not just that the header bit was set. Every such block is
1234// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1235// so this only ever counts attempted reads, never a completed decode.
1236thread_local! {
1237 static COMP_MODE_HITS: std::cell::Cell<usize> =
1238 const { std::cell::Cell::new(0) };
1239}
1240
1241/// Current value of [`COMP_MODE_HITS`].
1242pub(crate) fn comp_mode_hits() -> usize {
1243 COMP_MODE_HITS.with(|c| c.get())
1244}
1245
1246// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1247// use for, across every call on the current thread -- the same before/after
1248// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1249// exercised palette reconstruction rather than only reading and refusing the
1250// `palette_y_mode` symbol.
1251thread_local! {
1252 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1253}
1254
1255/// Current value of [`PALETTE_HITS`].
1256pub(crate) fn palette_hits() -> usize {
1257 PALETTE_HITS.with(|c| c.get())
1258}
1259
1260// lane-tiles r12: of those, how many sat at their own TILE's left column --
1261// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1262// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1263// palette gate that never hits one proves nothing about the tile guard.
1264thread_local! {
1265 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1266}
1267
1268/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1269pub(crate) fn palette_tile_left_hits() -> usize {
1270 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1271}
1272
1273// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1274// palette use -- proves a stream actually reconstructed UV palette pixels,
1275// not just read and refused the `palette_uv_mode` symbol.
1276thread_local! {
1277 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1278}
1279
1280/// Current value of [`PALETTE_UV_HITS`].
1281pub(crate) fn palette_uv_hits() -> usize {
1282 PALETTE_UV_HITS.with(|c| c.get())
1283}
1284
1285// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1286// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1287// (not just the square path's) actually fired.
1288thread_local! {
1289 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1290}
1291
1292/// Current value of [`PALETTE_RECT_HITS`].
1293pub(crate) fn palette_rect_hits() -> usize {
1294 PALETTE_RECT_HITS.with(|c| c.get())
1295}
1296
1297// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1298// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1299// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1300// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1301// RD, almost always refused-on-use because the block doesn't end up USING a
1302// palette -- see r5's report). This is the site the removed refusal
1303// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1304// fired here whether or not the block picked a palette, so this is the
1305// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1306// never observes.
1307thread_local! {
1308 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1309}
1310
1311/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1312pub(crate) fn rect_screen_content_hits() -> usize {
1313 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1314}
1315
1316// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1317// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1318// windowing actually ran, not just that the whole-block path stayed exact.
1319// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1320// first actually incremented in r7, when the refusal it guarded was lifted.
1321thread_local! {
1322 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1323}
1324
1325/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1326pub(crate) fn palette_split_tx_hits() -> usize {
1327 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1328}
1329
1330thread_local! {
1331 /// A just-decoded palette-Y block's own predicted pixels
1332 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1333 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1334 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1335 /// per-block override through `read_plane`'s two dozen call sites is the
1336 /// alternative this avoids). Always empty again once that call consumes
1337 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
1338 /// sees stale state.
1339 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1340 const { std::cell::RefCell::new(None) };
1341}
1342
1343
1344/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
1345/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
1346/// site whose reconstruct never runs would be picked up by the NEXT block's
1347/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1348/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1349#[track_caller]
1350fn set_palette_pred(buf: Vec<u16>) {
1351 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1352 let stale = PALETTE_PRED.with(|c| c.borrow().is_some());
1353 eprintln!(
1354 "PALSET len={} stale={stale} at {}",
1355 buf.len(),
1356 std::panic::Location::caller()
1357 );
1358 }
1359 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
1360}
1361
1362#[track_caller]
1363fn take_palette_pred() -> Option<Vec<u16>> {
1364 let got = PALETTE_PRED.with(|c| c.borrow_mut().take());
1365 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1366 eprintln!(
1367 "PALTAKE len={:?} at {}",
1368 got.as_ref().map(Vec::len),
1369 std::panic::Location::caller()
1370 );
1371 }
1372 got
1373}
1374
1375thread_local! {
1376 /// The current frame's `mi` grid, kept only while a frame header set
1377 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
1378 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
1379 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
1380 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
1381 /// does not allow intrabc (so nothing is paid for it).
1382 ///
1383 /// corner-cut: only [`decode_block`] (the square path) records into it,
1384 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
1385 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
1386 /// be wrong there; upgrade = record from the rect/leaf paths too.
1387 static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1388 const { std::cell::RefCell::new(None) };
1389 /// The block vector [`read_intra_mode`] just decoded, handed to
1390 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1391 /// which the alternative -- a tenth tuple member through every caller --
1392 /// already avoids). Always `.take()`n by the block that reads it.
1393 static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1394 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1395 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1396}
1397
1398/// Current value of [`INTRABC_HITS`].
1399pub(crate) fn intrabc_hits() -> usize {
1400 INTRABC_HITS.with(|c| c.get())
1401}
1402
1403/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
1404pub(crate) fn reset_intrabc_hits() {
1405 INTRABC_HITS.with(|c| c.set(0));
1406}
1407
1408/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1409/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1410/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1411/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1412fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1413 INTRABC_MI_GRID.with(|g| {
1414 let mut g = g.borrow_mut();
1415 let Some((grid, _, _)) = g.as_mut() else {
1416 return;
1417 };
1418 let info = crate::mvstack::MiInfo {
1419 is_inter: dv.is_some(),
1420 ref_frame: 0,
1421 ref_frame1: None,
1422 mv: dv.unwrap_or((0, 0)),
1423 mv1: None,
1424 is_new_mv: dv.is_some(),
1425 is_global_mv0: false,
1426 is_global_mv1: false,
1427 size: n4,
1428 size_h: n4,
1429 };
1430 for r in mi_r..mi_r + n4 {
1431 for c in mi_c..mi_c + n4 {
1432 grid.set(r, c, info);
1433 }
1434 }
1435 });
1436}
1437
1438// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
1439// proves a real `skip_mode_present` stream actually reached a block that
1440// picked it, not just that the frame header bit was set.
1441thread_local! {
1442 static SKIP_MODE_HITS: std::cell::Cell<usize> =
1443 const { std::cell::Cell::new(0) };
1444}
1445
1446/// Current value of [`SKIP_MODE_HITS`].
1447pub(crate) fn skip_mode_hits() -> usize {
1448 SKIP_MODE_HITS.with(|c| c.get())
1449}
1450
1451// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
1452// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
1453// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
1454// reached [`obmc_blend`], not just the header bit.
1455thread_local! {
1456 static OBMC_HITS: std::cell::Cell<usize> =
1457 const { std::cell::Cell::new(0) };
1458}
1459
1460// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
1461// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
1462// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
1463// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
1464// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
1465// decoder used to read with the wrong alphabet, so a gate that asserts this
1466// counter advanced proves the fixed path fired (class
1467// `gate-blind-to-feature`).
1468thread_local! {
1469 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1470}
1471
1472/// Current value of [`FIMV_ALPHABET_HITS`].
1473pub fn fimv_alphabet_hits() -> usize {
1474 FIMV_ALPHABET_HITS.with(|c| c.get())
1475}
1476
1477// lane-fimv r1: how many frame headers this decoder has decoded with
1478/// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
1479// prove the encoder really produced the header state under test rather than
1480// assume it.
1481thread_local! {
1482 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1483}
1484
1485/// Current value of [`FIMV_FRAME_HITS`].
1486pub fn fimv_frame_hits() -> usize {
1487 FIMV_FRAME_HITS.with(|c| c.get())
1488}
1489
1490/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
1491/// `force_integer_mv` bit is set.
1492pub fn note_force_integer_mv_frame() {
1493 FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1));
1494}
1495
1496/// Current value of [`OBMC_HITS`].
1497pub(crate) fn obmc_hits() -> usize {
1498 OBMC_HITS.with(|c| c.get())
1499}
1500
1501// lane-scaledref r1: per-case firing counts for the scaled-reference gate
1502// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
1503// reference would pass just as well and prove nothing, so the gate
1504// hard-asserts each combination this round lifts actually occurred:
1505// a compound block with a scaled tap, a warp block whose warp libaom
1506// suppresses because the reference is scaled, an OBMC block, an interintra
1507// block, and an 8x8 leaf.
1508thread_local! {
1509 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1510 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1511 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1512 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1513 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1514 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1515 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1516}
1517
1518/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
1519/// scaled and one unscaled tap.
1520pub(crate) fn mixed_scale_compound_hits() -> usize {
1521 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
1522}
1523
1524/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
1525/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
1526/// instead because their reference is scaled (libaom `motion_mode_allowed`,
1527/// `blockd.h:1484`).
1528pub(crate) fn scaled_warp_suppressed_hits() -> usize {
1529 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
1530}
1531
1532/// Current value of [`SCALED_COMPOUND_HITS`].
1533pub(crate) fn scaled_compound_hits() -> usize {
1534 SCALED_COMPOUND_HITS.with(|c| c.get())
1535}
1536
1537/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
1538pub(crate) fn scaled_warp_fallback_hits() -> usize {
1539 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
1540}
1541
1542/// Current value of [`SCALED_OBMC_HITS`].
1543pub(crate) fn scaled_obmc_hits() -> usize {
1544 SCALED_OBMC_HITS.with(|c| c.get())
1545}
1546
1547/// Current value of [`SCALED_INTERINTRA_HITS`].
1548pub(crate) fn scaled_interintra_hits() -> usize {
1549 SCALED_INTERINTRA_HITS.with(|c| c.get())
1550}
1551
1552/// Current value of [`SCALED_BLOCK8_HITS`].
1553pub(crate) fn scaled_block8_hits() -> usize {
1554 SCALED_BLOCK8_HITS.with(|c| c.get())
1555}
1556
1557// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
1558// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
1559// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
1560// 8x8-leaf OBMC block apart from a 16x16+ one.
1561thread_local! {
1562 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1563}
1564
1565// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
1566// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
1567// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
1568// -- the gate's proof that a fixture really exercises the alphabet this
1569// round changed, even though the block itself still refuses (warp
1570// estimation/filter not ported).
1571thread_local! {
1572 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
1573 const { std::cell::Cell::new(0) };
1574}
1575
1576/// Current value of [`WARP_SELECTED_HITS`].
1577pub(crate) fn warp_selected_hits() -> usize {
1578 WARP_SELECTED_HITS.with(|c| c.get())
1579}
1580
1581// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
1582// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
1583// into the compound intermediate) rather than translationally -- the
1584// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
1585// really reached [`crate::warp::warp_affine_compound`].
1586thread_local! {
1587 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
1588 const { std::cell::Cell::new(0) };
1589}
1590
1591/// Current value of [`COMPOUND_WARP_HITS`].
1592pub(crate) fn compound_warp_hits() -> usize {
1593 COMPOUND_WARP_HITS.with(|c| c.get())
1594}
1595
1596// lane-gmaffine r1: how many blocks built their prediction from a
1597// SIX-parameter (`AFFINE`) global-motion model through
1598// `crate::warp::global_warp_params` -- the gate's proof that a stream really
1599// carried an AFFINE `global_motion_params` AND that a block was predicted
1600// with it, not merely that the header parsed one.
1601thread_local! {
1602 static AFFINE_GM_HITS: std::cell::Cell<usize> =
1603 const { std::cell::Cell::new(0) };
1604}
1605
1606/// Current value of [`AFFINE_GM_HITS`].
1607pub(crate) fn affine_gm_hits() -> usize {
1608 AFFINE_GM_HITS.with(|c| c.get())
1609}
1610
1611// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
1612// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
1613// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
1614// only once `find_projection` returned a usable model, unlike
1615// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
1616// proof that the leaf path itself fired, not the 16x16+ one.
1617thread_local! {
1618 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1619 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1620}
1621
1622/// Current value of [`GLOBALMV_HITS_8`].
1623pub(crate) fn globalmv_hits_8() -> usize {
1624 GLOBALMV_HITS_8.with(|c| c.get())
1625}
1626
1627/// Current value of [`WARP_HITS_8`].
1628pub(crate) fn warp_hits_8() -> usize {
1629 WARP_HITS_8.with(|c| c.get())
1630}
1631
1632// How many blocks decoded `interintra == 1` with the non-wedge blended
1633// prediction applied (lane-interintra r1) -- the gate's proof that a
1634// stream actually exercised interintra.
1635thread_local! {
1636 static INTERINTRA_HITS: std::cell::Cell<usize> =
1637 const { std::cell::Cell::new(0) };
1638}
1639
1640/// Current value of [`INTERINTRA_HITS`].
1641pub(crate) fn interintra_hits() -> usize {
1642 INTERINTRA_HITS.with(|c| c.get())
1643}
1644
1645// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
1646// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
1647// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
1648// gate fixture actually exercises this alphabet, even though the block
1649// still refuses (the mask blend itself is unported).
1650thread_local! {
1651 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
1652 const { std::cell::Cell::new(0) };
1653}
1654
1655/// Current value of [`MASKED_COMPOUND_HITS`].
1656pub(crate) fn masked_compound_hits() -> usize {
1657 MASKED_COMPOUND_HITS.with(|c| c.get())
1658}
1659
1660// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
1661// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
1662// actually exercised the wedge blend, not just the DIFFWTD half of
1663// `MASKED_COMPOUND_HITS`.
1664thread_local! {
1665 static WEDGE_HITS: std::cell::Cell<usize> =
1666 const { std::cell::Cell::new(0) };
1667}
1668
1669/// Current value of [`WEDGE_HITS`].
1670pub(crate) fn wedge_hits() -> usize {
1671 WEDGE_HITS.with(|c| c.get())
1672}
1673
1674// How many blocks decoded a real wedge-INTERINTRA block
1675// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
1676// a gate fixture exercised the wedge blend (fixed sign 0), not just the
1677// smooth arm counted by `INTERINTRA_HITS`.
1678thread_local! {
1679 static WII_HITS: std::cell::Cell<usize> =
1680 const { std::cell::Cell::new(0) };
1681}
1682
1683/// Current value of [`WII_HITS`].
1684pub(crate) fn wii_hits() -> usize {
1685 WII_HITS.with(|c| c.get())
1686}
1687
1688/// Current value of [`OBMC_HITS_8`].
1689pub(crate) fn obmc_hits_8() -> usize {
1690 OBMC_HITS_8.with(|c| c.get())
1691}
1692
1693// lane-rectgate r1: how many 32x32 quadrants actually decoded a
1694// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
1695// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
1696// `VERT_B` all still fall into the generic "a partition type this encoder
1697// never writes" refusal below) -- the gate's proof that a free-partition
1698// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
1699// coincidentally never selecting one.
1700thread_local! {
1701 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
1702 const { std::cell::Cell::new(0) };
1703}
1704
1705/// Current value of [`EXTENDED_PARTITION_HITS`].
1706pub(crate) fn extended_partition_hits() -> usize {
1707 EXTENDED_PARTITION_HITS.with(|c| c.get())
1708}
1709
1710// lane-partitions r1: how many 32x32 quadrants decoded a real
1711// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
1712// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
1713// gate's proof this round's arms actually fired.
1714thread_local! {
1715 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
1716 const { std::cell::Cell::new(0) };
1717}
1718
1719/// Current value of [`RECT_PARTITION_HITS`].
1720pub(crate) fn rect_partition_hits() -> usize {
1721 RECT_PARTITION_HITS.with(|c| c.get())
1722}
1723
1724// lane-inter8 r1: how many superblocks an inter tile coded as a single
1725// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
1726// static content, previously a named refusal).
1727thread_local! {
1728 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
1729 const { std::cell::Cell::new(0) };
1730}
1731
1732/// Current value of [`INTER_SB_NONE_HITS`].
1733pub(crate) fn inter_sb_none_hits() -> usize {
1734 INTER_SB_NONE_HITS.with(|c| c.get())
1735}
1736
1737// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
1738// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
1739// path has always run that loop, so only this counter proves the newly-lifted
1740// alphabet value fired.
1741thread_local! {
1742 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
1743 const { std::cell::Cell::new(0) };
1744}
1745
1746/// Current value of [`INTER_SUB16_SPLIT_HITS`].
1747pub(crate) fn inter_sub16_split_hits() -> usize {
1748 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
1749}
1750
1751// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
1752// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
1753// rect coefficient reader itself fired, not just the strip-level partition
1754// symbol [`RECT_PARTITION_HITS`] already counts.
1755thread_local! {
1756 static RECT_COEFF_HITS: std::cell::Cell<usize> =
1757 const { std::cell::Cell::new(0) };
1758}
1759
1760/// Current value of [`RECT_COEFF_HITS`].
1761pub(crate) fn rect_coeff_hits() -> usize {
1762 RECT_COEFF_HITS.with(|c| c.get())
1763}
1764
1765// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
1766// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
1767// charter's real-aomenc gate hard-asserts.
1768thread_local! {
1769 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
1770 const { std::cell::Cell::new(0) };
1771}
1772
1773/// Current value of [`RECT_LEAF_COEFF_HITS`].
1774pub(crate) fn rect_leaf_coeff_hits() -> usize {
1775 RECT_LEAF_COEFF_HITS.with(|c| c.get())
1776}
1777
1778// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
1779// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
1780// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
1781// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
1782thread_local! {
1783 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
1784 const { std::cell::Cell::new(0) };
1785}
1786
1787/// Current value of [`MODE_MI_OVERRIDE_HITS`].
1788pub(crate) fn mode_mi_override_hits() -> usize {
1789 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
1790}
1791
1792// lane-cfl r1: how many times a chroma intra-edge filter-type read
1793// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
1794// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
1795// r1 defect would have filtered a chroma edge with the wrong strength.
1796thread_local! {
1797 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
1798 const { std::cell::Cell::new(0) };
1799}
1800
1801/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
1802pub(crate) fn uv_mode_mi_override_hits() -> usize {
1803 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
1804}
1805
1806// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
1807// suppressed at a TILE edge that is not a frame edge -- the above/left
1808// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
1809// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
1810// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
1811// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
1812// above would decide this tile's chroma edge filter strength.
1813thread_local! {
1814 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
1815 const { std::cell::Cell::new(0) };
1816}
1817
1818/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
1819pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
1820 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
1821}
1822
1823// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
1824// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
1825// shapes the r1 chroma defect showed up on.
1826thread_local! {
1827 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1828 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1829}
1830
1831/// Current value of [`CFL_BLOCK_HITS`].
1832pub(crate) fn cfl_block_hits() -> usize {
1833 CFL_BLOCK_HITS.with(|c| c.get())
1834}
1835
1836/// Current value of [`UV_ANGLE_DELTA_HITS`].
1837pub(crate) fn uv_angle_delta_hits() -> usize {
1838 UV_ANGLE_DELTA_HITS.with(|c| c.get())
1839}
1840
1841// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
1842// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
1843// gate's proof this round's arms actually reached a real block, not just
1844// that `partition_w64` read one of those two symbol values.
1845thread_local! {
1846 static SB_RECT_HITS: std::cell::Cell<usize> =
1847 const { std::cell::Cell::new(0) };
1848}
1849
1850/// Current value of [`SB_RECT_HITS`].
1851pub(crate) fn sb_rect_hits() -> usize {
1852 SB_RECT_HITS.with(|c| c.get())
1853}
1854
1855// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
1856// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
1857// strip) fired. Real aomenc picks these at 64 even with
1858// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
1859// the counter the gate hard-asserts.
1860thread_local! {
1861 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
1862 const { std::cell::Cell::new([0; 4]) };
1863}
1864
1865/// Current value of [`SB_AB_HITS`], summed over the four arms.
1866pub(crate) fn sb_ab_hits() -> usize {
1867 SB_AB_HITS.with(|c| c.get().iter().sum())
1868}
1869
1870/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
1871/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
1872/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
1873/// proof of all four.
1874pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
1875 SB_AB_HITS.with(std::cell::Cell::get)
1876}
1877
1878// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
1879// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
1880// strips). Two counters, not one, because a gate that only proved "some 1:4
1881// strip fired" would pass on a stream that never coded the other axis, and
1882// every scan/context table this round added comes in a transposed pair.
1883thread_local! {
1884 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1885 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1886}
1887
1888/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
1889pub(crate) fn sb_rect4_horz_hits() -> usize {
1890 SB_RECT4_HORZ_HITS.with(|c| c.get())
1891}
1892
1893/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
1894pub(crate) fn sb_rect4_vert_hits() -> usize {
1895 SB_RECT4_VERT_HITS.with(|c| c.get())
1896}
1897
1898// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
1899// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
1900// strips), the arms the ReelB mid-film extract stops at.
1901thread_local! {
1902 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1903 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1904}
1905
1906/// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
1907/// a gate that only counted strips would pass on an all-skip stream, which
1908/// exercises none of the new scan/context tables.
1909thread_local! {
1910 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1911}
1912
1913/// Current value of `RECT4_COEFF_HITS`.
1914pub(crate) fn rect4_coeff_hits() -> usize {
1915 RECT4_COEFF_HITS.with(|c| c.get())
1916}
1917
1918/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
1919pub(crate) fn rect4_32_horz_hits() -> usize {
1920 RECT4_32_HORZ_HITS.with(|c| c.get())
1921}
1922
1923/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
1924pub(crate) fn rect4_32_vert_hits() -> usize {
1925 RECT4_32_VERT_HITS.with(|c| c.get())
1926}
1927
1928// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
1929// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
1930// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
1931// just inert-compiled. Zero forever on a passing gate means that gate's
1932// stream never carries `delta_q_present=1` through a rect64 block.
1933thread_local! {
1934 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
1935 const { std::cell::Cell::new(0) };
1936}
1937
1938/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
1939pub(crate) fn rect64_qidx_drift_hits() -> usize {
1940 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
1941}
1942
1943// lane-partab r1: how many 32x32 quadrants decoded an AB partition
1944// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
1945// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
1946// free-partition gate's proof this round's arms actually fired.
1947thread_local! {
1948 static PARTAB_HITS: std::cell::Cell<usize> =
1949 const { std::cell::Cell::new(0) };
1950}
1951
1952/// Current value of [`PARTAB_HITS`].
1953pub(crate) fn partab_hits() -> usize {
1954 PARTAB_HITS.with(|c| c.get())
1955}
1956
1957// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
1958// one counter per arm rather than one shared total -- the gate hard-asserts
1959// each of these individually nonzero so a recipe that only ever fires
1960// HORZ_A can't silently stand in for the whole set.
1961thread_local! {
1962 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
1963 const { std::cell::Cell::new(0) };
1964 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
1965 const { std::cell::Cell::new(0) };
1966 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
1967 const { std::cell::Cell::new(0) };
1968 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
1969 const { std::cell::Cell::new(0) };
1970}
1971
1972/// Current value of [`INTRA_HORZ_A_HITS`].
1973pub(crate) fn intra_horz_a_hits() -> usize {
1974 INTRA_HORZ_A_HITS.with(|c| c.get())
1975}
1976/// Current value of [`INTRA_HORZ_B_HITS`].
1977pub(crate) fn intra_horz_b_hits() -> usize {
1978 INTRA_HORZ_B_HITS.with(|c| c.get())
1979}
1980/// Current value of [`INTRA_VERT_A_HITS`].
1981pub(crate) fn intra_vert_a_hits() -> usize {
1982 INTRA_VERT_A_HITS.with(|c| c.get())
1983}
1984/// Current value of [`INTRA_VERT_B_HITS`].
1985pub(crate) fn intra_vert_b_hits() -> usize {
1986 INTRA_VERT_B_HITS.with(|c| c.get())
1987}
1988
1989// How many [`read_inter_compound_mode`] reads actually happened
1990// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
1991// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
1992// mvstack build), not just that `comp_mode` fired. Still refused right
1993// after (no MV assignment or MC wired), so this only counts attempted
1994// reads.
1995thread_local! {
1996 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
1997 const { std::cell::Cell::new(0) };
1998}
1999
2000/// Current value of [`COMPOUND_MODE_HITS`].
2001pub(crate) fn compound_mode_hits() -> usize {
2002 COMPOUND_MODE_HITS.with(|c| c.get())
2003}
2004
2005/// How many query blocks folded in at least one temporal MV candidate
2006/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
2007/// temporal-MV gate's own firing counter (lane-av1tmvp).
2008///
2009/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
2010/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
2011/// this file (`decode_inter_block`) still passes `tpl: None` -- this
2012/// counter compiles and the projection math it counts is unit-tested
2013/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
2014/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
2015/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
2016/// against any real stream today. See the module doc on
2017/// `crate::motion_field` and this crate's ledger for the remaining wiring.
2018pub(crate) fn tmv_hits() -> usize {
2019 crate::mvstack::tmv_hits()
2020}
2021
2022/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
2023/// produced on this thread, the 10-bit inter gate's firing proof.
2024pub(crate) fn inter_pred_hits() -> usize {
2025 crate::mc::inter_pred_hits()
2026}
2027
2028/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
2029/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
2030/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
2031/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
2032/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
2033/// needs to turn a query block's own resolved `ref_frame` into
2034/// `TplArgs::cur_offset_0` (spec 7.9.3).
2035pub(crate) struct TplFrameArgs<'a> {
2036 pub field: &'a crate::motion_field::TplField,
2037 pub order_hint_bits: u32,
2038 pub order_hint: u32,
2039 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
2040 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
2041 /// frame's own `ref_frame_idx` names for each single reference.
2042 pub ref_order_hints: [u32; 7],
2043}
2044
2045/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
2046/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
2047/// decoded `grid`: every 4x4 unit an inter block covers reads the same
2048/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
2049/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
2050/// exact — every block this crate ever codes is at least 8x8, so no 8x8
2051/// cell straddles two different blocks' values.
2052pub(crate) fn build_motion_field(
2053 grid: &MiGrid,
2054 mi_cols: usize,
2055 mi_rows: usize,
2056 order_hint: u32,
2057 ref_order_hints: [u32; 7],
2058) -> crate::motion_field::MotionField {
2059 let mut field =
2060 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
2061 for row in 0..mi_rows {
2062 for col in 0..mi_cols {
2063 if let Some(info) = grid.get(row, col)
2064 && info.is_inter
2065 && info.ref_frame > 0
2066 {
2067 field.set(
2068 row,
2069 col,
2070 crate::motion_field::SavedMv {
2071 mv: info.mv,
2072 ref_frame: info.ref_frame,
2073 },
2074 );
2075 }
2076 }
2077 }
2078 field
2079}
2080
2081/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
2082/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
2083pub(crate) fn ref_hits(ref_frame: i8) -> usize {
2084 let c = match ref_frame {
2085 LAST2_FRAME => &LAST2_HITS,
2086 LAST3_FRAME => &LAST3_HITS,
2087 GOLDEN_FRAME => &GOLDEN_HITS,
2088 BWDREF_FRAME => &BWDREF_HITS,
2089 ALTREF2_FRAME => &ALTREF2_HITS,
2090 ALTREF_FRAME => &ALTREF_HITS,
2091 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
2092 };
2093 c.with(|v| v.get())
2094}
2095
2096thread_local! {
2097 /// The sequence header's `enable_intra_edge_filter`, set once per
2098 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
2099 /// own read of it, kept off the call stack (see that function's own doc
2100 /// comment for why) rather than threaded through every `read_plane`/
2101 /// `decode_block`/`decode_leaf8` call between here and there.
2102 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2103}
2104
2105/// Set [`ENABLE_EDGE_FILTER`] for this thread.
2106///
2107/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
2108/// never did -- so an inter frame's intra blocks read whatever value the last
2109/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
2110/// harmless (its own key frame sets it first), but a caller that decodes an
2111/// inter frame directly, or a test harness running several streams on one
2112/// thread, inherits a foreign sequence's bit: decode stops being a pure
2113/// function of the bitstream. `decode_stream` now calls this once per stream
2114/// from the sequence header, which covers every frame including inter ones.
2115pub(crate) fn set_enable_edge_filter(value: bool) {
2116 ENABLE_EDGE_FILTER.with(|f| f.set(value));
2117}
2118
2119/// Current value of [`ANGLE_DELTA_HITS`].
2120pub(crate) fn angle_delta_hits() -> usize {
2121 ANGLE_DELTA_HITS.with(|c| c.get())
2122}
2123
2124/// Current value of [`TX_CLASS1_HITS`].
2125pub(crate) fn tx_class1_hits() -> usize {
2126 TX_CLASS1_HITS.with(|c| c.get())
2127}
2128
2129// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
2130// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
2131// bottom) this thread's decode actually reconstructed -- the same
2132// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
2133// genuinely exercised the sub-8x8 leaf path rather than every attempt
2134// coincidentally landing on `PARTITION_NONE`.
2135thread_local! {
2136 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2137}
2138
2139/// Current value of [`SUB8_SPLIT_HITS`].
2140pub(crate) fn sub8_split_hits() -> usize {
2141 SUB8_SPLIT_HITS.with(|c| c.get())
2142}
2143
2144// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
2145// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
2146// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
2147// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
2148// asserts on these two rather than a plain leaf count.
2149thread_local! {
2150 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2151 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2152 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
2153 /// two 4x4 transform units, predicted one after the other. A separate
2154 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
2155 /// the gate can prove THIS path fired.
2156 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2157 /// 16x8/8x16 intra strips whose prediction actually read past the block's
2158 /// own width (above-right) or height (below-left) -- the samples
2159 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
2160 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
2161 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2162 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
2163 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
2164 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2165}
2166
2167/// Current value of [`RECT8_SPLIT_TX_HITS`].
2168pub(crate) fn rect8_split_tx_hits() -> usize {
2169 RECT8_SPLIT_TX_HITS.with(|c| c.get())
2170}
2171
2172/// Current value of [`RECT_STRIP_PRED_HITS`].
2173pub(crate) fn rect_strip_pred_hits() -> usize {
2174 RECT_STRIP_PRED_HITS.with(|c| c.get())
2175}
2176
2177/// Current value of [`RECT_STRIP_REACH_HITS`].
2178pub(crate) fn rect_strip_reach_hits() -> usize {
2179 RECT_STRIP_REACH_HITS.with(|c| c.get())
2180}
2181
2182/// Current value of [`TX4X8_CODED_HITS`].
2183pub(crate) fn tx4x8_coded_hits() -> usize {
2184 TX4X8_CODED_HITS.with(|c| c.get())
2185}
2186
2187/// Current value of [`TX8X4_CODED_HITS`].
2188pub(crate) fn tx8x4_coded_hits() -> usize {
2189 TX8X4_CODED_HITS.with(|c| c.get())
2190}
2191
2192// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
2193// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
2194// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
2195// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
2196// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
2197// (`eob_pt_{16,64,128,256}_chroma_class1`).
2198thread_local! {
2199 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
2200 const { std::cell::Cell::new(0) };
2201}
2202
2203/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
2204pub(crate) fn chroma_eob_class1_hits() -> usize {
2205 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
2206}
2207
2208/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
2209/// `tx_type` put this block's `eob_pt` on the class-1 row.
2210fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
2211 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
2212 CHROMA_EOB_CLASS1_HITS.with(|c| c.set(c.get() + 1));
2213 }
2214}
2215
2216const SUB_MI: u32 = 4;
2217const MI: usize = 4;
2218const SB: usize = 64;
2219/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
2220/// (tile start, superblock-row start).
2221///
2222/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
2223/// `av1_get_partition_plane_context` reads its own zero-initialised
2224/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
2225/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
2226/// (64), which reads identically at every level up to 64x64 but sets the bit
2227/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
2228/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
2229/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
2230const NO_NEIGHBOUR_SIDE: usize = 128;
2231const BLOCK: usize = 32;
2232const SUB: usize = 16;
2233const TX32: usize = 32;
2234const TX16: usize = 16;
2235const TX8: usize = 8;
2236const TX4: usize = 4;
2237const DC_PRED: usize = 0;
2238/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
2239/// carries an angle delta — [`crate::tile`]'s own private copy of the same
2240/// constant.
2241const V_PRED: usize = 1;
2242const H_PRED: usize = 2;
2243/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
2244/// `Fimode_To_Intradir`, libaom `blockd.h`).
2245const D157_PRED: usize = 6;
2246/// The last directional mode, `D67_PRED`.
2247const D67_PRED: usize = 8;
2248/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
2249/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
2250/// codes anything else, so this decoder never reads anything else either.
2251const ANGLE_DELTA_ZERO: usize = 3;
2252const NUM_BASE_LEVELS: i32 = 2;
2253const COEFF_BASE_RANGE: i32 = 12;
2254const BR_STEP: i32 = 3;
2255const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
2256
2257/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
2258/// whose probability mass a superblock or block half outside the frame
2259/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
2260/// duplicated here (that module is another lane's territory this round) and
2261/// kept in step with it by the byte-exact round-trip tests below rather than
2262/// by sharing code.
2263const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
2264const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
2265
2266fn element_prob(cdf: &[u16], element: usize) -> u16 {
2267 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
2268}
2269
2270/// The two-symbol CDF a partial superblock/block's forced-split flag is read
2271/// with: the mass of `elements` becomes the probability of the one partition
2272/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
2273/// (the encoder's non-adapting counterpart to this read).
2274fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
2275 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
2276 [32768 - split, 32768, 0]
2277}
2278
2279fn unsupported(what: impl Into<String>) -> Error {
2280 Error::unsupported("AV1 tile", what.into())
2281}
2282
2283/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
2284/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
2285/// same rule.
2286pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
2287 match base_q_idx {
2288 0..=20 => 0,
2289 21..=60 => 1,
2290 61..=120 => 2,
2291 _ => 3,
2292 }
2293}
2294
2295/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
2296/// [`crate::tile`]'s writer generates its scan tables with.
2297fn default_scan(side: usize) -> Vec<u16> {
2298 let mut scan = Vec::with_capacity(side * side);
2299 for d in 0..(2 * side - 1) {
2300 let lo = d.saturating_sub(side - 1);
2301 let hi = d.min(side - 1);
2302 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
2303 if d % 2 == 0 {
2304 scan.extend(diagonal.rev());
2305 } else {
2306 scan.extend(diagonal);
2307 }
2308 }
2309 scan
2310}
2311
2312/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
2313/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
2314/// in, instead of the default zigzag. libaom's own tables are keyed by a
2315/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
2316/// physically column-major level buffer, but they decompose to the exact
2317/// same (row, col) walk as a flat row-major traversal of *our* row-major
2318/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
2319/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
2320/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
2321/// transposed (column 0 down every row, then column 1, ...).
2322fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
2323 class_scan_table_wh(side, side, class)
2324}
2325
2326/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
2327/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
2328/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
2329/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
2330/// transcribed with -- `mrow` is the plain row-major raster in our indexing
2331/// and `mcol` its transpose, at rect sizes exactly as at square ones.
2332fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
2333 match class {
2334 TxClass::Vert => (0..(w * h) as u16).collect(),
2335 TxClass::Horiz => (0..w)
2336 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
2337 .collect(),
2338 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
2339 }
2340}
2341
2342fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
2343 match scan_idx {
2344 0 => 0,
2345 i if i <= area / 8 => 1,
2346 i if i <= area / 4 => 2,
2347 _ => 3,
2348 }
2349}
2350
2351fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
2352 if row >= side || col >= side {
2353 0
2354 } else {
2355 grid[row * side + col]
2356 }
2357}
2358
2359/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
2360/// `txb_common.h`): everything but the two lone-axis-identity types this
2361/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
2362#[derive(Clone, Copy, PartialEq, Eq)]
2363enum TxClass {
2364 TwoD,
2365 Horiz,
2366 Vert,
2367}
2368
2369impl TxClass {
2370 fn of(tx_type: TxType) -> Self {
2371 match tx_type {
2372 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
2373 // key on axis alone -- FLIPADST is still ADST for this purpose.
2374 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
2375 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
2376 _ => Self::TwoD,
2377 }
2378 }
2379}
2380
2381/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
2382/// table (indexed by the position along the transform's *coded* axis --
2383/// `col` for horiz, `row` for vert) that places their contexts past the 2D
2384/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
2385/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
2386fn nz_map_ctx_offset_1d(i: usize) -> usize {
2387 match i {
2388 0 => 26,
2389 1 => 31,
2390 _ => 36,
2391 }
2392}
2393
2394fn base_ctx(
2395 grid: &[i32],
2396 side: usize,
2397 row: usize,
2398 col: usize,
2399 class: TxClass,
2400 rect_shape: Option<(usize, usize)>,
2401) -> usize {
2402 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
2403 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
2404 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
2405 // position through the full 1D neighbour sum and offset table. Skipping
2406 // that for every class desynced the last (DC) coefficient of a
2407 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
2408 // 0, which then read one extra `BR` symbol at the max and forced a
2409 // spurious third Golomb call).
2410 if class == TxClass::TwoD && row == 0 && col == 0 {
2411 return 0;
2412 }
2413 let offsets: [(usize, usize); 5] = match class {
2414 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
2415 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
2416 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
2417 };
2418 let mag: i32 = offsets
2419 .iter()
2420 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
2421 .sum();
2422 let ctx = ((mag + 1) >> 1).min(4) as usize;
2423 match class {
2424 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
2425 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
2426 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
2427 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
2428 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
2429 // strip, which own a genuinely different table from the square one
2430 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
2431 // square table vs the real ctx 13 the rect table gives).
2432 TxClass::TwoD => {
2433 // lane-rectsplit r4: apply libaom's GENERATING RULE
2434 // (`txb_common.h:199-209`) directly instead of indexing the
2435 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
2436 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
2437 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
2438 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
2439 // so 32 consecutive entries are one COLUMN: the [`cdf`]
2440 // transcriptions are `[col][row]` and this read had them as
2441 // `[row][col]` -- the transpose, i.e. the other shape's rule with
2442 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
2443 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
2444 // pins the rule against the tables over their whole 5x5 domain.
2445 if let Some((w, h)) = rect_shape {
2446 if std::env::var_os("EC_NZOFF_DUMP").is_some() {
2447 eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}");
2448 }
2449 if w < h && row < 2 {
2450 return ctx + 11;
2451 }
2452 if w > h && col < 2 {
2453 return ctx + 16;
2454 }
2455 }
2456 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2457 }
2458 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
2459 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
2460 }
2461}
2462
2463fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
2464 let extra = match class {
2465 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
2466 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
2467 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
2468 };
2469 let mag = neighbour(grid, side, row + 1, col).abs()
2470 + neighbour(grid, side, row, col + 1).abs()
2471 + extra;
2472 let mag = (((mag + 1) >> 1).min(6)) as usize;
2473 if row == 0 && col == 0 {
2474 return mag;
2475 }
2476 let near_origin = match class {
2477 TxClass::TwoD => row < 2 && col < 2,
2478 TxClass::Horiz => col == 0,
2479 TxClass::Vert => row == 0,
2480 };
2481 if near_origin { mag + 7 } else { mag + 14 }
2482}
2483
2484/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
2485/// transposed from libaom's column-major buffer into this decoder's row-major
2486/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
2487/// against the real table). Not the square zigzag formula generalized to
2488/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
2489const SCAN_32X16: [u16; 512] = [
2490 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
2491 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
2492 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
2493 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
2494 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
2495 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
2496 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
2497 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
2498 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
2499 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
2500 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
2501 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
2502 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
2503 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
2504 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
2505 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
2506 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
2507 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
2508 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
2509 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
2510 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
2511 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
2512 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
2513 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
2514 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
2515 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
2516 509, 478, 447, 510, 479, 511,
2517];
2518
2519/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
2520/// [`SCAN_32X16`]'s doc comment).
2521const SCAN_16X32: [u16; 512] = [
2522 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,
2523 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
2524 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
2525 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
2526 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
2527 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
2528 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
2529 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
2530 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
2531 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
2532 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
2533 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
2534 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
2535 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
2536 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
2537 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
2538 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
2539 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
2540 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
2541 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
2542 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
2543 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
2544 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
2545 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
2546 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
2547 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
2548];
2549
2550/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
2551/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
2552/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
2553/// the same source).
2554const SCAN_4X8: [u16; 32] = [
2555 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,
2556 23, 26, 29, 27, 30, 31,
2557];
2558
2559/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
2560const SCAN_8X4: [u16; 32] = [
2561 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,
2562 29, 22, 15, 30, 23, 31,
2563];
2564
2565/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
2566/// [`SCAN_32X16`]'s doc comment).
2567const SCAN_16X8: [u16; 128] = [
2568 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,
2569 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
2570 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
2571 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
2572 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
2573 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
2574];
2575
2576/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
2577/// [`SCAN_32X16`]'s doc comment).
2578const SCAN_8X16: [u16; 128] = [
2579 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,
2580 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
2581 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
2582 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
2583 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
2584 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
2585];
2586
2587/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
2588/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
2589/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
2590/// scans column-major (`p = col * height + row`), so a naive copy of
2591/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
2592/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
2593/// are byte-identical to this decoder's [`SCAN_8X16`].
2594const SCAN_32X8: [u16; 256] = [
2595 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
2596 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
2597 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
2598 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
2599 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
2600 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
2601 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
2602 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
2603 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
2604 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
2605 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
2606 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
2607 222, 191, 254, 223, 255,
2608];
2609/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
2610/// 16x64 `PARTITION_VERT_4` strip).
2611const SCAN_8X32: [u16; 256] = [
2612 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,
2613 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
2614 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
2615 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
2616 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
2617 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
2618 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
2619 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
2620 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
2621 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
2622 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
2623 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
2624 239, 246, 253, 247, 254, 255,
2625];
2626/// `Default_Scan_16x4`, this decoder's own row-major transcription of
2627/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
2628/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
2629/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
2630/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
2631/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
2632/// were emitted -- a naive copy installs the transpose (class
2633/// reference-layout-not-spec).
2634const SCAN_16X4: [u16; 64] = [
2635 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,
2636 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
2637 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
2638];
2639/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
2640/// 8x32 `PARTITION_VERT_4` strip).
2641const SCAN_4X16: [u16; 64] = [
2642 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,
2643 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
2644 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
2645];
2646
2647/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
2648/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
2649/// asymmetric-extent pattern).
2650fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
2651 if row >= h || col >= w {
2652 0
2653 } else {
2654 grid[row * w + col]
2655 }
2656}
2657
2658/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
2659/// the rect generalization is libaom's own comment in
2660/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
2661/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
2662/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
2663/// [`decode_block_rect`] codes (see that function's own doc comment).
2664fn base_ctx_rect(
2665 grid: &[i32],
2666 w: usize,
2667 h: usize,
2668 row: usize,
2669 col: usize,
2670 class: TxClass,
2671) -> usize {
2672 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
2673 // the 2D class short-circuits the DC position.
2674 if class == TxClass::TwoD && row == 0 && col == 0 {
2675 return 0;
2676 }
2677 let offsets: [(usize, usize); 5] = match class {
2678 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
2679 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
2680 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
2681 };
2682 let mag: i32 = offsets
2683 .iter()
2684 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
2685 .sum();
2686 let ctx = ((mag + 1) >> 1).min(4) as usize;
2687 match class {
2688 TxClass::TwoD => {
2689 if w < h && row < 2 {
2690 return ctx + 11;
2691 }
2692 if w > h && col < 2 {
2693 return ctx + 16;
2694 }
2695 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2696 }
2697 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
2698 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
2699 // position along one axis only).
2700 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
2701 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
2702 }
2703}
2704
2705/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
2706/// neighbour-offset math itself is shape-independent, only the boundary
2707/// clamp needs the real bound in each axis.
2708fn br_ctx_rect(
2709 grid: &[i32],
2710 w: usize,
2711 h: usize,
2712 row: usize,
2713 col: usize,
2714 class: TxClass,
2715) -> usize {
2716 let extra = match class {
2717 TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(),
2718 TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(),
2719 TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(),
2720 };
2721 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
2722 + neighbour_rect(grid, w, h, row, col + 1).abs()
2723 + extra;
2724 let mag = (((mag + 1) >> 1).min(6)) as usize;
2725 if row == 0 && col == 0 {
2726 return mag;
2727 }
2728 let near_origin = match class {
2729 TxClass::TwoD => row < 2 && col < 2,
2730 TxClass::Horiz => col == 0,
2731 TxClass::Vert => row == 0,
2732 };
2733 if near_origin { mag + 7 } else { mag + 14 }
2734}
2735
2736fn dc_vote(dc: Option<bool>) -> i32 {
2737 match dc {
2738 None => 0,
2739 Some(true) => -1,
2740 Some(false) => 1,
2741 }
2742}
2743
2744fn dc_sign_ctx(vote: i32) -> usize {
2745 match vote.signum() {
2746 0 => 0,
2747 -1 => 1,
2748 _ => 2,
2749 }
2750}
2751
2752/// The remainder of a level the base and base-range syntax could not reach
2753/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
2754/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
2755fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
2756 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
2757 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
2758 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
2759 // for every tail any encoder writes -- our own writer tops out at 19 zeros
2760 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
2761 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
2762 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
2763 // RED: seed 67 stops here today, and with the cap raised it decodes to a
2764 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
2765 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
2766 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
2767 // together with that defect's fix, not before.
2768 let mut length = 1u32;
2769 while dec.literal(1) == 0 {
2770 length += 1;
2771 if length > 20 {
2772 return Err(unsupported("a Golomb tail longer than this decoder reads"));
2773 }
2774 }
2775 let mut x = 1u32;
2776 for _ in 1..length {
2777 x = (x << 1) | dec.literal(1);
2778 }
2779 Ok(x - 1)
2780}
2781
2782/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
2783/// [`crate::tile`]'s `write_eob`.
2784fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
2785 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
2786 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
2787
2788 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2789 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
2790 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
2791 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
2792 // `eob_multi_ctx`). Missing that split desynced the very first
2793 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
2794 // against a real aomdec trace).
2795 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
2796 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
2797 (_, Some(class1)) => class1,
2798 };
2799 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2800 let (range, value) = dec.debug_state();
2801 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
2802 }
2803 let group = dec.symbol(eob_pt) + 1;
2804 if trace {
2805 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
2806 }
2807 let bits = OFFSET_BITS[group];
2808 let mut offset = 0u32;
2809 if bits > 0 {
2810 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
2811 if trace {
2812 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
2813 }
2814 offset = top << (bits - 1);
2815 if bits > 1 {
2816 offset |= dec.literal(bits - 1);
2817 }
2818 }
2819 GROUP_START[group] + offset as usize
2820}
2821
2822/// One transform block's levels, the inverse of [`crate::tile`]'s
2823/// `write_coeffs`, returned as a `side * side` grid in raster order, along
2824/// with the transform type that grid was coded under (`DCT_DCT` when the
2825/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
2826/// 64-point transforms, which never code anything else).
2827///
2828/// # Errors
2829/// Returns an error if the `tx_type` symbol decodes to a value outside its
2830/// CDF's own set (a corrupt or unsupported bitstream) — every value the
2831/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
2832/// produce dispatches to a real inverse transform.
2833/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
2834/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
2835/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
2836/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
2837/// the plane's own predicted mode instead. Every entry this table can
2838/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
2839/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
2840/// table ever names), so unlike the CDF-coded luma path there is no
2841/// ext-tx-set membership check to fall back from here.
2842fn default_intra_tx_type(mode: u8) -> TxType {
2843 use crate::intra::{
2844 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
2845 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
2846 };
2847 match mode {
2848 DC_PRED | D45_PRED => TxType::DctDct,
2849 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
2850 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
2851 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
2852 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
2853 }
2854}
2855
2856/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
2857/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
2858/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
2859fn is_smooth_mode(mode: usize) -> bool {
2860 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
2861}
2862
2863fn read_coeffs(
2864 dec: &mut SymbolDecoder,
2865 coding: &mut TxbTables,
2866 scan: &[u16],
2867 skip_ctx: usize,
2868 sign_ctx: usize,
2869 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
2870 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
2871 // nothing at all; `DctDct` for every luma call and every chroma call at
2872 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
2873 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
2874 default_tx_type: TxType,
2875 // `Some((w, h))` with `w != h` when this read is a superblock-level
2876 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
2877 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
2878 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
2879 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
2880 // caller's block genuinely is `side` x `side`.
2881 rect_shape: Option<(usize, usize)>,
2882) -> Result<(Vec<i32>, TxType)> {
2883 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2884 let side = coding.side;
2885 let mut grid = vec![0i32; side * side];
2886 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2887 let (range, value) = dec.debug_state();
2888 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
2889 }
2890 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
2891 if std::env::var_os("EC_TRACE_COEFF").is_some() {
2892 let (rng, _) = dec.debug_state();
2893 eprintln!(
2894 "EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero={} rng={rng}",
2895 all_zero as i32
2896 );
2897 }
2898 if std::env::var_os("EC_AV1_TELL").is_some() {
2899 eprintln!(
2900 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
2901 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
2902 );
2903 }
2904 if trace {
2905 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
2906 }
2907 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2908 let (range, value) = dec.debug_state();
2909 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
2910 }
2911 if all_zero {
2912 return Ok((grid, TxType::DctDct));
2913 }
2914 let mut tx_type = default_tx_type;
2915 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
2916 // The CDF row's own width names its set (lane-cdffwd2: extended
2917 // past the original two-way intra split once wider `reduced_tx_set
2918 // == 0` inter sets joined the table): 17 slots (16 symbols) is
2919 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
2920 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
2921 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
2922 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
2923 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
2924 let len = tx_type_cdf.len();
2925 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
2926 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
2927 }
2928 let t = dec.symbol(tx_type_cdf);
2929 if std::env::var_os("EC_TRACE_COEFF").is_some() {
2930 let (rng, _) = dec.debug_state();
2931 eprintln!("EC_COEFF_STEP tag=tx_type rng={rng}");
2932 }
2933 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2934 let (range, value) = dec.debug_state();
2935 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
2936 }
2937 if trace {
2938 eprintln!("TRACE tx_type value={t} len={len}");
2939 }
2940 tx_type = match len {
2941 17 => TxType::from_symbol_all16(t),
2942 13 => TxType::from_symbol_set2_12(t),
2943 8 => TxType::from_symbol_set1(t),
2944 _ => TxType::from_symbol(t),
2945 }
2946 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
2947 }
2948
2949 let class = TxClass::of(tx_type);
2950 if class != TxClass::TwoD {
2951 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
2952 }
2953 let eob = read_eob(dec, coding, class);
2954 if trace {
2955 eprintln!("TRACE eob value={eob}");
2956 }
2957 let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some();
2958 if ec_trace_coeff {
2959 let (rng, _) = dec.debug_state();
2960 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
2961 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
2962 }
2963 let class_scan;
2964 let scan: &[u16] = if class == TxClass::TwoD {
2965 scan
2966 } else {
2967 class_scan = class_scan_table(side, class);
2968 &class_scan
2969 };
2970 let mut levels = vec![0i32; side * side];
2971 for scan_idx in (0..eob).rev() {
2972 let pos = scan[scan_idx] as usize;
2973 let (row, col) = (pos / side, pos % side);
2974 let level = if scan_idx == eob - 1 {
2975 let ctx = eob_coeff_ctx(scan_idx, side * side);
2976 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
2977 if trace {
2978 eprintln!(
2979 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
2980 );
2981 }
2982 v
2983 } else {
2984 let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
2985 let v = dec.symbol(&mut coding.base[ctx]) as i32;
2986 if ec_trace_coeff {
2987 let (rng, _) = dec.debug_state();
2988 // `pos` in libaom's column-major `coeff_idx` convention, so
2989 // the ladder lines up with instrumented `aomdec`.
2990 let apos = col * side + row;
2991 eprintln!(
2992 "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"
2993 );
2994 }
2995 if trace {
2996 eprintln!(
2997 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
2998 );
2999 }
3000 v
3001 };
3002 let level = if level > NUM_BASE_LEVELS {
3003 let ctx = br_ctx(&levels, side, row, col, class);
3004 let mut level = level;
3005 let mut sent = 0;
3006 loop {
3007 let k = dec.symbol(&mut coding.br[ctx]) as i32;
3008 if trace {
3009 eprintln!(
3010 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
3011 );
3012 }
3013 level += k;
3014 sent += BR_STEP;
3015 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
3016 break;
3017 }
3018 }
3019 level
3020 } else {
3021 level
3022 };
3023 if ec_trace_coeff && scan_idx == eob - 1 {
3024 let (rng, _) = dec.debug_state();
3025 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
3026 }
3027 levels[pos] = level;
3028 }
3029 if ec_trace_coeff {
3030 let (rng, _) = dec.debug_state();
3031 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
3032 }
3033
3034 for (c, &pos) in scan[..eob].iter().enumerate() {
3035 let level = levels[pos as usize];
3036 if level == 0 {
3037 continue;
3038 }
3039 let negative = if pos == 0 {
3040 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
3041 if trace {
3042 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
3043 }
3044 v
3045 } else {
3046 dec.literal(1) == 1
3047 };
3048 if ec_trace_coeff {
3049 let (rng, _) = dec.debug_state();
3050 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
3051 }
3052 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
3053 let g = read_golomb(dec)?;
3054 if trace {
3055 eprintln!("TRACE golomb pos={pos} value={g}");
3056 }
3057 level + g as i32
3058 } else {
3059 level
3060 };
3061 if ec_trace_coeff {
3062 let (rng, _) = dec.debug_state();
3063 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
3064 }
3065 grid[pos as usize] = if negative { -level } else { level };
3066 }
3067 Ok((grid, tx_type))
3068}
3069
3070/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
3071/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
3072/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
3073/// can ever produce, since every `tx_type` this decoder's rect sets can read
3074/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
3075/// rather than guess-decode if a non-2D class ever shows up here, since
3076/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
3077/// form for those.
3078fn read_coeffs_rect(
3079 dec: &mut SymbolDecoder,
3080 coding: &mut TxbTables,
3081 scan: &[u16],
3082 w: usize,
3083 h: usize,
3084 skip_ctx: usize,
3085 sign_ctx: usize,
3086 default_tx_type: TxType,
3087) -> Result<(Vec<i32>, TxType)> {
3088 let rect_trace = std::env::var_os("EC_TRACE_COEFF").is_some();
3089 let mut grid = vec![0i32; w * h];
3090 let entry_rng = dec.debug_state().0;
3091 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
3092 if rect_trace {
3093 eprintln!(
3094 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} all_zero={} rng={}",
3095 all_zero as i32,
3096 dec.debug_state().0
3097 );
3098 }
3099 if all_zero {
3100 return Ok((grid, TxType::DctDct));
3101 }
3102 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
3103 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
3104 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
3105 // context offsets -- both of which now have rect forms
3106 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
3107 // The rect sets that carry no symbol at all still pass `None` here.
3108 let mut tx_type = default_tx_type;
3109 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
3110 let len = tx_type_cdf.len();
3111 let t = dec.symbol(tx_type_cdf);
3112 tx_type = match len {
3113 17 => TxType::from_symbol_all16(t),
3114 13 => TxType::from_symbol_set2_12(t),
3115 8 => TxType::from_symbol_set1(t),
3116 _ => TxType::from_symbol(t),
3117 }
3118 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
3119 if rect_trace {
3120 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
3121 }
3122 }
3123 let class = TxClass::of(tx_type);
3124 if class != TxClass::TwoD {
3125 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3126 }
3127 let eob = read_eob(dec, coding, class);
3128 if rect_trace {
3129 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
3130 }
3131 let class_scan;
3132 let scan: &[u16] = if class == TxClass::TwoD {
3133 scan
3134 } else {
3135 class_scan = class_scan_table_wh(w, h, class);
3136 &class_scan
3137 };
3138 let mut levels = vec![0i32; w * h];
3139 for scan_idx in (0..eob).rev() {
3140 let pos = scan[scan_idx] as usize;
3141 let (row, col) = (pos / w, pos % w);
3142 // libaom's column-major `coeff_idx`, for ladder comparison.
3143 let apos = col * h + row;
3144 let level = if scan_idx == eob - 1 {
3145 let ctx = eob_coeff_ctx(scan_idx, w * h);
3146 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
3147 if rect_trace {
3148 eprintln!(
3149 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
3150 dec.debug_state().0
3151 );
3152 }
3153 v
3154 } else {
3155 let ctx = base_ctx_rect(&levels, w, h, row, col, class);
3156 let v = dec.symbol(&mut coding.base[ctx]) as i32;
3157 if rect_trace {
3158 eprintln!(
3159 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
3160 dec.debug_state().0
3161 );
3162 }
3163 v
3164 };
3165 let level = if level > NUM_BASE_LEVELS {
3166 let ctx = br_ctx_rect(&levels, w, h, row, col, class);
3167 let mut level = level;
3168 let mut sent = 0;
3169 loop {
3170 let k = dec.symbol(&mut coding.br[ctx]) as i32;
3171 if rect_trace {
3172 eprintln!(
3173 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
3174 dec.debug_state().0
3175 );
3176 }
3177 level += k;
3178 sent += BR_STEP;
3179 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
3180 break;
3181 }
3182 }
3183 level
3184 } else {
3185 level
3186 };
3187 levels[pos] = level;
3188 if rect_trace {
3189 let (rng, _) = dec.debug_state();
3190 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
3191 }
3192 }
3193 if rect_trace {
3194 let (rng, _) = dec.debug_state();
3195 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
3196 }
3197 for &pos in &scan[..eob] {
3198 let level = levels[pos as usize];
3199 if level == 0 {
3200 continue;
3201 }
3202 let negative = if pos == 0 {
3203 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
3204 } else {
3205 dec.literal(1) == 1
3206 };
3207 if rect_trace {
3208 let (rng, _) = dec.debug_state();
3209 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} rng={rng}", u8::from(negative));
3210 }
3211 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
3212 let g = read_golomb(dec)?;
3213 level + g as i32
3214 } else {
3215 level
3216 };
3217 grid[pos as usize] = if negative { -level } else { level };
3218 }
3219 Ok((grid, tx_type))
3220}
3221
3222/// What one coded block leaves behind for the blocks that read it as a
3223/// neighbour: whether it coded anything at all, and the sign of its DC —
3224/// [`crate::tile`]'s own private `Neighbour`.
3225#[derive(Clone, Copy, Default)]
3226struct Neighbour {
3227 /// The transform unit's cumulative coefficient level (spec `cul_level`,
3228 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
3229 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
3230 /// boolean (`level != 0`) is enough for every context this decoder read
3231 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
3232 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
3233 /// needs the actual magnitude tier of its above/left neighbours, not
3234 /// just whether they coded anything.
3235 level: u8,
3236 dc: Option<bool>,
3237}
3238
3239fn neighbour_state(grid: &[i32]) -> Neighbour {
3240 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
3241 Neighbour {
3242 level: cul.min(7) as u8,
3243 dc: (grid[0] != 0).then_some(grid[0] < 0),
3244 }
3245}
3246
3247/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
3248/// transform unit smaller than the block it sits in): `top`/`left` are the
3249/// above/left neighbours' magnitude tiers, each already clamped to 4.
3250const SKIP_CONTEXTS: [[usize; 5]; 5] = [
3251 [1, 2, 2, 2, 3],
3252 [2, 4, 4, 4, 5],
3253 [2, 4, 4, 4, 5],
3254 [2, 4, 4, 4, 5],
3255 [3, 5, 5, 5, 6],
3256];
3257
3258/// The neighbour state a block's contexts are read from — a duplicate of
3259/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
3260/// territory this round), kept at the same two granularities the real writer
3261/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
3262/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
3263/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
3264/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
3265/// chroma transform straddling the true, odd-sized frame edge see its
3266/// neighbour's state clamped at its own subsampled edge rather than luma's.
3267struct Neighbours {
3268 above: Vec<[Neighbour; 3]>,
3269 left: Vec<[Neighbour; 3]>,
3270 above_mode: Vec<usize>,
3271 left_mode: Vec<usize>,
3272 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
3273 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
3274 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
3275 /// luma one -- the same block can (and often does) code a different
3276 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
3277 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
3278 /// within-block neighbour finer than this grid) is luma-only -- a known,
3279 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
3280 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
3281 above_uv_mode: Vec<usize>,
3282 left_uv_mode: Vec<usize>,
3283 above_side: Vec<usize>,
3284 left_side: Vec<usize>,
3285 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
3286 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
3287 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
3288 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
3289 /// array cannot tell the second leaf's partition symbol that the first
3290 /// one was coded at 8x8.
3291 above_side_mi: Vec<usize>,
3292 left_side_mi: Vec<usize>,
3293 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
3294 /// / row, with the mi position it was written at
3295 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
3296 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
3297 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
3298 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
3299 /// leaf whose neighbour is another split group needs that group's leaf 3
3300 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
3301 /// and read only by [`decode_leaf_split4`]; the position guard makes it
3302 /// fall back to the coarse slot whenever the real neighbour was a block
3303 /// of 8x8 or larger (whose one mode is correct for every row it spans).
3304 sub8_mode_col: Vec<(usize, usize)>,
3305 sub8_mode_row: Vec<(usize, usize)>,
3306 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
3307 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
3308 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
3309 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
3310 /// the leaf above writes the same row slot the block to the left owns.
3311 uv_mode_col: Vec<(usize, usize)>,
3312 uv_mode_row: Vec<(usize, usize)>,
3313 /// Whether the block above/left of this column/row was coded `skip` --
3314 /// an inter frame's own `skip` context (spec `SkipContext`), which the
3315 /// key-frame writer never tracks (its skip context is always zero); a
3316 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
3317 /// `left_skip`.
3318 above_skip: Vec<bool>,
3319 left_skip: Vec<bool>,
3320 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
3321 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
3322 /// pixels last written over each unit by `set_txfm_ctxs`/
3323 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
3324 /// symbol reads its context from (lane-txselect, spec 5.11.17).
3325 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
3326 /// array is exactly libaom's per-superblock-row reset, since each mi row
3327 /// is only ever visited inside one superblock row.
3328 above_txfm: Vec<u8>,
3329 left_txfm: Vec<u8>,
3330 /// Whether the block above/left of this column/row coded `skip_mode`
3331 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
3332 /// lane-av1comp round 14.
3333 above_skip_mode: Vec<bool>,
3334 left_skip_mode: Vec<bool>,
3335 /// Whether the block above/left was coded inter -- the `is_inter`
3336 /// context (spec `av1_get_intra_inter_context`), a duplicate of
3337 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
3338 above_inter: Vec<bool>,
3339 left_inter: Vec<bool>,
3340 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
3341 /// alphabet) the block above/left of this column/row coded, or `-1` for
3342 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
3343 /// functions (`mvstack::ref_ctx` family) need the real reference, not
3344 /// just "was it inter" (lane-av1refs: every inter block used to be
3345 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
3346 /// enough).
3347 above_ref: Vec<i8>,
3348 left_ref: Vec<i8>,
3349 /// The block above/left's *second* reference frame when it was coded
3350 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
3351 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
3352 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
3353 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
3354 /// (no decode path here ever produces a compound block yet).
3355 above_ref1: Vec<Option<i8>>,
3356 left_ref1: Vec<Option<i8>>,
3357 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
3358 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
3359 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
3360 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
3361 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
3362 above_comp_group_idx: Vec<u8>,
3363 left_comp_group_idx: Vec<u8>,
3364 above_compound_idx: Vec<u8>,
3365 left_compound_idx: Vec<u8>,
3366 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
3367 /// `3` = "no info": an intra neighbour or the frame's own border) of the
3368 /// block above/left of this column/row -- spec
3369 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
3370 above_filter: Vec<[u8; 2]>,
3371 left_filter: Vec<[u8; 2]>,
3372 mi_cols: usize,
3373 mi_rows: usize,
3374 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
3375 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
3376 /// 7.15) never filters an 8x8 luma block whose covering coded block read
3377 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
3378 /// grain [`Self::record_mi`] already writes at), read back at 8x8
3379 /// granularity by [`apply_cdef`] since `skip` is constant across every
3380 /// mi cell one coded block covers.
3381 skip_grid: Vec<bool>,
3382 skip_grid_cols_mi: usize,
3383 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
3384 /// never splits a coded block's transform below its own size (round 2:
3385 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
3386 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
3387 /// edge-length lookup (`apply_deblock`).
3388 tx_grid: Vec<u8>,
3389 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
3390 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
3391 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
3392 tx_h_grid: Vec<u8>,
3393 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
3394 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
3395 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
3396 /// does NOT follow luma's `tx_depth` split, so deriving it as
3397 /// `tx_grid / 2` invented chroma transform edges the deblocker then
3398 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
3399 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
3400 /// every caller routes through.
3401 uv_tx_grid: Vec<u8>,
3402 uv_tx_h_grid: Vec<u8>,
3403 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
3404 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
3405 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
3406 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
3407 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
3408 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
3409 /// reference onto `LAST_FRAME`'s own delta).
3410 ref_grid: Vec<i8>,
3411 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
3412 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
3413 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
3414 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
3415 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
3416 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
3417 /// to know which mode produced the value.
3418 delta_lf_grid: Vec<[i8; 4]>,
3419 /// The block above/left's own palette-Y size (0 = not a palette block)
3420 /// and its base colours -- `av1_get_palette_mode_ctx`/
3421 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
3422 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
3423 above_palette_size: Vec<usize>,
3424 left_palette_size: Vec<usize>,
3425 above_palette_colors: Vec<[u16; 8]>,
3426 left_palette_colors: Vec<[u16; 8]>,
3427 /// As the four fields above, for the neighbour's own chroma (U-channel
3428 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
3429 /// palette size/colours (lane-palette2 r1).
3430 above_palette_uv_size: Vec<usize>,
3431 left_palette_uv_size: Vec<usize>,
3432 above_palette_uv_colors: Vec<[u16; 8]>,
3433 left_palette_uv_colors: Vec<[u16; 8]>,
3434 /// This tile's own top-left corner, in 4x4 mode-info units (spec
3435 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
3436 /// neighbour" check compares against this instead of literal `0`, since a
3437 /// block at the tile's own top/left edge has no usable neighbour even
3438 /// though a decoded block sits there in the picture (spec `decode_tile`'s
3439 /// per-tile `clear_above_context`/`left_available`/`up_available`).
3440 /// `0` for a single-tile frame, matching every existing caller exactly.
3441 tile_row0_mi: usize,
3442 tile_col0_mi: usize,
3443}
3444
3445impl Neighbours {
3446 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
3447 /// true (unpadded) size in 4x4 mode-info units.
3448 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
3449 Self {
3450 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
3451 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
3452 above_mode: vec![DC_PRED; cols],
3453 left_mode: vec![DC_PRED; rows],
3454 above_uv_mode: vec![DC_PRED; cols],
3455 left_uv_mode: vec![DC_PRED; rows],
3456 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
3457 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
3458 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
3459 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
3460 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3461 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3462 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3463 uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3464 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
3465 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
3466 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
3467 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
3468 // 16x16 block beside it, which a SUB-grid slot cannot name
3469 // (class context-read-from-one-cell).
3470 above_skip: vec![false; cols * (SUB / MI)],
3471 left_skip: vec![false; rows * (SUB / MI)],
3472 above_skip_mode: vec![false; cols * (SUB / MI)],
3473 left_skip_mode: vec![false; rows * (SUB / MI)],
3474 above_inter: vec![false; cols * (SUB / MI)],
3475 left_inter: vec![false; rows * (SUB / MI)],
3476 above_ref: vec![-1; cols * (SUB / MI)],
3477 left_ref: vec![-1; rows * (SUB / MI)],
3478 above_ref1: vec![None; cols * (SUB / MI)],
3479 left_ref1: vec![None; rows * (SUB / MI)],
3480 above_comp_group_idx: vec![0; cols * (SUB / MI)],
3481 left_comp_group_idx: vec![0; rows * (SUB / MI)],
3482 above_compound_idx: vec![0; cols * (SUB / MI)],
3483 left_compound_idx: vec![0; rows * (SUB / MI)],
3484 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
3485 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
3486 mi_cols,
3487 mi_rows,
3488 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
3489 skip_grid_cols_mi: cols * (SUB / MI),
3490 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3491 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3492 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3493 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3494 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
3495 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
3496 above_palette_size: vec![0; cols],
3497 left_palette_size: vec![0; rows],
3498 above_palette_colors: vec![[0u16; 8]; cols],
3499 left_palette_colors: vec![[0u16; 8]; rows],
3500 above_palette_uv_size: vec![0; cols],
3501 left_palette_uv_size: vec![0; rows],
3502 above_palette_uv_colors: vec![[0u16; 8]; cols],
3503 left_palette_uv_colors: vec![[0u16; 8]; rows],
3504 tile_row0_mi: 0,
3505 tile_col0_mi: 0,
3506 }
3507 }
3508
3509 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
3510 /// tile's own column span (`col1_mi` exclusive), plus recording
3511 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
3512 /// availability check below. Left context resets every superblock row
3513 /// regardless of tile ([`Self::start_row`], already called once per SB
3514 /// row by every caller) so it needs no tile-specific reset here.
3515 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
3516 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
3517 // are tile-relative, same as every other neighbour lookup here.
3518 SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
3519 self.tile_row0_mi = row0_mi;
3520 self.tile_col0_mi = col0_mi;
3521 let end = col1_mi.min(self.above.len());
3522 for i in col0_mi.min(end)..end {
3523 self.above[i] = Default::default();
3524 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE;
3525 }
3526 let (sc0, sc1) = (
3527 col0_mi / (SUB / MI),
3528 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
3529 );
3530 for i in sc0.min(sc1)..sc1 {
3531 self.above_mode[i] = DC_PRED;
3532 self.above_side[i] = NO_NEIGHBOUR_SIDE;
3533 }
3534 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
3535 // the tile's own mi column span directly.
3536 let mend = col1_mi.min(self.above_skip.len());
3537 for i in col0_mi.min(mend)..mend {
3538 self.above_skip[i] = false;
3539 self.above_skip_mode[i] = false;
3540 self.above_inter[i] = false;
3541 self.above_ref[i] = -1;
3542 self.above_ref1[i] = None;
3543 self.above_comp_group_idx[i] = 0;
3544 self.above_compound_idx[i] = 0;
3545 self.above_filter[i] = [3u8; 2];
3546 }
3547 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
3548 // stale `(row, mode)` from the tile to the LEFT names an mi row this
3549 // tile's first block would read as its own above neighbour.
3550 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
3551 for i in col0_mi.min(mcol_end)..mcol_end {
3552 self.sub8_mode_col[i] = (usize::MAX, 0);
3553 self.uv_mode_col[i] = (usize::MAX, 0);
3554 }
3555 }
3556
3557 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
3558 /// for a non-palette block, clearing any stale neighbour state) into every
3559 /// [`SUB`]-grid cell it covers on both the above and left edges --
3560 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
3561 /// call sites are all square blocks).
3562 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3563 self.record_palette_y_rect(at, side, side, size, colors);
3564 }
3565
3566 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
3567 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
3568 /// [`Self::record`]): a true rect strip's above/left neighbour spans
3569 /// differ.
3570 fn record_palette_y_rect(
3571 &mut self,
3572 at: (usize, usize),
3573 w: usize,
3574 h: usize,
3575 size: usize,
3576 colors: [u16; 8],
3577 ) {
3578 let (r, c) = at;
3579 // `.max(1)`: a below-16px span covers no whole SUB cell, so the plain
3580 // `w / SUB` loop was a NO-OP for every 16x8/8x16/8x8/4x4 leaf and the
3581 // next block read a long-dead palette out of the above/left arrays
3582 // (class [[cdf-row-held-constant]], lane-palette2 r8). libaom keeps
3583 // `palette_size` per 4px mi cell; corner-cut: our grid is 16px, so a
3584 // sub-16 leaf stamps its whole containing cell -- safe today because
3585 // every sub-16 leaf path refuses palette outright (so it can only
3586 // ever stamp `size == 0`, and its cell holds no palette sibling).
3587 // Upgrade path: widen the palette arrays to mi granularity.
3588 for cell in 0..(w / SUB).max(1) {
3589 self.above_palette_size[c + cell] = size;
3590 self.above_palette_colors[c + cell] = colors;
3591 }
3592 for cell in 0..(h / SUB).max(1) {
3593 self.left_palette_size[r + cell] = size;
3594 self.left_palette_colors[r + cell] = colors;
3595 }
3596 }
3597
3598 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
3599 /// neighbours that are themselves a palette-Y block, plus
3600 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
3601 /// cache (pred_common.c:73).
3602 ///
3603 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
3604 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
3605 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
3606 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
3607 /// the ctx too made every superblock in the frame's second SB row read
3608 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
3609 /// palette block decoded as "no palette" and the tile desynced from
3610 /// there (class [[cdf-row-held-constant]]).
3611 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
3612 let (r, c) = at;
3613 let above_ok = r % 4 != 0;
3614 // `xd->above_mbmi` exists for every row but the tile's own first.
3615 let above_is_palette =
3616 r * (SUB / MI) > self.tile_row0_mi && self.above_palette_size[c] > 0;
3617 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
3618 (self.above_palette_size[c], self.above_palette_colors[c])
3619 } else {
3620 (0, [0u16; 8])
3621 };
3622 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
3623 // is NULL whenever the block sits at its TILE's own left column
3624 // (`left_available`), not the frame's -- without this guard a second
3625 // tile column reads the previous tile's palette colours into its cache
3626 // and its `palette_y_mode` ctx.
3627 let left_ok = c > self.tile_col0_mi / (SUB / MI);
3628 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
3629 (self.left_palette_size[r], self.left_palette_colors[r])
3630 } else {
3631 (0, [0u16; 8])
3632 };
3633 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
3634 let mut cache = Vec::with_capacity(16);
3635 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3636 if cache.last() != Some(&v) {
3637 cache.push(v);
3638 }
3639 };
3640 let (mut ai, mut li) = (0usize, 0usize);
3641 while ai < above_n && li < left_n {
3642 let (va, vl) = (above_colors[ai], left_colors[li]);
3643 if vl < va {
3644 push_dedup(&mut cache, vl);
3645 li += 1;
3646 } else {
3647 push_dedup(&mut cache, va);
3648 ai += 1;
3649 if vl == va {
3650 li += 1;
3651 }
3652 }
3653 }
3654 while ai < above_n {
3655 push_dedup(&mut cache, above_colors[ai]);
3656 ai += 1;
3657 }
3658 while li < left_n {
3659 push_dedup(&mut cache, left_colors[li]);
3660 li += 1;
3661 }
3662 (ctx, cache)
3663 }
3664
3665 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
3666 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
3667 /// same way (lane-palette2 r1).
3668 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3669 self.record_palette_uv_rect(at, side, side, size, colors);
3670 }
3671
3672 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
3673 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
3674 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
3675 /// luma resolution regardless of which plane the recorded state is for).
3676 fn record_palette_uv_rect(
3677 &mut self,
3678 at: (usize, usize),
3679 w: usize,
3680 h: usize,
3681 size: usize,
3682 colors: [u16; 8],
3683 ) {
3684 let (r, c) = at;
3685 // See [`Self::record_palette_y_rect`] for the `.max(1)`.
3686 for cell in 0..(w / SUB).max(1) {
3687 self.above_palette_uv_size[c + cell] = size;
3688 self.above_palette_uv_colors[c + cell] = colors;
3689 }
3690 for cell in 0..(h / SUB).max(1) {
3691 self.left_palette_uv_size[r + cell] = size;
3692 self.left_palette_uv_colors[r + cell] = colors;
3693 }
3694 }
3695
3696 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
3697 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
3698 /// no neighbour lookup at all (it is this block's own just-decided Y
3699 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
3700 /// so only the cache is wanted here.
3701 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
3702 let (r, c) = at;
3703 let above_ok = r % 4 != 0;
3704 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
3705 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
3706 } else {
3707 (0, [0u16; 8])
3708 };
3709 // Same tile-relative left availability as the luma cache above.
3710 let left_ok = c > self.tile_col0_mi / (SUB / MI);
3711 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
3712 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
3713 } else {
3714 (0, [0u16; 8])
3715 };
3716 let mut cache = Vec::with_capacity(16);
3717 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3718 if cache.last() != Some(&v) {
3719 cache.push(v);
3720 }
3721 };
3722 let (mut ai, mut li) = (0usize, 0usize);
3723 while ai < above_n && li < left_n {
3724 let (va, vl) = (above_colors[ai], left_colors[li]);
3725 if vl < va {
3726 push_dedup(&mut cache, vl);
3727 li += 1;
3728 } else {
3729 push_dedup(&mut cache, va);
3730 ai += 1;
3731 if vl == va {
3732 li += 1;
3733 }
3734 }
3735 }
3736 while ai < above_n {
3737 push_dedup(&mut cache, above_colors[ai]);
3738 ai += 1;
3739 }
3740 while li < left_n {
3741 push_dedup(&mut cache, left_colors[li]);
3742 li += 1;
3743 }
3744 cache
3745 }
3746
3747 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
3748 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
3749 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
3750 /// units as [`Self::fill_skip_grid`].
3751 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
3752 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
3753 }
3754
3755 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
3756 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
3757 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
3758 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
3759 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
3760 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
3761 fn fill_lf_grid_rect(
3762 &mut self,
3763 at_mi: (usize, usize),
3764 w_mi: usize,
3765 h_mi: usize,
3766 tx_px: u8,
3767 tx_h_px: u8,
3768 ref_frame: i8,
3769 ) {
3770 let (mi_r, mi_c) = at_mi;
3771 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
3772 // half its luma one (min 4 px, the smallest transform), capped at
3773 // TX_32X32 -- independent of this block's luma `tx_depth`.
3774 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
3775 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
3776 let cur = CURRENT_DELTA_LF.with(|c| c.get());
3777 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
3778 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
3779 } else {
3780 [cur[0].clamp(-63, 63) as i8; 4]
3781 };
3782 for rr in 0..h_mi {
3783 for cc in 0..w_mi {
3784 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
3785 if let Some(cell) = self.tx_grid.get_mut(idx) {
3786 *cell = tx_px;
3787 }
3788 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
3789 *cell = tx_h_px;
3790 }
3791 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
3792 *cell = uv_tx_w;
3793 }
3794 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
3795 *cell = uv_tx_h;
3796 }
3797 if let Some(cell) = self.ref_grid.get_mut(idx) {
3798 *cell = ref_frame;
3799 }
3800 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
3801 *cell = snapshot;
3802 }
3803 }
3804 }
3805 }
3806
3807 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
3808 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
3809 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
3810 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
3811 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
3812 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
3813 }
3814
3815 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
3816 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
3817 let (mi_r, mi_c) = at_mi;
3818 for rr in 0..h_mi {
3819 for cc in 0..w_mi {
3820 if let Some(cell) = self
3821 .skip_grid
3822 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
3823 {
3824 *cell = skip;
3825 }
3826 }
3827 }
3828 }
3829
3830 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
3831 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
3832 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
3833 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
3834 /// straddle the region with a mix of skip/non-skip blocks).
3835 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
3836 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
3837 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
3838 /// filtered edge's two sides are each exactly one coded block wide.
3839 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
3840 self.skip_grid
3841 .get(mi_r * self.skip_grid_cols_mi + mi_c)
3842 .copied()
3843 .unwrap_or(false)
3844 }
3845
3846 /// The `skip_txfm` context of a block whose top-left mi cell is
3847 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
3848 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
3849 /// with an absent neighbour contributing 0. The mi grid is per tile, so
3850 /// row/column 0 is a tile edge and has no neighbour on that axis.
3851 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
3852 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
3853 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
3854 }
3855
3856 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
3857 (0..2).all(|rr| {
3858 (0..2).all(|cc| {
3859 self.skip_grid
3860 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
3861 .copied()
3862 .unwrap_or(false)
3863 })
3864 })
3865 }
3866
3867 fn start_row(&mut self) {
3868 self.left.iter_mut().for_each(|l| *l = Default::default());
3869 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
3870 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
3871 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3872 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3873 self.left_skip.iter_mut().for_each(|s| *s = false);
3874 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
3875 self.left_inter.iter_mut().for_each(|i| *i = false);
3876 self.left_ref.iter_mut().for_each(|r| *r = -1);
3877 self.left_ref1.iter_mut().for_each(|r| *r = None);
3878 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
3879 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
3880 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
3881 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
3882 // context (a tile/SB-row boundary has no left neighbour).
3883 self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
3884 self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
3885 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
3886 // are per-mi maps like every other one here, so they reset with the
3887 // row too -- the left guard above is what actually stops a cross-tile
3888 // read, this keeps a stale colour out of the arrays at all.
3889 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
3890 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
3891 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
3892 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
3893 }
3894
3895 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
3896 /// block that reads it as a neighbour -- [`crate::tile`]'s
3897 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
3898 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
3899 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
3900 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
3901 /// the real value, not just `is_inter`).
3902 fn record_inter(
3903 &mut self,
3904 at: (usize, usize),
3905 side: usize,
3906 skip: bool,
3907 is_inter: bool,
3908 ref_frame: i8,
3909 filter: [u8; 2],
3910 skip_mode: bool,
3911 ) {
3912 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
3913 }
3914
3915 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
3916 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
3917 /// r1: a true rectangular strip's above-context span (its own width) and
3918 /// left-context span (its own height) differ, unlike every caller before
3919 /// this round (class neighbour-votes-all-its-fields).
3920 #[allow(clippy::too_many_arguments)]
3921 fn record_inter_rect(
3922 &mut self,
3923 at: (usize, usize),
3924 w_sub: usize,
3925 h_sub: usize,
3926 skip: bool,
3927 is_inter: bool,
3928 ref_frame: i8,
3929 filter: [u8; 2],
3930 skip_mode: bool,
3931 ) {
3932 let (r, c) = at;
3933 self.record_inter_rect_mi(
3934 (r * (SUB / MI), c * (SUB / MI)),
3935 w_sub / MI,
3936 h_sub / MI,
3937 skip,
3938 is_inter,
3939 ref_frame,
3940 filter,
3941 skip_mode,
3942 );
3943 }
3944
3945 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
3946 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
3947 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
3948 /// routes through the wrapper above.
3949 #[allow(clippy::too_many_arguments)]
3950 fn record_inter_rect_mi(
3951 &mut self,
3952 at_mi: (usize, usize),
3953 w_mi: usize,
3954 h_mi: usize,
3955 skip: bool,
3956 is_inter: bool,
3957 ref_frame: i8,
3958 filter: [u8; 2],
3959 skip_mode: bool,
3960 ) {
3961 let (r, c) = at_mi;
3962 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
3963 for cell in 0..w_mi {
3964 self.above_skip[c + cell] = skip;
3965 self.above_skip_mode[c + cell] = skip_mode;
3966 self.above_inter[c + cell] = is_inter;
3967 self.above_ref[c + cell] = ref_frame;
3968 // lane-av1comp: no caller of `record_inter` ever decodes a
3969 // compound block yet (see [`Self::above_ref1`]'s doc); the
3970 // parameter this becomes lands with `read_ref_frames`.
3971 self.above_ref1[c + cell] = None;
3972 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
3973 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
3974 // as `3`/`1` even though this block has no second reference.
3975 // `record_compound_ctx` overwrites this with the real bit for an
3976 // actual compound block's cells, called right after this one.
3977 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
3978 self.above_compound_idx[c + cell] = u8::from(altref);
3979 self.above_filter[c + cell] = filter;
3980 }
3981 for cell in 0..h_mi {
3982 self.left_skip[r + cell] = skip;
3983 self.left_skip_mode[r + cell] = skip_mode;
3984 self.left_inter[r + cell] = is_inter;
3985 self.left_ref[r + cell] = ref_frame;
3986 self.left_ref1[r + cell] = None;
3987 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
3988 self.left_compound_idx[r + cell] = u8::from(altref);
3989 self.left_filter[r + cell] = filter;
3990 }
3991 }
3992
3993 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
3994 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
3995 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
3996 /// `get_comp_index_context`) -- called right after `record_inter` for
3997 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
3998 /// stamps `above_ref1`/`left_ref1` with the block's real second
3999 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
4000 /// this is the one caller that actually knows it) -- so the next block's
4001 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
4002 /// neighbour instead of `record_inter`'s single-ref default.
4003 fn record_compound_ctx(
4004 &mut self,
4005 at: (usize, usize),
4006 side: usize,
4007 ref1: i8,
4008 comp_group_idx: u8,
4009 compound_idx: u8,
4010 ) {
4011 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
4012 }
4013
4014 /// [`Self::record_compound_ctx`] with independent above/left extents,
4015 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
4016 #[allow(clippy::too_many_arguments)]
4017 fn record_compound_ctx_rect(
4018 &mut self,
4019 at: (usize, usize),
4020 w_sub: usize,
4021 h_sub: usize,
4022 ref1: i8,
4023 comp_group_idx: u8,
4024 compound_idx: u8,
4025 ) {
4026 let (r, c) = at;
4027 self.record_compound_ctx_rect_mi(
4028 (r * (SUB / MI), c * (SUB / MI)),
4029 w_sub / MI,
4030 h_sub / MI,
4031 ref1,
4032 comp_group_idx,
4033 compound_idx,
4034 );
4035 }
4036
4037 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
4038 /// [`Self::record_inter_rect_mi`]).
4039 fn record_compound_ctx_rect_mi(
4040 &mut self,
4041 at_mi: (usize, usize),
4042 w_mi: usize,
4043 h_mi: usize,
4044 ref1: i8,
4045 comp_group_idx: u8,
4046 compound_idx: u8,
4047 ) {
4048 let (r, c) = at_mi;
4049 for cell in 0..w_mi {
4050 self.above_ref1[c + cell] = Some(ref1);
4051 self.above_comp_group_idx[c + cell] = comp_group_idx;
4052 self.above_compound_idx[c + cell] = compound_idx;
4053 }
4054 for cell in 0..h_mi {
4055 self.left_ref1[r + cell] = Some(ref1);
4056 self.left_comp_group_idx[r + cell] = comp_group_idx;
4057 self.left_compound_idx[r + cell] = compound_idx;
4058 }
4059 }
4060
4061 /// The context of a block's partition symbol: delegates to the mi-precise
4062 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
4063 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
4064 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
4065 /// only touches the finer mi arrays -- leaves them stale for the *next*
4066 /// sibling's own partition symbol.
4067 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
4068 let (r, c) = at;
4069 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
4070 }
4071
4072 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
4073 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
4074 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
4075 /// than the enclosing 16x16 slot's stale, shared state.
4076 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
4077 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
4078 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
4079 }
4080
4081 /// The gathered coded/DC-sign state of the blocks above and to the left
4082 /// of a block `side` samples across, per plane.
4083 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
4084 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
4085 }
4086
4087 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
4088 /// units, for the same reason [`Self::record_mi`] does.
4089 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
4090 let side_mi = side / MI;
4091 std::array::from_fn(|plane| {
4092 let mut above_coded = false;
4093 let mut left_coded = false;
4094 let mut vote = 0;
4095 for cell in 0..side_mi {
4096 let above = &self.above[mi_c + cell][plane];
4097 let left = &self.left[mi_r + cell][plane];
4098 above_coded |= above.level != 0;
4099 left_coded |= left.level != 0;
4100 vote += dc_vote(above.dc) + dc_vote(left.dc);
4101 }
4102 (above_coded, left_coded, vote)
4103 })
4104 }
4105
4106 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
4107 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
4108 /// extent pattern for a true rectangular strip's own coefficient context.
4109 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
4110 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
4111 }
4112
4113 /// [`Self::around_rect`] taking the block's position directly in 4x4
4114 /// mode-info units, mirroring [`Self::around_mi`].
4115 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
4116 let (w_mi, h_mi) = (w / MI, h / MI);
4117 std::array::from_fn(|plane| {
4118 let mut above_coded = false;
4119 let mut left_coded = false;
4120 let mut vote = 0;
4121 for cell in 0..w_mi {
4122 let above = &self.above[mi_c + cell][plane];
4123 above_coded |= above.level != 0;
4124 vote += dc_vote(above.dc);
4125 }
4126 for cell in 0..h_mi {
4127 let left = &self.left[mi_r + cell][plane];
4128 left_coded |= left.level != 0;
4129 vote += dc_vote(left.dc);
4130 }
4131 (above_coded, left_coded, vote)
4132 })
4133 }
4134
4135 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
4136 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
4137 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
4138 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
4139 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
4140 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
4141 /// is always 0, spec's `plane_bsize == tx_size` branch).
4142 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
4143 let mut top = 0u8;
4144 let mut left = 0u8;
4145 for cell in 0..side_mi {
4146 top |= self.above[mi_c + cell][0].level;
4147 left |= self.left[mi_r + cell][0].level;
4148 }
4149 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
4150 if std::env::var_os("EC_AV1_TRACE").is_some() {
4151 eprintln!(
4152 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
4153 );
4154 }
4155 ctx
4156 }
4157
4158 /// Writes one coded block into every cell it covers, on both grids: the
4159 /// mode/side arrays up to `side`'s own width, and the coefficient-context
4160 /// arrays up to the true frame edge — the units past it are left at their
4161 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
4162 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
4163 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
4164 /// not from this block's own side).
4165 fn record(
4166 &mut self,
4167 at: (usize, usize),
4168 side: usize,
4169 mode: usize,
4170 uv_mode: usize,
4171 grids: &[Vec<i32>; 3],
4172 ) {
4173 self.record_rect(at, side, side, mode, uv_mode, grids);
4174 }
4175
4176 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
4177 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
4178 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
4179 /// spec's per-edge partition-context rule, so a true rectangular block
4180 /// naturally wants two different values here rather than one.
4181 /// Writes this block's luma `mode` into the mi-granular
4182 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
4183 /// position a *later* neighbour would read it from: the block's LAST mi
4184 /// row for every column it spans (what the block below reads via
4185 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
4186 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
4187 /// read these back, and only when the recorded position is exactly their
4188 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
4189 fn record_mode_mi(
4190 &mut self,
4191 mi_r: usize,
4192 mi_c: usize,
4193 mi_w: usize,
4194 mi_h: usize,
4195 mode: usize,
4196 ) {
4197 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
4198 for cell in 0..mi_w {
4199 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
4200 *slot = (last_r, mode);
4201 }
4202 }
4203 for cell in 0..mi_h {
4204 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
4205 *slot = (last_c, mode);
4206 }
4207 }
4208 }
4209
4210 /// The mi-exact above/left neighbour luma mode for a block whose top-left
4211 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
4212 /// mi position (then the coarse [`SUB`]-grid slot is right by
4213 /// construction). See [`Self::record_mode_mi`].
4214 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
4215 match self.sub8_mode_col.get(mi_c) {
4216 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m),
4217 _ => None,
4218 }
4219 }
4220
4221 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
4222 match self.sub8_mode_row.get(mi_r) {
4223 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m),
4224 _ => None,
4225 }
4226 }
4227
4228 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
4229 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
4230 fn record_uv_mode_mi(
4231 &mut self,
4232 mi_r: usize,
4233 mi_c: usize,
4234 mi_w: usize,
4235 mi_h: usize,
4236 uv_mode: usize,
4237 ) {
4238 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
4239 for cell in 0..mi_w {
4240 if let Some(slot) = self.uv_mode_col.get_mut(mi_c + cell) {
4241 *slot = (last_r, uv_mode);
4242 }
4243 }
4244 for cell in 0..mi_h {
4245 if let Some(slot) = self.uv_mode_row.get_mut(mi_r + cell) {
4246 *slot = (last_c, uv_mode);
4247 }
4248 }
4249 }
4250
4251 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
4252 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
4253 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
4254 /// block has recorded the exact neighbouring mi.
4255 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
4256 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
4257 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
4258 // array that `start_tile` does not clear, so a block on a tile's first
4259 // mi row used to read the uv_mode of the block above it in the tile
4260 // ABOVE and filter its chroma edge at that neighbour's strength
4261 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
4262 // at chroma (120, 32), the top-right tile's first block).
4263 let have_above = mi_r > self.tile_row0_mi;
4264 let have_left = mi_c > self.tile_col0_mi;
4265 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
4266 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
4267 {
4268 UV_TILE_EDGE_SUPPRESSED_HITS.with(|h| h.set(h.get() + 1));
4269 }
4270 let above = match self.uv_mode_col.get(mi_c) {
4271 Some(&(row, m)) if have_above && row == mi_r - 1 => m,
4272 _ if have_above => self.above_uv_mode[c],
4273 _ => DC_PRED,
4274 };
4275 let left = match self.uv_mode_row.get(mi_r) {
4276 Some(&(col, m)) if have_left && col == mi_c - 1 => m,
4277 _ if have_left => self.left_uv_mode[r],
4278 _ => DC_PRED,
4279 };
4280 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
4281 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
4282 // have been filtered at the wrong strength by the coarse map alone.
4283 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
4284 UV_MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
4285 }
4286 is_smooth_mode(above) || is_smooth_mode(left)
4287 }
4288
4289 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
4290 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
4291 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
4292 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
4293 /// holding an OLDER, larger block's mode -- it only ever recorded into the
4294 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
4295 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
4296 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
4297 /// a different CDF for the same mode value).
4298 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
4299 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4300 let above = self.mode_above_mi(mi_r, mi_c).unwrap_or(self.above_mode[c]);
4301 let left = self.mode_left_mi(mi_r, mi_c).unwrap_or(self.left_mode[r]);
4302 if above != self.above_mode[c] || left != self.left_mode[r] {
4303 MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
4304 }
4305 (above, left)
4306 }
4307
4308 fn record_rect(
4309 &mut self,
4310 at: (usize, usize),
4311 w: usize,
4312 h: usize,
4313 mode: usize,
4314 uv_mode: usize,
4315 grids: &[Vec<i32>; 3],
4316 ) {
4317 let (r, c) = at;
4318 for cell in 0..w / SUB {
4319 self.above_mode[c + cell] = mode;
4320 self.above_uv_mode[c + cell] = uv_mode;
4321 self.above_side[c + cell] = w;
4322 }
4323 for cell in 0..h / SUB {
4324 self.left_mode[r + cell] = mode;
4325 self.left_uv_mode[r + cell] = uv_mode;
4326 self.left_side[r + cell] = h;
4327 }
4328 self.record_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, mode);
4329 self.record_uv_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, uv_mode);
4330 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
4331 }
4332
4333 /// The coefficient-context half of [`Self::record`], taking the block's
4334 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
4335 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
4336 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
4337 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
4338 self.record_mi_rect(at_mi, side, side, grids);
4339 }
4340
4341 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
4342 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
4343 fn record_mi_rect(
4344 &mut self,
4345 at_mi: (usize, usize),
4346 w: usize,
4347 h: usize,
4348 grids: &[Vec<i32>; 3],
4349 ) {
4350 let (mi_r, mi_c) = at_mi;
4351 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
4352 let (w_mi, h_mi) = (w / MI, h / MI);
4353 for cell in 0..h_mi {
4354 self.left_side_mi[mi_r + cell] = h;
4355 }
4356 for cell in 0..w_mi {
4357 self.above_side_mi[mi_c + cell] = w;
4358 }
4359 // A chroma 4x4 unit straddling the true luma edge is still whole in
4360 // chroma's own halved grid, so libaom rounds the luma bound up to the
4361 // plane's own 4x4 unit before clamping a subsampled plane
4362 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
4363 let round_up_even = |n: usize| n.div_ceil(2) * 2;
4364 let bound_h = [
4365 self.mi_rows,
4366 round_up_even(self.mi_rows),
4367 round_up_even(self.mi_rows),
4368 ];
4369 let bound_w = [
4370 self.mi_cols,
4371 round_up_even(self.mi_cols),
4372 round_up_even(self.mi_cols),
4373 ];
4374 for cell in 0..h_mi {
4375 self.left[mi_r + cell] = std::array::from_fn(|plane| {
4376 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
4377 states[plane]
4378 } else {
4379 Default::default()
4380 }
4381 });
4382 }
4383 for cell in 0..w_mi {
4384 self.above[mi_c + cell] = std::array::from_fn(|plane| {
4385 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
4386 states[plane]
4387 } else {
4388 Default::default()
4389 }
4390 });
4391 }
4392 }
4393
4394 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
4395 /// inside a coded block whose luma transform is smaller than its own
4396 /// side (`TxMode::Select`): the real per-transform-unit coefficient
4397 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
4398 /// coarse per-block `tx_grid`/`fill_lf_grid` state
4399 /// [`Self::record_split_luma`] still writes once for the whole block.
4400 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
4401 /// the caller's own [`Self::record_split_luma`] call sets those once,
4402 /// at the block's own true side, not this TU's.
4403 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
4404 let state = neighbour_state(grid);
4405 let side_mi = tx_px / MI;
4406 for cell in 0..side_mi {
4407 if mi_r + cell < self.mi_rows {
4408 self.left[mi_r + cell][0] = state;
4409 }
4410 if mi_c + cell < self.mi_cols {
4411 self.above[mi_c + cell][0] = state;
4412 }
4413 }
4414 }
4415
4416 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
4417 /// block whose luma was decoded as several transform units through
4418 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
4419 /// whole-block luma write -- everything [`Self::record`] does except
4420 /// plane 0, which is already correct per-TU by the time this runs.
4421 fn record_split_luma(
4422 &mut self,
4423 at: (usize, usize),
4424 side: usize,
4425 mode: usize,
4426 uv_mode: usize,
4427 chroma_grids: [&[i32]; 2],
4428 ) {
4429 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
4430 }
4431
4432 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
4433 /// extents in pixels (lane-rectsplit r1), the same relationship
4434 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
4435 /// luma transform split into several square units needs exactly this
4436 /// bookkeeping, at its own true rectangular extents.
4437 fn record_split_luma_rect(
4438 &mut self,
4439 at: (usize, usize),
4440 w: usize,
4441 h: usize,
4442 mode: usize,
4443 uv_mode: usize,
4444 chroma_grids: [&[i32]; 2],
4445 ) {
4446 let (r, c) = at;
4447 for cell in 0..w / SUB {
4448 self.above_mode[c + cell] = mode;
4449 self.above_uv_mode[c + cell] = uv_mode;
4450 self.above_side[c + cell] = w;
4451 }
4452 for cell in 0..h / SUB {
4453 self.left_mode[r + cell] = mode;
4454 self.left_uv_mode[r + cell] = uv_mode;
4455 self.left_side[r + cell] = h;
4456 }
4457 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4458 let (w_mi, h_mi) = (w / MI, h / MI);
4459 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
4460 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
4461 for cell in 0..h_mi {
4462 self.left_side_mi[mi_r + cell] = h;
4463 }
4464 for cell in 0..w_mi {
4465 self.above_side_mi[mi_c + cell] = w;
4466 }
4467 let round_up_even = |n: usize| n.div_ceil(2) * 2;
4468 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
4469 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
4470 let plane = plane_idx + 1;
4471 let state = neighbour_state(grid);
4472 for cell in 0..h_mi {
4473 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
4474 self.left[mi_r + cell][plane] = state;
4475 }
4476 }
4477 for cell in 0..w_mi {
4478 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
4479 self.above[mi_c + cell][plane] = state;
4480 }
4481 }
4482 }
4483 }
4484}
4485
4486/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
4487/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
4488/// exactly — including its skip context, which the real key-frame writer
4489/// always writes at a fixed context of zero (it never tracks a neighbour-based
4490/// one for intra blocks; that is the inter-frame writer's rule instead).
4491/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
4492/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
4493/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
4494/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
4495/// plain DC chroma.
4496/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
4497/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
4498/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
4499/// instead (the defect commit 1a89ed9 fixed at the square sites).
4500fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
4501 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
4502 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
4503}
4504
4505/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
4506/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
4507/// bound (spec `filter_intra_mode_info` never reads a symbol there).
4508fn filter_intra_size_class(side: usize) -> Option<usize> {
4509 match side {
4510 4 => Some(0),
4511 8 => Some(1),
4512 16 => Some(2),
4513 32 => Some(3),
4514 _ => None,
4515 }
4516}
4517
4518/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
4519/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
4520/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
4521/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
4522fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
4523 match (bw, bh) {
4524 (32, 16) => Some(4),
4525 (16, 32) => Some(5),
4526 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
4527 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
4528 // here dropped that symbol on every DC_PRED strip of that size and
4529 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
4530 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
4531 (16, 8) => Some(6),
4532 (8, 16) => Some(7),
4533 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
4534 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
4535 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
4536 (4, 8) => Some(8),
4537 (8, 4) => Some(9),
4538 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
4539 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
4540 // `use_filter_intra` symbol on those strips although aomenc writes
4541 // one for every DC_PRED block of that shape with
4542 // `--enable-filter-intra=1` (its default), silently desyncing the
4543 // tile (class symbol-consumption-gap).
4544 (32, 8) => Some(10),
4545 (8, 32) => Some(11),
4546 _ if bw == bh => filter_intra_size_class(bw),
4547 _ => None,
4548 }
4549}
4550
4551/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
4552/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
4553/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
4554/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
4555/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
4556fn palette_bsize_ctx(side: usize) -> Option<usize> {
4557 palette_bsize_ctx_wh(side, side)
4558}
4559
4560/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
4561/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
4562/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
4563/// for ANY bsize, not just the square ones a hand-picked table happened to
4564/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
4565/// row breaks the moment its indexing field moves off the diagonal, and a
4566/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
4567/// block dimension is a power of two, so `bw*bh` always is too and
4568/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
4569/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
4570fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
4571 if !(8..=64).contains(&bw) || !(8..=64).contains(&bh) {
4572 return None;
4573 }
4574 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
4575}
4576
4577/// A just-decoded palette-Y block's own size, base colours (only the first
4578/// `size` entries are real), and per-pixel colour-index map (`side*side`,
4579/// row-major, each entry `< size`).
4580struct PaletteY {
4581 size: usize,
4582 colors: [u16; 8],
4583 map: Vec<u8>,
4584}
4585
4586/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
4587/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
4588/// shared between U and V, both co-located after 4:2:0 subsampling) plus
4589/// each plane's own base colours.
4590struct PaletteUv {
4591 size: usize,
4592 u_colors: [u16; 8],
4593 v_colors: [u16; 8],
4594 map: Vec<u8>,
4595}
4596
4597/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
4598/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
4599/// `get_unsigned_bits`, which is the same formula): smallest `n` with
4600/// `2^n >= x`, `0` for `x <= 1`.
4601fn ceil_log2(x: u32) -> u32 {
4602 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
4603}
4604
4605/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
4606/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
4607fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
4608 let l = ceil_log2(n as u32);
4609 let m = (1usize << l) - n;
4610 let v = dec.literal(l - 1) as usize;
4611 if v < m {
4612 v
4613 } else {
4614 (v << 1) - m + dec.literal(1) as usize
4615 }
4616}
4617
4618/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
4619/// colours (already-known, from the above/left neighbours) with the
4620/// ascending `transmitted` ones (delta-coded off the wire) back into one
4621/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
4622/// value picks the cached copy first, matching the C `<=`.
4623fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
4624 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
4625 let (mut ci, mut ti) = (0, 0);
4626 while ci < cached.len() && ti < transmitted.len() {
4627 if cached[ci] <= transmitted[ti] {
4628 out.push(cached[ci]);
4629 ci += 1;
4630 } else {
4631 out.push(transmitted[ti]);
4632 ti += 1;
4633 }
4634 }
4635 out.extend_from_slice(&cached[ci..]);
4636 out.extend_from_slice(&transmitted[ti..]);
4637 out
4638}
4639
4640/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this
4641/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
4642/// (one flag bit each, in cache order), then delta-codes the remainder
4643/// (first value raw, each following delta `>= 1` off a shrinking bit width),
4644/// and merges the two ascending lists back together.
4645fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
4646 let mut cached = Vec::with_capacity(n);
4647 for &c in cache {
4648 if cached.len() >= n {
4649 break;
4650 }
4651 if dec.literal(1) == 1 {
4652 cached.push(c);
4653 }
4654 }
4655 let mut colors = [0u16; 8];
4656 let n_cached = cached.len();
4657 if n_cached < n {
4658 let mut transmitted = Vec::with_capacity(n - n_cached);
4659 let first = dec.literal(8) as u16;
4660 transmitted.push(first);
4661 if n_cached + 1 < n {
4662 let min_bits = 8u32 - 3;
4663 let mut bits = min_bits + dec.literal(2);
4664 let mut range = 255i32 - i32::from(first) - 1;
4665 for _ in (n_cached + 1)..n {
4666 let delta = dec.literal(bits) as i32 + 1;
4667 let prev = *transmitted.last().unwrap();
4668 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
4669 range -= i32::from(val) - i32::from(prev);
4670 bits = bits.min(ceil_log2(range.max(0) as u32));
4671 transmitted.push(val);
4672 }
4673 }
4674 let merged = merge_colors(&transmitted, &cached);
4675 colors[..n].copy_from_slice(&merged);
4676 } else {
4677 colors[..n].copy_from_slice(&cached[..n]);
4678 }
4679 colors
4680}
4681
4682/// `read_palette_colors_uv` (decodemv.c:509), bit_depth fixed at 8: U reads
4683/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
4684/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
4685/// unbiased by `+1` -- both differences from Y's own reader, matching the C
4686/// side by side). V never uses a cache: a leading bit picks either `n` raw
4687/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
4688/// rather than clamp.
4689fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
4690 let mut cached = Vec::with_capacity(n);
4691 for &c in cache {
4692 if cached.len() >= n {
4693 break;
4694 }
4695 if dec.literal(1) == 1 {
4696 cached.push(c);
4697 }
4698 }
4699 let mut u_colors = [0u16; 8];
4700 let n_cached = cached.len();
4701 if n_cached < n {
4702 let mut transmitted = Vec::with_capacity(n - n_cached);
4703 let first = dec.literal(8) as u16;
4704 transmitted.push(first);
4705 if n_cached + 1 < n {
4706 let min_bits = 8u32 - 3;
4707 let mut bits = min_bits + dec.literal(2);
4708 let mut range = 255i32 - i32::from(first);
4709 for _ in (n_cached + 1)..n {
4710 let delta = dec.literal(bits) as i32;
4711 let prev = *transmitted.last().unwrap();
4712 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
4713 range -= i32::from(val) - i32::from(prev);
4714 bits = bits.min(ceil_log2(range.max(0) as u32));
4715 transmitted.push(val);
4716 }
4717 }
4718 let merged = merge_colors(&transmitted, &cached);
4719 u_colors[..n].copy_from_slice(&merged);
4720 } else {
4721 u_colors[..n].copy_from_slice(&cached[..n]);
4722 }
4723 let mut v_colors = [0u16; 8];
4724 if dec.literal(1) == 1 {
4725 let min_bits_v = 8u32 - 4;
4726 let bits = min_bits_v + dec.literal(2);
4727 v_colors[0] = dec.literal(8) as u16;
4728 for i in 1..n {
4729 let mut delta = dec.literal(bits) as i32;
4730 if delta != 0 && dec.literal(1) == 1 {
4731 delta = -delta;
4732 }
4733 let mut val = i32::from(v_colors[i - 1]) + delta;
4734 if val < 0 {
4735 val += 256;
4736 }
4737 if val >= 256 {
4738 val -= 256;
4739 }
4740 v_colors[i] = val as u16;
4741 }
4742 } else {
4743 for i in 0..n {
4744 v_colors[i] = dec.literal(8) as u16;
4745 }
4746 }
4747 (u_colors, v_colors)
4748}
4749
4750/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
4751/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
4752/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
4753const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
4754
4755/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
4756/// map's own per-pixel context and colour-order permutation, from the
4757/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
4758/// selection sort). `map`'s stride is `side` (this decoder never crops a
4759/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
4760/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
4761/// actual colour index to store.
4762fn palette_color_index_context(
4763 map: &[u8],
4764 side: usize,
4765 row: usize,
4766 col: usize,
4767 n: usize,
4768) -> (usize, [u8; 8]) {
4769 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
4770 let up_left = if col >= 1 && row >= 1 {
4771 Some(map[(row - 1) * side + col - 1])
4772 } else {
4773 None
4774 };
4775 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
4776 let mut scores = [0i32; 8];
4777 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
4778 if let Some(v) = neighbour {
4779 scores[v as usize] += weight;
4780 }
4781 }
4782 let mut color_order = [0u8; 8];
4783 for i in 0..8 {
4784 color_order[i] = i as u8;
4785 }
4786 for i in 0..3 {
4787 let mut max = scores[i];
4788 let mut max_idx = i;
4789 for j in (i + 1)..n {
4790 if scores[j] > max {
4791 max = scores[j];
4792 max_idx = j;
4793 }
4794 }
4795 if max_idx != i {
4796 let max_score = scores[max_idx];
4797 let max_color = color_order[max_idx];
4798 for k in (i + 1..=max_idx).rev() {
4799 scores[k] = scores[k - 1];
4800 color_order[k] = color_order[k - 1];
4801 }
4802 scores[i] = max_score;
4803 color_order[i] = max_color;
4804 }
4805 }
4806 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
4807 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
4808 (ctx as usize, color_order)
4809}
4810
4811/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
4812/// map's wavefront decode over a `side x side` grid -- this decoder's
4813/// palette blocks are always square and never straddle the frame's true
4814/// (possibly odd) edge without already allocating the full `side*side`
4815/// region (every other skip/residual path here does the same), so no
4816/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
4817/// libaom's own non-block-aligned split.
4818fn decode_color_index_map(
4819 dec: &mut SymbolDecoder,
4820 cdfs: &mut Cdfs,
4821 n: usize,
4822 side: usize,
4823 uv: bool,
4824) -> Vec<u8> {
4825 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
4826}
4827
4828/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
4829/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
4830/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
4831/// independently rather than one shared `side` -- the square call above is
4832/// just `bw == bh`.
4833fn decode_color_index_map_wh(
4834 dec: &mut SymbolDecoder,
4835 cdfs: &mut Cdfs,
4836 n: usize,
4837 bw: usize,
4838 bh: usize,
4839 uv: bool,
4840) -> Vec<u8> {
4841 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
4842 let mut map = vec![0u8; bw * bh];
4843 if trace {
4844 let (rng, _) = dec.debug_state();
4845 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
4846 }
4847 map[0] = read_uniform(dec, n) as u8;
4848 if trace {
4849 let (rng, _) = dec.debug_state();
4850 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
4851 }
4852 for i in 1..(bw + bh - 1) {
4853 let j_hi = i.min(bw - 1);
4854 let j_lo = i.saturating_sub(bh - 1);
4855 for j in (j_lo..=j_hi).rev() {
4856 let row = i - j;
4857 let col = j;
4858 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
4859 if trace {
4860 let (rng, _) = dec.debug_state();
4861 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
4862 }
4863 let symbol = if uv {
4864 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
4865 } else {
4866 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
4867 };
4868 map[row * bw + col] = color_order[symbol];
4869 if trace {
4870 let (rng, _) = dec.debug_state();
4871 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
4872 }
4873 }
4874 }
4875 map
4876}
4877
4878/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
4879/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
4880/// size class comes from [`filter_intra_size_class_rect`] instead of the
4881/// square-only [`filter_intra_size_class`], and the palette read (when
4882/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
4883/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
4884/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
4885/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
4886#[allow(clippy::too_many_arguments)]
4887fn read_intra_mode_rect(
4888 dec: &mut SymbolDecoder,
4889 cdfs: &mut Cdfs,
4890 above_mode: usize,
4891 left_mode: usize,
4892 cfl: bool,
4893 bw: usize,
4894 bh: usize,
4895 enable_filter_intra: bool,
4896 skip_ctx: usize,
4897 allow_screen_content_tools: bool,
4898 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
4899 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
4900 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
4901 palette: Option<(usize, &[u16])>,
4902 palette_uv_cache: &[u16],
4903 mi_r: usize,
4904 mi_c: usize,
4905) -> Result<(
4906 bool,
4907 usize,
4908 i32,
4909 usize,
4910 i32,
4911 Option<(i32, i32)>,
4912 Option<usize>,
4913 Option<PaletteY>,
4914 Option<PaletteUv>,
4915)> {
4916 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
4917 macro_rules! istep {
4918 ($name:literal, $val:expr) => {
4919 if ec_istep {
4920 let (rng, _) = dec.debug_state();
4921 eprintln!(
4922 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
4923 $name, $val
4924 );
4925 }
4926 };
4927 }
4928 // Same `intra_segment_id` placement as the square reader above.
4929 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
4930 if seg_id_pre_skip() {
4931 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
4932 }
4933 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
4934 istep!("skip", skip as i32);
4935 if !seg_id_pre_skip() {
4936 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
4937 }
4938 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
4939 istep!("cdef", 0);
4940 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
4941 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
4942 // `false`.
4943 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
4944 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
4945 istep!("dq", 0);
4946 let above_ctx = INTRA_MODE_CTX[above_mode];
4947 let left_ctx = INTRA_MODE_CTX[left_mode];
4948 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
4949 istep!("mode", mode as i32);
4950 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
4951 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
4952 } else {
4953 0
4954 };
4955 istep!("angle_y", angle_delta_y);
4956 let uv_mode = if cfl {
4957 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
4958 } else {
4959 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
4960 };
4961 istep!("uv_mode", uv_mode as i32);
4962 let alpha = if cfl && uv_mode == UV_CFL_PRED {
4963 Some(read_cfl_alphas(dec, cdfs))
4964 } else {
4965 None
4966 };
4967 if (9..=12).contains(&uv_mode) {
4968 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
4969 }
4970 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
4971 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
4972 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
4973 } else {
4974 0
4975 };
4976 istep!("angle_uv", angle_delta_uv);
4977 if angle_delta_uv != 0 {
4978 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
4979 }
4980 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
4981 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
4982 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
4983 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
4984 // colours only here, the colour-index maps deferred past `filter_intra`
4985 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
4986 // runs from the caller, after the whole mode-info read).
4987 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
4988 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
4989 if allow_screen_content_tools
4990 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
4991 {
4992 // r6: this is the exact site the removed blanket refusal used to
4993 // guard -- reached for EVERY rect strip in a screen-content frame,
4994 // independent of whether the block ends up using a palette.
4995 RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1));
4996 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
4997 let use_palette_y =
4998 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
4999 if use_palette_y {
5000 if palette.is_none() {
5001 return Err(unsupported(
5002 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
5003 ));
5004 }
5005 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
5006 let colors = read_palette_colors_y(dec, n, cache);
5007 palette_y_pending = Some((n, colors));
5008 }
5009 let palette_uv_mode_ctx = usize::from(use_palette_y);
5010 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
5011 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
5012 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
5013 palette_uv_pending = Some((n, u_colors, v_colors));
5014 }
5015 }
5016 let mut filter_intra = None;
5017 if std::env::var_os("EC_AV1_TRACE").is_some() {
5018 let (rng, _) = dec.debug_state();
5019 eprintln!(
5020 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
5021 class={:?} rng={rng}",
5022 enable_filter_intra as i32,
5023 filter_intra_size_class_rect(bw, bh)
5024 );
5025 }
5026 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
5027 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
5028 if mode == DC_PRED
5029 && enable_filter_intra
5030 && palette_y_pending.is_none()
5031 && let Some(class) = filter_intra_size_class_rect(bw, bh)
5032 {
5033 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
5034 if std::env::var_os("EC_AV1_TRACE").is_some() {
5035 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
5036 }
5037 if use_filter_intra {
5038 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
5039 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
5040 filter_intra = Some(fi_mode);
5041 }
5042 }
5043 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
5044 // same order as [`read_intra_mode`]'s own square path.
5045 let palette_y = palette_y_pending.map(|(n, colors)| {
5046 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
5047 PALETTE_HITS.with(|c| c.set(c.get() + 1));
5048 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
5049 PaletteY { size: n, colors, map }
5050 });
5051 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
5052 let map = decode_color_index_map_wh(dec, cdfs, n, bw / 2, bh / 2, true);
5053 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
5054 PaletteUv { size: n, u_colors, v_colors, map }
5055 });
5056 Ok((
5057 skip,
5058 mode,
5059 angle_delta_y,
5060 uv_mode,
5061 angle_delta_uv,
5062 alpha,
5063 filter_intra,
5064 palette_y,
5065 palette_uv,
5066 ))
5067}
5068
5069/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
5070/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
5071/// above against this block's own *width* and the neighbour to the left
5072/// against its own *height* -- for a square block those are the same value,
5073/// which is why the square-only version can get away with one `own_side`.
5074fn tx_size_context_rect(
5075 n: &Neighbours,
5076 (mi_r, mi_c): (usize, usize),
5077 own_w: usize,
5078 own_h: usize,
5079) -> usize {
5080 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
5081 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
5082 usize::from(above) + usize::from(left)
5083}
5084
5085/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
5086fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
5087 let (cw, ch) = (bw / 2, bh / 2);
5088 let mut ac = vec![0i32; cw * ch];
5089 let mut sum = 0i32;
5090 for cy in 0..ch {
5091 for cx in 0..cw {
5092 let (lx, ly) = (px + cx * 2, py + cy * 2);
5093 let q3 = (i32::from(y.data[ly * y.width + lx])
5094 + i32::from(y.data[ly * y.width + lx + 1])
5095 + i32::from(y.data[(ly + 1) * y.width + lx])
5096 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
5097 << 1;
5098 ac[cy * cw + cx] = q3;
5099 sum += q3;
5100 }
5101 }
5102 let num_pel = (cw * ch) as i32;
5103 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
5104 ac.iter_mut().for_each(|v| *v -= avg);
5105 ac
5106}
5107
5108/// Everything a rect strip already read out of the stream before its luma
5109/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
5110/// (nine values that would otherwise be nine more parameters).
5111struct RectStripModes {
5112 skip: bool,
5113 mode: usize,
5114 angle_delta_y: i32,
5115 uv_predict_mode: usize,
5116 angle_delta_uv: i32,
5117 alpha: Option<(i32, i32)>,
5118 filter_intra: Option<usize>,
5119 smooth_neighbor: bool,
5120 smooth_neighbor_uv: bool,
5121 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
5122 /// mapped through the colour table), sliced per transform unit below --
5123 /// palette prediction reads no edge pixels, so a unit's slice of the
5124 /// whole-block map IS its prediction. Without this a palette strip whose
5125 /// transform splits predicted DC and came out flat grey while the entropy
5126 /// stream stayed in sync (the coefficients are read either way).
5127 palette_y: Option<Vec<u16>>,
5128 /// As `palette_y`, for the un-split chroma transform (U, V).
5129 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
5130}
5131
5132/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
5133/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
5134/// rect path here refused by name until now ("per-unit rect prediction is not
5135/// ported").
5136///
5137/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
5138/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
5139/// strip the very first step already lands on a SQUARE transform
5140/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
5141/// every further step halves a square) -- so each unit is square and reads
5142/// through the ordinary square [`read_plane`]. What is genuinely rectangular
5143/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
5144/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
5145/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
5146/// split by luma's depth.
5147///
5148/// Each unit predicts off whatever the earlier units of this same block
5149/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
5150/// inside `av1_foreach_transformed_block`, raster order), which is exactly
5151/// what predicting the whole strip in one shot got wrong.
5152#[allow(clippy::too_many_arguments)]
5153fn decode_rect_split(
5154 dec: &mut SymbolDecoder,
5155 cdfs: &mut Cdfs,
5156 neighbours: &mut Neighbours,
5157 at: (usize, usize),
5158 bw: usize,
5159 bh: usize,
5160 tx: usize,
5161 m: &RectStripModes,
5162 y: &mut PlaneBuf,
5163 u: &mut PlaneBuf,
5164 v: &mut PlaneBuf,
5165 base_q_idx: u8,
5166 reduced_tx_set: bool,
5167) -> Result<()> {
5168 let (r, c) = at;
5169 let (px, py) = (c * SUB, r * SUB);
5170 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5171 let (cpx, cpy) = (px / 2, py / 2);
5172 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5173 // The chroma transform is picked before any symbol is read, so an
5174 // unsupported chroma shape refuses before this strip desyncs the tile.
5175 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
5176 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
5177 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
5178 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
5179 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
5180 // lane-rectchroma r1: the 1:4 superblock strips (64x16/16x64,
5181 // `decode_block_rect64`'s `strip64!` arm) and the 8x16 left rect of a
5182 // 16x16 `VERT_B` reach here once their tx depth is non-zero -- the
5183 // shapes their chroma half takes. `get_txsize_entropy_ctx(TX_32X8)`
5184 // is `(0 + 4 + 1) >> 1 == 2`, the 16x16 CDF set (eob alphabet 256),
5185 // exactly as the unsplit 1:4 path already picks it; `TX_8X4` reduces
5186 // to `(0 + 1 + 1) >> 1 == 1`, the 8x8 set `ChromaRect8x4` carries
5187 // (eob 32), as `decode_leaf_rect`'s own chroma half already does.
5188 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
5189 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
5190 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
5191 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
5192 _ => None,
5193 };
5194 if !m.skip {
5195 if let Some(i) = match (chroma_w, chroma_h) {
5196 (32, 8) => Some(0),
5197 (8, 32) => Some(1),
5198 (8, 4) => Some(2),
5199 (4, 8) => Some(3),
5200 _ => None,
5201 } {
5202 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
5203 let mut hits = c.get();
5204 hits[i] += 1;
5205 c.set(hits);
5206 });
5207 }
5208 if chroma.is_none() {
5209 // Diagnostic for the next caller that lands here (class
5210 // refusal-names-a-correlate: the message names the tool, not the
5211 // shape); the refusal below keeps its inventory-pinned wording.
5212 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx} chroma={chroma_w}x{chroma_h}");
5213 }
5214 }
5215 // lane-rectsplit r2 (verifier finding): with both callers wired
5216 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
5217 // 64x32/32x64) every shape that reaches here has a table above, so this
5218 // arm is UNREACHABLE today. It stays as the shape guard for the next
5219 // caller -- a new strip size would otherwise hit the `expect` below and
5220 // panic instead of refusing by name -- and so stays in
5221 // `refusal_inventory::REFUSALS`.
5222 if !m.skip && chroma.is_none() {
5223 return Err(unsupported(
5224 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
5225 ));
5226 }
5227 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
5228 if bw.max(bh) == 64 && bw / tx > 1 && bh / tx > 1 {
5229 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1));
5230 }
5231 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
5232 let luma_set = txbset_for(tx, reduced_tx_set);
5233 let luma_scan = default_scan(tx);
5234 let zero_tu = vec![0i32; tx * tx];
5235 // The strip's OWN edge availability, the fallback for a transform unit
5236 // whose top-right/bottom-left pixels fall outside the strip.
5237 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5238 for tu_row in 0..bh / tx {
5239 for tu_col in 0..bw / tx {
5240 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
5241 let (tu_px, tu_py) = (px + tu_col * tx, py + tu_row * tx);
5242 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
5243 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
5244 // transform unit INSIDE a block, which is a different rule from
5245 // the standalone-block table [`Reach::of`] applies -- and the
5246 // reason a depth-2 superblock strip came out one sample off
5247 // before this: `Reach::of(tx, ..)` answered as if the unit were
5248 // its own block at that superblock position.
5249 // * top-right: if the unit's right neighbour is still inside the
5250 // strip the pixels are already reconstructed (`col_off +
5251 // tx_wide < plane_bw`); otherwise only the strip's own top row
5252 // of units can reach past it, through the block-level answer.
5253 // * bottom-left: a unit that is not in the strip's left column
5254 // has none (`col_off > 0` returns 0); inside the strip
5255 // (`row_off + tx_high < plane_bh`) they are the left
5256 // neighbour's, already reconstructed; the last row falls back
5257 // to the block-level answer.
5258 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx, block_reach);
5259 // The unit's own window on the block's palette prediction.
5260 if let Some(buf) = &m.palette_y {
5261 let tu_buf: Vec<u16> = (0..tx)
5262 .flat_map(|i| {
5263 let base = (row_off + i) * bw + col_off;
5264 buf[base..base + tx].iter().copied()
5265 })
5266 .collect();
5267 set_palette_pred(tu_buf);
5268 }
5269 if m.skip {
5270 y.reconstruct(
5271 tu_px,
5272 tu_py,
5273 tx,
5274 m.mode,
5275 m.angle_delta_y,
5276 tu_reach,
5277 &zero_tu,
5278 None,
5279 m.filter_intra,
5280 m.smooth_neighbor,
5281 );
5282 neighbours.record_mi_luma(tu_mi, tx, &zero_tu);
5283 } else {
5284 let tu_around = neighbours.around_mi(tu_mi, tx)[0];
5285 // This unit is smaller than the block it sits in, so
5286 // `txb_skip_ctx` is the neighbour-magnitude table, not the
5287 // lone-TU 0 (spec `get_txb_ctx_general`).
5288 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx / MI);
5289 let tu_grid = read_plane(
5290 dec,
5291 cdfs,
5292 luma_set,
5293 &luma_scan,
5294 0,
5295 tu_around,
5296 m.mode,
5297 m.mode,
5298 m.angle_delta_y,
5299 tu_reach,
5300 y,
5301 tu_px,
5302 tu_py,
5303 tx,
5304 tx,
5305 base_q_idx,
5306 None,
5307 m.filter_intra,
5308 Some(tu_skip_ctx),
5309 m.smooth_neighbor,
5310 )?;
5311 neighbours.record_mi_luma(tu_mi, tx, &tu_grid);
5312 }
5313 }
5314 }
5315 // CHROMA: one un-split rect transform for the whole strip.
5316 let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5317 let reach = block_reach;
5318 let (u_grid, v_grid) = if m.skip {
5319 let zero = vec![0i32; chroma_w * chroma_h];
5320 if let Some((ub, _)) = &m.palette_uv {
5321 set_palette_pred(ub.clone());
5322 }
5323 u.reconstruct_rect(
5324 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
5325 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
5326 );
5327 if let Some((_, vb)) = &m.palette_uv {
5328 set_palette_pred(vb.clone());
5329 }
5330 v.reconstruct_rect(
5331 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
5332 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
5333 );
5334 (zero.clone(), zero)
5335 } else {
5336 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
5337 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
5338 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
5339 // so only the 16x8/8x16 pair takes the mode-indexed default.
5340 let default_tx = if chroma_w.max(chroma_h) >= 32 {
5341 TxType::DctDct
5342 } else {
5343 default_intra_tx_type(m.uv_predict_mode as u8)
5344 };
5345 let around = neighbours.around_rect(at, bw, bh);
5346 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
5347 for plane_idx in 1..=2 {
5348 let skip_ctx =
5349 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
5350 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
5351 let (levels, tx_type) = read_coeffs_rect(
5352 dec,
5353 &mut coding,
5354 chroma_scan,
5355 chroma_w,
5356 chroma_h,
5357 skip_ctx,
5358 dc_sign_ctx(around[plane_idx].2),
5359 default_tx,
5360 )?;
5361 // The same delta_q proof the unsplit rect64 path records
5362 // (lane-rectsplit r4: lifting the split-transform refusal moved
5363 // superblock strips onto this path, so only counting there would
5364 // leave the delta_q gate's counter silent for them).
5365 if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) {
5366 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
5367 }
5368 let residual = dequant_and_inverse_typed_wh(
5369 &levels,
5370 chroma_w,
5371 chroma_h,
5372 crate::decode::bit_depth(),
5373 CURRENT_Q_IDX.with(|c| c.get()),
5374 plane_q_delta(plane_idx).0,
5375 plane_q_delta(plane_idx).1,
5376 tx_type,
5377 );
5378 let cfl = m
5379 .alpha
5380 .zip(ac.as_deref())
5381 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
5382 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
5383 if let Some((ub, vb)) = &m.palette_uv {
5384 let buf = if plane_idx == 1 { ub } else { vb };
5385 set_palette_pred(buf.clone());
5386 }
5387 plane.reconstruct_rect(
5388 cpx,
5389 cpy,
5390 chroma_w,
5391 chroma_h,
5392 m.uv_predict_mode,
5393 m.angle_delta_uv,
5394 reach,
5395 &residual,
5396 cfl,
5397 None,
5398 m.smooth_neighbor_uv,
5399 );
5400 grids.push(levels);
5401 }
5402 let mut it = grids.into_iter();
5403 (it.next().unwrap(), it.next().unwrap())
5404 };
5405 neighbours.record_split_luma_rect(at, bw, bh, m.mode, m.uv_predict_mode, [&u_grid, &v_grid]);
5406 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
5407 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx as u8, tx as u8, 0);
5408 if std::env::var_os("EC_AV1_TRACE").is_some() {
5409 let (rng, _) = dec.debug_state();
5410 eprintln!(
5411 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} tx={tx} rng={rng}"
5412 );
5413 }
5414 Ok(())
5415}
5416
5417/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
5418/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
5419/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
5420/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
5421/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
5422/// has no rectangular-transform coefficient reader, and a chroma plane here
5423/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
5424/// with no depth-based square-tiling escape the way luma's own resolved
5425/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
5426/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
5427#[allow(clippy::too_many_arguments)]
5428fn decode_block_rect(
5429 dec: &mut SymbolDecoder,
5430 cdfs: &mut Cdfs,
5431 neighbours: &mut Neighbours,
5432 at: (usize, usize),
5433 bw: usize,
5434 bh: usize,
5435 y: &mut PlaneBuf,
5436 u: &mut PlaneBuf,
5437 v: &mut PlaneBuf,
5438 enable_filter_intra: bool,
5439 allow_screen_content_tools: bool,
5440 base_q_idx: u8,
5441 tx_select: bool,
5442 reduced_tx_set: bool,
5443) -> Result<()> {
5444 let (r, c) = at;
5445 let (px, py) = (c * SUB, r * SUB);
5446 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
5447 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
5448 let palette_uv_cache = neighbours.palette_uv_cache(at);
5449 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
5450 read_intra_mode_rect(
5451 dec,
5452 cdfs,
5453 nb_above_mode,
5454 nb_left_mode,
5455 true,
5456 bw,
5457 bh,
5458 enable_filter_intra,
5459 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
5460 allow_screen_content_tools,
5461 Some((palette_ctx, &palette_cache)),
5462 &palette_uv_cache,
5463 r * (SUB / MI),
5464 c * (SUB / MI),
5465 )?;
5466 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
5467 if smooth_neighbor {
5468 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5469 }
5470 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
5471 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
5472 // `uv_mode`, not the luma one.
5473 let smooth_neighbor_uv =
5474 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
5475 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
5476 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
5477 // rectangle just as happily), so a `use_filter_intra` strip at this level
5478 // predicts instead of refusing. The below-16x16 leaf arm
5479 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
5480 if filter_intra.is_some() {
5481 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
5482 }
5483 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
5484 DC_PRED
5485 } else {
5486 uv_mode
5487 };
5488 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5489 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
5490 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
5491 // one did not, so with `--enable-tx-size-search=0` -- which several gate
5492 // recipes use -- the decoder consumed a symbol the encoder never wrote and
5493 // desynced the tile from that point on. That is why both strips of the
5494 // pinned HORZ quadrant were wrong from their very first pixel, and why our
5495 // range after the read equalled the oracle's range for the whole block.
5496 let depth = if tx_select {
5497 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
5498 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
5499 } else {
5500 0
5501 };
5502 if depth != 0 {
5503 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
5504 // lane-rectsplit r1: a split transform is predicted and reconstructed
5505 // per transform unit, each unit taking its edges from the previous
5506 // unit's reconstruction inside this same strip (spec 5.11.36) --
5507 // [`decode_rect_split`]. `depth_to_tx_size` of a 2:1 strip is square
5508 // from the first step on, so `bw.min(bh) >> (depth - 1)` names it.
5509 let tx = bw.min(bh) >> (depth - 1);
5510 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
5511 eprintln!(
5512 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
5513 depth={depth} tx={tx} mode={mode} uv={uv_predict_mode} skip={skip} \
5514 angle_y={angle_delta_y}"
5515 );
5516 }
5517 let modes = RectStripModes {
5518 skip,
5519 mode,
5520 angle_delta_y,
5521 uv_predict_mode,
5522 angle_delta_uv,
5523 alpha,
5524 filter_intra,
5525 smooth_neighbor,
5526 smooth_neighbor_uv,
5527 palette_y: palette_y
5528 .as_ref()
5529 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
5530 palette_uv: palette_uv.as_ref().map(|p| {
5531 (
5532 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
5533 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
5534 )
5535 }),
5536 };
5537 if palette_y.is_some() || palette_uv.is_some() {
5538 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
5539 }
5540 decode_rect_split(
5541 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,
5542 )?;
5543 // This early return skips this fn's own tail, so the palette
5544 // neighbour state has to be stamped HERE too: without it a split-tx
5545 // strip left the above/left palette arrays holding a DEAD block's
5546 // colours, and the next block's colour cache
5547 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
5548 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
5549 // and only those pixels were wrong (lane-palette2 r10).
5550 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
5551 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
5552 let (puv_size, puv_colors) =
5553 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
5554 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
5555 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
5556 return Ok(());
5557 }
5558 let (tx_w, tx_h) = (bw, bh);
5559 let (cpx, cpy) = (px / 2, py / 2);
5560 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5561 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5562 if std::env::var_os("EC_AV1_TRACE").is_some() {
5563 let (rng, _) = dec.debug_state();
5564 eprintln!(
5565 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
5566 skip={} tx={depth} rng={rng}",
5567 skip as i32
5568 );
5569 }
5570 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
5571 // block's prediction is the reconstructed colour-index map, set fresh
5572 // right before each `reconstruct_rect` call below (lane-palette2 r4).
5573 if let Some(ref pyv) = palette_y {
5574 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
5575 set_palette_pred(buf);
5576 }
5577 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
5578 (
5579 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
5580 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
5581 )
5582 });
5583 if skip {
5584 y.reconstruct_rect(
5585 px,
5586 py,
5587 bw,
5588 bh,
5589 mode,
5590 angle_delta_y,
5591 reach,
5592 &vec![0i32; bw * bh],
5593 None,
5594 filter_intra,
5595 smooth_neighbor,
5596 );
5597 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5598 if let Some((ub, _)) = &palette_uv_bufs {
5599 set_palette_pred(ub.clone());
5600 }
5601 u.reconstruct_rect(
5602 cpx,
5603 cpy,
5604 chroma_w,
5605 chroma_h,
5606 uv_predict_mode,
5607 angle_delta_uv,
5608 reach,
5609 &vec![0i32; chroma_w * chroma_h],
5610 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5611 None,
5612 smooth_neighbor_uv,
5613 );
5614 if let Some((_, vb)) = &palette_uv_bufs {
5615 set_palette_pred(vb.clone());
5616 }
5617 v.reconstruct_rect(
5618 cpx,
5619 cpy,
5620 chroma_w,
5621 chroma_h,
5622 uv_predict_mode,
5623 angle_delta_uv,
5624 reach,
5625 &vec![0i32; chroma_w * chroma_h],
5626 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5627 None,
5628 smooth_neighbor_uv,
5629 );
5630 neighbours.record_rect(
5631 at,
5632 bw,
5633 bh,
5634 mode,
5635 uv_predict_mode,
5636 &[
5637 vec![0i32; bw * bh],
5638 vec![0i32; chroma_w * chroma_h],
5639 vec![0i32; chroma_w * chroma_h],
5640 ],
5641 );
5642 } else {
5643 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
5644 // reduces both size pairs to their square-up CDF sets
5645 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
5646 // doc comments); the scan order and 2D context tables are the real
5647 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
5648 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
5649 (&SCAN_32X16, &SCAN_16X8)
5650 } else {
5651 (&SCAN_16X32, &SCAN_8X16)
5652 };
5653 // lane-rectwire r3: real coefficients desync a pixel-exact gate
5654 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
5655 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
5656 // pixel (not a subtle context-table off-by-one), while the sibling
5657 // non-rect quadrants of the same frame match. Range-ladder bisection
5658 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
5659 // but the intra key-frame path has no traced symbol between the
5660 // partition read and the first coefficient block (mode/skip/tx_depth
5661 // reads are all untraced in libaom's decodeframe.c intra path, unlike
5662 // the inter EC_TRACE_MODE this round added), so a same-length range
5663 // comparison wasn't reachable within budget -- see
5664 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
5665 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
5666 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
5667 // libaom and match). lane-rectwire r4: range-ladder against the
5668 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
5669 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
5670 // both confirmed in sync -- rng=58692 on both sides right after
5671 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
5672 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
5673 // immediately after: ours moves rng 58692 -> 43570, which cannot be
5674 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
5675 // its own tx_size read) unless oracle's tx symbol is a near-certainty
5676 // CDF that barely narrows the range -- i.e. this decoder's
5677 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
5678 // a 32x16/16x32 strip is the first diverging symbol, not the
5679 // coefficient-context math r3 already cleared. Not confirmed byte-
5680 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
5681 // `read_tx_size`'s own rng, not attempted this round -- budget), so
5682 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
5683 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
5684 // it unconditionally where both square paths gate on `tx_select`. With
5685 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
5686 // decoder consumed one that was never there.
5687 {
5688 let around = neighbours.around_rect(at, bw, bh);
5689 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
5690 let (luma_levels, luma_tx_type) = read_coeffs_rect(
5691 dec,
5692 &mut luma_coding,
5693 luma_scan,
5694 bw,
5695 bh,
5696 0,
5697 dc_sign_ctx(around[0].2),
5698 TxType::DctDct,
5699 )?;
5700 if std::env::var_os("EC_AV1_TRACE").is_some() {
5701 let (rng, _) = dec.debug_state();
5702 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
5703 }
5704 let luma_residual = dequant_and_inverse_typed_wh(
5705 &luma_levels,
5706 bw,
5707 bh,
5708 crate::decode::bit_depth(),
5709 block_q_idx(),
5710 plane_q_delta(0).0,
5711 plane_q_delta(0).1,
5712 luma_tx_type,
5713 );
5714 y.reconstruct_rect(
5715 px,
5716 py,
5717 bw,
5718 bh,
5719 mode,
5720 angle_delta_y,
5721 reach,
5722 &luma_residual,
5723 None,
5724 filter_intra,
5725 smooth_neighbor,
5726 );
5727 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5728 if let Some((ub, _)) = &palette_uv_bufs {
5729 set_palette_pred(ub.clone());
5730 }
5731 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5732 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
5733 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
5734 let (u_levels, u_tx_type) = read_coeffs_rect(
5735 dec,
5736 &mut u_coding,
5737 chroma_scan,
5738 chroma_w,
5739 chroma_h,
5740 u_skip_ctx,
5741 dc_sign_ctx(around[1].2),
5742 u_default_tx,
5743 )?;
5744 if std::env::var_os("EC_AV1_TRACE").is_some() {
5745 let (rng, _) = dec.debug_state();
5746 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
5747 }
5748 let u_residual = dequant_and_inverse_typed_wh(
5749 &u_levels,
5750 chroma_w,
5751 chroma_h,
5752 crate::decode::bit_depth(),
5753 block_q_idx(),
5754 plane_q_delta(1).0,
5755 plane_q_delta(1).1,
5756 u_tx_type,
5757 );
5758 u.reconstruct_rect(
5759 cpx,
5760 cpy,
5761 chroma_w,
5762 chroma_h,
5763 uv_predict_mode,
5764 angle_delta_uv,
5765 reach,
5766 &u_residual,
5767 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5768 None,
5769 smooth_neighbor_uv,
5770 );
5771 if let Some((_, vb)) = &palette_uv_bufs {
5772 set_palette_pred(vb.clone());
5773 }
5774 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5775 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
5776 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
5777 let (v_levels, v_tx_type) = read_coeffs_rect(
5778 dec,
5779 &mut v_coding,
5780 chroma_scan,
5781 chroma_w,
5782 chroma_h,
5783 v_skip_ctx,
5784 dc_sign_ctx(around[2].2),
5785 v_default_tx,
5786 )?;
5787 if std::env::var_os("EC_AV1_TRACE").is_some() {
5788 let (rng, _) = dec.debug_state();
5789 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
5790 }
5791 let v_residual = dequant_and_inverse_typed_wh(
5792 &v_levels,
5793 chroma_w,
5794 chroma_h,
5795 crate::decode::bit_depth(),
5796 block_q_idx(),
5797 plane_q_delta(2).0,
5798 plane_q_delta(2).1,
5799 v_tx_type,
5800 );
5801 v.reconstruct_rect(
5802 cpx,
5803 cpy,
5804 chroma_w,
5805 chroma_h,
5806 uv_predict_mode,
5807 angle_delta_uv,
5808 reach,
5809 &v_residual,
5810 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5811 None,
5812 smooth_neighbor_uv,
5813 );
5814 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
5815 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
5816 }
5817 }
5818 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
5819 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
5820 let (puv_size, puv_colors) =
5821 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
5822 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
5823 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
5824 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
5825 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
5826 if std::env::var_os("EC_AV1_TRACE").is_some() {
5827 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
5828 }
5829 Ok(())
5830}
5831
5832/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
5833/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
5834/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
5835/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
5836/// the second strip of a HORZ/VERT split sits offset by half the 16x16
5837/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
5838/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
5839/// previous strip is directly above (same column, `mi_h` rows up) or
5840/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
5841/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
5842/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
5843/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
5844/// this strip's real position, never the coarse `record_rect` (which the
5845/// caller uses once, after both strips, exactly like the `VERT_B` arm next
5846/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
5847/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
5848/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
5849/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
5850#[allow(clippy::too_many_arguments)]
5851fn decode_leaf_rect(
5852 dec: &mut SymbolDecoder,
5853 cdfs: &mut Cdfs,
5854 neighbours: &mut Neighbours,
5855 outer_at: (usize, usize),
5856 leaf_mi: (usize, usize),
5857 bw: usize,
5858 bh: usize,
5859 prev_leaf: Option<((usize, usize), usize)>,
5860 y: &mut PlaneBuf,
5861 u: &mut PlaneBuf,
5862 v: &mut PlaneBuf,
5863 enable_filter_intra: bool,
5864 allow_screen_content_tools: bool,
5865 base_q_idx: u8,
5866 tx_select: bool,
5867 reduced_tx_set: bool,
5868) -> Result<usize> {
5869 let _ = base_q_idx;
5870 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
5871 eprintln!(
5872 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
5873 dec.debug_state().0
5874 );
5875 }
5876 let (r, c) = outer_at;
5877 let mut above_mode = neighbours.above_mode[c];
5878 let mut left_mode = neighbours.left_mode[r];
5879 let (mi_w, mi_h) = (bw / MI, bh / MI);
5880 if let Some(((pr, pc), pmode)) = prev_leaf {
5881 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
5882 above_mode = pmode;
5883 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
5884 left_mode = pmode;
5885 }
5886 }
5887 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
5888 // cannot hold the modes a split (or a pair of strips) leaves behind, so
5889 // when the map holds the block at exactly this strip's above/left mi it
5890 // is the neighbour libaom's `above_mi`/`left_mi` reads.
5891 if let Some(m) = neighbours.mode_above_mi(leaf_mi.0, leaf_mi.1) {
5892 above_mode = m;
5893 }
5894 if let Some(m) = neighbours.mode_left_mi(leaf_mi.0, leaf_mi.1) {
5895 left_mode = m;
5896 }
5897 let smooth_neighbor =
5898 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
5899 if smooth_neighbor {
5900 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5901 }
5902 // The palette-Y mode CDF row is picked by the neighbours' palette use
5903 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
5904 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
5905 // a palette narrows the wrong interval and desyncs the tile even when the
5906 // decoded bit is the same. The cell is the 16px-SUB cell containing the
5907 // leaf (the palette neighbour arrays have no finer granularity).
5908 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
5909 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(pal_at);
5910 let palette_uv_cache = neighbours.palette_uv_cache(pal_at);
5911 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
5912 read_intra_mode_rect(
5913 dec,
5914 cdfs,
5915 above_mode,
5916 left_mode,
5917 true,
5918 bw,
5919 bh,
5920 enable_filter_intra,
5921 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
5922 allow_screen_content_tools,
5923 Some((palette_ctx, &palette_cache)),
5924 &palette_uv_cache,
5925 leaf_mi.0,
5926 leaf_mi.1,
5927 )?;
5928 if palette_y.is_some() || palette_uv.is_some() {
5929 // Symbols (mode/size/colours/index map) are all read above, so the
5930 // tile stays in sync; only the *pixel* reconstruction of a palette on
5931 // a below-16x16 strip is unported and ungated (lane-palette2 r7).
5932 return Err(unsupported(
5933 "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)",
5934 ));
5935 }
5936 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
5937 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
5938 }
5939 if filter_intra.is_some() {
5940 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
5941 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
5942 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
5943 // below already makes; this refusal was square-only prose.
5944 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
5945 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.set(c.get() + 1));
5946 }
5947 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
5948 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
5949 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
5950 // a constant `false`.
5951 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
5952 let depth = if tx_select {
5953 let ctx = tx_size_context_rect(neighbours, leaf_mi, bw, bh);
5954 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
5955 } else {
5956 0
5957 };
5958 if depth != 0 {
5959 return Err(unsupported(
5960 "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect \
5961 prediction is not ported)",
5962 ));
5963 }
5964 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
5965 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5966 let (cpx, cpy) = (px / 2, py / 2);
5967 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5968 let (luma_levels, u_levels, v_levels);
5969 if skip {
5970 luma_levels = vec![0i32; bw * bh];
5971 u_levels = vec![0i32; chroma_w * chroma_h];
5972 v_levels = vec![0i32; chroma_w * chroma_h];
5973 y.reconstruct_rect(
5974 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
5975 smooth_neighbor,
5976 );
5977 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5978 u.reconstruct_rect(
5979 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
5980 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
5981 );
5982 v.reconstruct_rect(
5983 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
5984 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
5985 );
5986 } else {
5987 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
5988 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
5989 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
5990 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
5991 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
5992 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
5993 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
5994 (&SCAN_16X8, &SCAN_8X4)
5995 } else {
5996 (&SCAN_8X16, &SCAN_4X8)
5997 };
5998 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
5999 let luma_set = if reduced_tx_set {
6000 TxbSet::LumaRect16x8
6001 } else {
6002 TxbSet::LumaRect16x8Set1
6003 };
6004 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
6005 let (l_levels, luma_tx_type) = read_coeffs_rect(
6006 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
6007 )?;
6008 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
6009 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
6010 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
6011 }
6012 luma_levels = l_levels;
6013 let luma_residual = dequant_and_inverse_typed_wh(
6014 &luma_levels, bw, bh, crate::decode::bit_depth(),
6015 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,
6016 );
6017 y.reconstruct_rect(
6018 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
6019 smooth_neighbor,
6020 );
6021 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6022 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
6023 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
6024 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
6025 let (u_l, u_tx_type) = read_coeffs_rect(
6026 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
6027 dc_sign_ctx(around[1].2), u_default_tx,
6028 )?;
6029 u_levels = u_l;
6030 let u_residual = dequant_and_inverse_typed_wh(
6031 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
6032 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,
6033 );
6034 u.reconstruct_rect(
6035 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
6036 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
6037 );
6038 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
6039 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
6040 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
6041 let (v_l, v_tx_type) = read_coeffs_rect(
6042 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
6043 dc_sign_ctx(around[2].2), v_default_tx,
6044 )?;
6045 v_levels = v_l;
6046 let v_residual = dequant_and_inverse_typed_wh(
6047 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
6048 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,
6049 );
6050 v.reconstruct_rect(
6051 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
6052 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
6053 );
6054 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
6055 }
6056 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
6057 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
6058 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
6059 // This leaf is necessarily non-palette (a palette one refused above), so
6060 // it must CLEAR the above/left palette state over its own span -- without
6061 // this the next block's `palette_y_mode` ctx and colour cache were read
6062 // off whatever block last covered the cell (lane-palette2 r8).
6063 neighbours.record_palette_y_rect(pal_at, bw, bh, 0, [0u16; 8]);
6064 neighbours.record_palette_uv_rect(pal_at, bw, bh, 0, [0u16; 8]);
6065 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
6066 // rows -- record the whole span, not one cell.
6067 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
6068 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
6069 Ok(mode)
6070}
6071
6072/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
6073/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
6074/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
6075/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
6076/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
6077/// strip's mode so this one's mode context sees its true above/left
6078/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
6079///
6080/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
6081/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
6082/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
6083/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
6084/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
6085/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
6086/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
6087///
6088/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
6089/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
6090/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
6091/// unexamined.
6092#[allow(clippy::too_many_arguments)]
6093fn decode_block_rect4(
6094 dec: &mut SymbolDecoder,
6095 cdfs: &mut Cdfs,
6096 neighbours: &mut Neighbours,
6097 strip_mi: (usize, usize),
6098 bw: usize,
6099 bh: usize,
6100 prev_strip: Option<((usize, usize), usize)>,
6101 y: &mut PlaneBuf,
6102 u: &mut PlaneBuf,
6103 v: &mut PlaneBuf,
6104 enable_filter_intra: bool,
6105 allow_screen_content_tools: bool,
6106 base_q_idx: u8,
6107 tx_select: bool,
6108) -> Result<(usize, usize)> {
6109 let _ = base_q_idx;
6110 let (mi_r, mi_c) = strip_mi;
6111 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
6112 let (mi_w, mi_h) = (bw / MI, bh / MI);
6113 let mut above_mode = neighbours.above_mode[c];
6114 let mut left_mode = neighbours.left_mode[r];
6115 if let Some(((pr, pc), pmode)) = prev_strip {
6116 if pc == mi_c && mi_r == pr + mi_h {
6117 above_mode = pmode;
6118 } else if pr == mi_r && mi_c == pc + mi_w {
6119 left_mode = pmode;
6120 }
6121 }
6122 let (
6123 skip,
6124 mode,
6125 angle_delta_y,
6126 uv_mode,
6127 angle_delta_uv,
6128 alpha,
6129 filter_intra,
6130 palette_y,
6131 palette_uv,
6132 ) = read_intra_mode_rect(
6133 dec,
6134 cdfs,
6135 above_mode,
6136 left_mode,
6137 true,
6138 bw,
6139 bh,
6140 enable_filter_intra,
6141 neighbours.skip_txfm_ctx(mi_r, mi_c),
6142 allow_screen_content_tools,
6143 None,
6144 &[],
6145 mi_r,
6146 mi_c,
6147 )?;
6148 // Merge of lane-palette2: `read_intra_mode_rect` now reads the palette
6149 // syntax for every rect strip, but this 1:4 decoder has no palette
6150 // reconstruction path (its caller never passes a cache). The symbols are
6151 // still read, so the stream stays in sync; a strip that ACTUALLY uses a
6152 // palette is refused rather than reconstructed wrong.
6153 if palette_y.is_some() || palette_uv.is_some() {
6154 return Err(unsupported(
6155 "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)",
6156 ));
6157 }
6158 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
6159 if smooth_neighbor {
6160 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6161 }
6162 let smooth_neighbor_uv =
6163 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
6164 if filter_intra.is_some() {
6165 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
6166 if bw > bh {
6167 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1));
6168 } else {
6169 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1));
6170 }
6171 }
6172 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
6173 DC_PRED
6174 } else {
6175 uv_mode
6176 };
6177 let depth = if tx_select {
6178 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
6179 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
6180 } else {
6181 0
6182 };
6183 if depth != 0 {
6184 // lane-tx64x16 r4: the depth is IN the message -- it says which port
6185 // the next round owes. depth 1 of a 4:1 strip is TX_16X8/TX_8X16
6186 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), a RECTANGULAR transform
6187 // unit with no luma coefficient tables here; depth 2 is TX_8X8,
6188 // square, the shape `decode_rect_split` already walks. The film stops
6189 // at depth 2, synthetic band fixtures hit both.
6190 return Err(unsupported(format!(
6191 "a 32x32-level 1:4 strip with a split transform (per-unit 4:1 prediction is not \
6192 ported, depth={depth})"
6193 )));
6194 }
6195 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
6196 // that is 8 px tall, so each strip stamps every cell it touches and the
6197 // LAST strip wins -- which is the right answer for the block below/right
6198 // of the 32x32, the only reader outside it. Written after this strip's
6199 // own context read above, never before.
6200 for cell in 0..bw.div_ceil(SUB) {
6201 neighbours.above_mode[c + cell] = mode;
6202 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
6203 neighbours.above_side[c + cell] = bw;
6204 }
6205 for cell in 0..bh.div_ceil(SUB) {
6206 neighbours.left_mode[r + cell] = mode;
6207 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
6208 neighbours.left_side[r + cell] = bh;
6209 }
6210 let (px, py) = (mi_c * MI, mi_r * MI);
6211 let (cpx, cpy) = (px / 2, py / 2);
6212 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
6213 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6214 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
6215 (&SCAN_32X8, &SCAN_16X4)
6216 } else {
6217 (&SCAN_8X32, &SCAN_4X16)
6218 };
6219 let (luma_levels, u_levels, v_levels) = if skip {
6220 (
6221 vec![0i32; bw * bh],
6222 vec![0i32; chroma_w * chroma_h],
6223 vec![0i32; chroma_w * chroma_h],
6224 )
6225 } else {
6226 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
6227 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
6228 let (luma_levels, luma_tx_type) = read_coeffs_rect(
6229 dec,
6230 &mut luma_coding,
6231 luma_scan,
6232 bw,
6233 bh,
6234 0,
6235 dc_sign_ctx(around[0].2),
6236 TxType::DctDct,
6237 )?;
6238 let mut planes = Vec::with_capacity(2);
6239 for plane in 1..3 {
6240 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
6241 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
6242 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
6243 let (levels, tx_type) = read_coeffs_rect(
6244 dec,
6245 &mut coding,
6246 chroma_scan,
6247 chroma_w,
6248 chroma_h,
6249 skip_ctx,
6250 dc_sign_ctx(around[plane].2),
6251 default_tx,
6252 )?;
6253 planes.push((levels, tx_type));
6254 }
6255 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
6256 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
6257 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
6258 let luma_residual = dequant_and_inverse_typed_wh(
6259 &luma_levels,
6260 bw,
6261 bh,
6262 crate::decode::bit_depth(),
6263 block_q_idx(),
6264 plane_q_delta(0).0,
6265 plane_q_delta(0).1,
6266 luma_tx_type,
6267 );
6268 y.reconstruct_rect(
6269 px,
6270 py,
6271 bw,
6272 bh,
6273 mode,
6274 angle_delta_y,
6275 reach,
6276 &luma_residual,
6277 None,
6278 filter_intra,
6279 smooth_neighbor,
6280 );
6281 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6282 for (plane, buf, levels, tx_type) in [
6283 (1usize, &mut *u, &u_levels, u_tx_type),
6284 (2, &mut *v, &v_levels, v_tx_type),
6285 ] {
6286 let residual = dequant_and_inverse_typed_wh(
6287 levels,
6288 chroma_w,
6289 chroma_h,
6290 crate::decode::bit_depth(),
6291 block_q_idx(),
6292 plane_q_delta(plane).0,
6293 plane_q_delta(plane).1,
6294 tx_type,
6295 );
6296 buf.reconstruct_rect(
6297 cpx,
6298 cpy,
6299 chroma_w,
6300 chroma_h,
6301 uv_predict_mode,
6302 angle_delta_uv,
6303 reach,
6304 &residual,
6305 alpha
6306 .zip(ac.as_deref())
6307 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
6308 None,
6309 smooth_neighbor_uv,
6310 );
6311 }
6312 neighbours.record_mi_rect(
6313 (mi_r, mi_c),
6314 bw,
6315 bh,
6316 &[luma_levels, u_levels, v_levels],
6317 );
6318 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
6319 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
6320 if bw > bh {
6321 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
6322 } else {
6323 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
6324 }
6325 return Ok((mode, uv_predict_mode));
6326 };
6327 y.reconstruct_rect(
6328 px,
6329 py,
6330 bw,
6331 bh,
6332 mode,
6333 angle_delta_y,
6334 reach,
6335 &luma_levels,
6336 None,
6337 filter_intra,
6338 smooth_neighbor,
6339 );
6340 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6341 u.reconstruct_rect(
6342 cpx,
6343 cpy,
6344 chroma_w,
6345 chroma_h,
6346 uv_predict_mode,
6347 angle_delta_uv,
6348 reach,
6349 &u_levels,
6350 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6351 None,
6352 smooth_neighbor_uv,
6353 );
6354 v.reconstruct_rect(
6355 cpx,
6356 cpy,
6357 chroma_w,
6358 chroma_h,
6359 uv_predict_mode,
6360 angle_delta_uv,
6361 reach,
6362 &v_levels,
6363 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6364 None,
6365 smooth_neighbor_uv,
6366 );
6367 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
6368 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
6369 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
6370 if bw > bh {
6371 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
6372 } else {
6373 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
6374 }
6375 Ok((mode, uv_predict_mode))
6376}
6377
6378/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
6379/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
6380/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
6381/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
6382/// cap, so LUMA needs the same corner truncation [`decode_block`] already
6383/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
6384/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
6385/// this function's own charter/report), so both strips read a real 32x32
6386/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
6387/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
6388/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
6389/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
6390/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
6391/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
6392/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
6393/// that function, only the single-transform-unit (`tx_depth == 0`) case is
6394/// supported: a split transform refuses by name rather than guess-decode.
6395#[allow(clippy::too_many_arguments)]
6396fn decode_block_rect64(
6397 dec: &mut SymbolDecoder,
6398 cdfs: &mut Cdfs,
6399 neighbours: &mut Neighbours,
6400 at: (usize, usize),
6401 bw: usize,
6402 bh: usize,
6403 y: &mut PlaneBuf,
6404 u: &mut PlaneBuf,
6405 v: &mut PlaneBuf,
6406 enable_filter_intra: bool,
6407 allow_screen_content_tools: bool,
6408 base_q_idx: u8,
6409 tx_select: bool,
6410 reduced_tx_set: bool,
6411) -> Result<()> {
6412 let (r, c) = at;
6413 let (px, py) = (c * SUB, r * SUB);
6414 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
6415 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
6416 let palette_uv_cache = neighbours.palette_uv_cache(at);
6417 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
6418 read_intra_mode_rect(
6419 dec,
6420 cdfs,
6421 nb_above_mode,
6422 nb_left_mode,
6423 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
6424 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
6425 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
6426 // correct), CFL must never be offered here -- passing `true`
6427 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
6428 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
6429 // from this block's very first symbol (lane-sbpart r3 bisect).
6430 false,
6431 bw,
6432 bh,
6433 enable_filter_intra,
6434 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
6435 allow_screen_content_tools,
6436 Some((palette_ctx, &palette_cache)),
6437 &palette_uv_cache,
6438 r * (SUB / MI),
6439 c * (SUB / MI),
6440 )?;
6441 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
6442 // The luma coefficient path here is the corner-cropped 32x32 real
6443 // transform embedded in a 64x32/32x64 grid ([`decode_block_rect64`]'s
6444 // own doc comment) -- a real (non-skip) palette block's residual
6445 // needs the plain, uncropped rect reader [`decode_block_rect`] already
6446 // has, not this one's truncation. `skip` (no residual at all) is
6447 // still supported below (lane-palette2 r4).
6448 return Err(unsupported(
6449 "a palette block with a real transform on a superblock-level HORZ/VERT \
6450 strip (corner-cropped luma coefficients not ported for palette)",
6451 ));
6452 }
6453 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
6454 if smooth_neighbor {
6455 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6456 }
6457 let smooth_neighbor_uv =
6458 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
6459 if filter_intra.is_some() {
6460 // `filter_intra_size_class_rect` already returns `None` for both
6461 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
6462 // 32 on both axes), so this symbol is never read at this level --
6463 // kept only as the same defensive refusal [`decode_block_rect`] has.
6464 return Err(unsupported(
6465 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
6466 av1_filter_intra_allowed_bsize caps at 32x32)",
6467 ));
6468 }
6469 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
6470 DC_PRED
6471 } else {
6472 uv_mode
6473 };
6474 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
6475 let depth = if tx_select {
6476 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
6477 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
6478 // counts `sub_tx_size_map` steps from the block's own max rect
6479 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
6480 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
6481 // steps, so this level's category is 3 (the same one a 64x64 square
6482 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
6483 // here was a wrong-table read of a real symbol.
6484 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
6485 } else {
6486 0
6487 };
6488 if depth != 0 {
6489 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
6490 // lane-rectsplit r1/r4: the superblock-level strip splits its
6491 // transform through the very same per-unit path as its 32x32-level
6492 // sibling (`sub_tx_size_map[TX_64X32] == TX_32X32`, square from the
6493 // first step on, so `bw.min(bh) >> (depth - 1)` names the unit).
6494 // lane-rectchroma r1: `sub_tx_size_map[TX_64X16] == TX_32X16`, NOT a
6495 // square -- a 4:1 strip's first transform split is still a 2:1 RECT
6496 // unit, and only the SECOND step reaches a square (TX_16X16). The
6497 // 2:1 formula below (square from the first step on) named 16x16 units
6498 // for a depth-1 64x16 strip, which decoded 2 chroma-32x8 strips of
6499 // the band fixture with the wrong luma tiling. depth 1 on a 4:1 strip
6500 // is refused by name; depth >= 2 is square, one step later.
6501 let is_1to4 = bw.max(bh) / bw.min(bh) == 4;
6502 if is_1to4 && depth == 1 && !skip {
6503 return Err(unsupported(
6504 "a coded 1:4 HORZ_4/VERT_4 strip whose transform splits only once (the unit is \
6505 still a 2:1 rect, not a square)",
6506 ));
6507 }
6508 let tx = if is_1to4 {
6509 bw.min(bh) >> (depth - 2)
6510 } else {
6511 bw.min(bh) >> (depth - 1)
6512 };
6513 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
6514 eprintln!(
6515 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
6516 depth={depth} tx={tx} mode={mode} uv={uv_predict_mode} skip={skip} \
6517 angle_y={angle_delta_y}"
6518 );
6519 }
6520 let modes = RectStripModes {
6521 skip,
6522 mode,
6523 angle_delta_y,
6524 uv_predict_mode,
6525 angle_delta_uv,
6526 alpha,
6527 filter_intra,
6528 smooth_neighbor,
6529 smooth_neighbor_uv,
6530 palette_y: palette_y
6531 .as_ref()
6532 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
6533 palette_uv: palette_uv.as_ref().map(|p| {
6534 (
6535 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
6536 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
6537 )
6538 }),
6539 };
6540 if palette_y.is_some() || palette_uv.is_some() {
6541 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
6542 }
6543 decode_rect_split(
6544 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,
6545 )?;
6546 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
6547 // (lane-palette2 r10): this return skips the fn's own tail, so a
6548 // split-tx superblock strip would otherwise leave the above/left
6549 // palette arrays holding a dead block's colours.
6550 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
6551 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
6552 let (puv_size, puv_colors) =
6553 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
6554 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
6555 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
6556 return Ok(());
6557 }
6558 let (tx_w, tx_h) = (bw, bh);
6559 let (cpx, cpy) = (px / 2, py / 2);
6560 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
6561 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6562 if let Some(ref pyv) = palette_y {
6563 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
6564 set_palette_pred(buf);
6565 }
6566 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
6567 (
6568 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
6569 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
6570 )
6571 });
6572 if skip {
6573 y.reconstruct_rect(
6574 px,
6575 py,
6576 bw,
6577 bh,
6578 mode,
6579 angle_delta_y,
6580 reach,
6581 &vec![0i32; bw * bh],
6582 None,
6583 filter_intra,
6584 smooth_neighbor,
6585 );
6586 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6587 if let Some((ub, _)) = &palette_uv_bufs {
6588 set_palette_pred(ub.clone());
6589 }
6590 u.reconstruct_rect(
6591 cpx,
6592 cpy,
6593 chroma_w,
6594 chroma_h,
6595 uv_predict_mode,
6596 angle_delta_uv,
6597 reach,
6598 &vec![0i32; chroma_w * chroma_h],
6599 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6600 None,
6601 smooth_neighbor_uv,
6602 );
6603 if let Some((_, vb)) = &palette_uv_bufs {
6604 set_palette_pred(vb.clone());
6605 }
6606 v.reconstruct_rect(
6607 cpx,
6608 cpy,
6609 chroma_w,
6610 chroma_h,
6611 uv_predict_mode,
6612 angle_delta_uv,
6613 reach,
6614 &vec![0i32; chroma_w * chroma_h],
6615 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6616 None,
6617 smooth_neighbor_uv,
6618 );
6619 neighbours.record_rect(
6620 at,
6621 bw,
6622 bh,
6623 mode,
6624 uv_predict_mode,
6625 &[
6626 vec![0i32; bw * bh],
6627 vec![0i32; chroma_w * chroma_h],
6628 vec![0i32; chroma_w * chroma_h],
6629 ],
6630 );
6631 } else {
6632 let around = neighbours.around_rect(at, bw, bh);
6633 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
6634 // (see this function's own doc comment). A 64-length axis codes only
6635 // its low 32 coefficients, so the corner is `min(bw, 32)` x
6636 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
6637 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
6638 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
6639 let scan32 = default_scan(TX32);
6640 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6641 let (rng, _) = dec.debug_state();
6642 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
6643 }
6644 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
6645 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
6646 read_coeffs(
6647 dec,
6648 &mut luma_coding,
6649 &scan32,
6650 0,
6651 dc_sign_ctx(around[0].2),
6652 TxType::DctDct,
6653 Some((bw, bh)),
6654 )?
6655 } else {
6656 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
6657 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
6658 // (`scan.c`) gives both the very same `default_scan_32x16` /
6659 // `default_scan_16x32` the 2:1 sizes use ("Half of the
6660 // coefficients of tx64 at higher frequencies are set to zeros. So
6661 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
6662 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
6663 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
6664 // 512-position eob group) -- BOTH identical to TX_32X16, so the
6665 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
6666 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
6667 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
6668 // what `base_ctx_rect` computes at (32, 16).
6669 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
6670 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
6671 read_coeffs_rect(
6672 dec,
6673 &mut luma_coding,
6674 luma_scan,
6675 luma_cw,
6676 luma_ch,
6677 0,
6678 dc_sign_ctx(around[0].2),
6679 TxType::DctDct,
6680 )?
6681 };
6682 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6683 let (rng, _) = dec.debug_state();
6684 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
6685 }
6686 let mut luma_levels = vec![0i32; bw * bh];
6687 for row in 0..luma_ch {
6688 luma_levels[row * bw..][..luma_cw]
6689 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
6690 }
6691 {
6692 let cur = block_q_idx();
6693 if cur != i32::from(base_q_idx) {
6694 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
6695 }
6696 if std::env::var_os("EC_AV1_TRACE").is_some() {
6697 eprintln!(
6698 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
6699 );
6700 }
6701 }
6702 let luma_residual = dequant_and_inverse_typed_wh(
6703 &luma_levels,
6704 bw,
6705 bh,
6706 crate::decode::bit_depth(),
6707 block_q_idx(),
6708 plane_q_delta(0).0,
6709 plane_q_delta(0).1,
6710 luma_tx_type,
6711 );
6712 y.reconstruct_rect(
6713 px,
6714 py,
6715 bw,
6716 bh,
6717 mode,
6718 angle_delta_y,
6719 reach,
6720 &luma_residual,
6721 None,
6722 filter_intra,
6723 smooth_neighbor,
6724 );
6725 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
6726 let leftcol: Vec<u16> = if px > 0 {
6727 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
6728 } else {
6729 vec![]
6730 };
6731 eprintln!(
6732 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
6733 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
6734 luma_corner.iter().any(|&v| v != 0),
6735 &y.data[py * y.width + px..][..bw],
6736 leftcol,
6737 );
6738 }
6739 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
6740 // corner crop needed (see doc comment).
6741 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6742 // The chroma plane is never truncated (both axes <= 32 after
6743 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
6744 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
6745 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
6746 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
6747 // set, and only the scan is new (lane-tx64x16).
6748 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
6749 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
6750 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
6751 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
6752 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
6753 };
6754 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
6755 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
6756 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6757 let (rng, _) = dec.debug_state();
6758 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
6759 }
6760 let (u_levels, u_tx_type) = read_coeffs_rect(
6761 dec,
6762 &mut u_coding,
6763 chroma_scan,
6764 chroma_w,
6765 chroma_h,
6766 u_skip_ctx,
6767 dc_sign_ctx(around[1].2),
6768 TxType::DctDct,
6769 )?;
6770 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6771 let (rng, _) = dec.debug_state();
6772 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
6773 }
6774 {
6775 let cur = block_q_idx();
6776 if cur != i32::from(base_q_idx) {
6777 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
6778 }
6779 if std::env::var_os("EC_AV1_TRACE").is_some() {
6780 eprintln!(
6781 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
6782 );
6783 }
6784 }
6785 let u_residual = dequant_and_inverse_typed_wh(
6786 &u_levels,
6787 chroma_w,
6788 chroma_h,
6789 crate::decode::bit_depth(),
6790 block_q_idx(),
6791 plane_q_delta(1).0,
6792 plane_q_delta(1).1,
6793 u_tx_type,
6794 );
6795 u.reconstruct_rect(
6796 cpx,
6797 cpy,
6798 chroma_w,
6799 chroma_h,
6800 uv_predict_mode,
6801 angle_delta_uv,
6802 reach,
6803 &u_residual,
6804 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6805 None,
6806 smooth_neighbor_uv,
6807 );
6808 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
6809 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
6810 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6811 let (rng, _) = dec.debug_state();
6812 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
6813 }
6814 let (v_levels, v_tx_type) = read_coeffs_rect(
6815 dec,
6816 &mut v_coding,
6817 chroma_scan,
6818 chroma_w,
6819 chroma_h,
6820 v_skip_ctx,
6821 dc_sign_ctx(around[2].2),
6822 TxType::DctDct,
6823 )?;
6824 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6825 let (rng, _) = dec.debug_state();
6826 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
6827 }
6828 {
6829 let cur = block_q_idx();
6830 if cur != i32::from(base_q_idx) {
6831 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
6832 }
6833 if std::env::var_os("EC_AV1_TRACE").is_some() {
6834 eprintln!(
6835 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
6836 );
6837 }
6838 }
6839 let v_residual = dequant_and_inverse_typed_wh(
6840 &v_levels,
6841 chroma_w,
6842 chroma_h,
6843 crate::decode::bit_depth(),
6844 block_q_idx(),
6845 plane_q_delta(2).0,
6846 plane_q_delta(2).1,
6847 v_tx_type,
6848 );
6849 v.reconstruct_rect(
6850 cpx,
6851 cpy,
6852 chroma_w,
6853 chroma_h,
6854 uv_predict_mode,
6855 angle_delta_uv,
6856 reach,
6857 &v_residual,
6858 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6859 None,
6860 smooth_neighbor_uv,
6861 );
6862 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
6863 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
6864 }
6865 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
6866 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
6867 let (puv_size, puv_colors) =
6868 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
6869 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
6870 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
6871 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
6872 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
6873 match (bw, bh) {
6874 (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)),
6875 (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)),
6876 _ => {}
6877 }
6878 if std::env::var_os("EC_AV1_TRACE").is_some() {
6879 let (rng, _) = dec.debug_state();
6880 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
6881 }
6882 Ok(())
6883}
6884
6885/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
6886/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
6887/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
6888/// it lands away from zero, for gate tests to prove a real stream fired one.
6889fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
6890 let symbol = dec.symbol(cdf);
6891 if symbol != ANGLE_DELTA_ZERO {
6892 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
6893 }
6894 symbol as i32 - ANGLE_DELTA_ZERO as i32
6895}
6896
6897#[allow(clippy::too_many_arguments)]
6898fn read_intra_mode(
6899 dec: &mut SymbolDecoder,
6900 cdfs: &mut Cdfs,
6901 above_mode: usize,
6902 left_mode: usize,
6903 cfl: bool,
6904 side: usize,
6905 enable_filter_intra: bool,
6906 skip_ctx: usize,
6907 allow_screen_content_tools: bool,
6908 allow_intrabc: bool,
6909 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
6910 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
6911 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
6912 // `None` at the excluded call sites (the 8x8-leaf path), which still read
6913 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
6914 // decoder reads either way -- but refuse by name the moment it fires,
6915 // exactly the old behaviour.
6916 palette: Option<(usize, &[u16])>,
6917 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
6918 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
6919 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
6920 // `use_palette_y`, not a neighbour lookup).
6921 palette_uv_cache: &[u16],
6922 mi_r: usize,
6923 mi_c: usize,
6924) -> Result<(
6925 bool,
6926 usize,
6927 i32,
6928 usize,
6929 i32,
6930 Option<(i32, i32)>,
6931 Option<usize>,
6932 Option<PaletteY>,
6933 Option<PaletteUv>,
6934)> {
6935 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
6936 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
6937 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
6938 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
6939 // line against the instrumented aomdec, not just `tell()`.
6940 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
6941 macro_rules! istep {
6942 ($name:literal, $val:expr) => {
6943 if ec_istep {
6944 let (rng, _) = dec.debug_state();
6945 eprintln!(
6946 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
6947 $name, $val
6948 );
6949 }
6950 };
6951 }
6952 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
6953 // `skip` when `SegIdPreSkip`, and after it otherwise.
6954 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
6955 if seg_id_pre_skip() {
6956 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
6957 }
6958 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
6959 if trace {
6960 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
6961 }
6962 istep!("skip", skip as i32);
6963 if !seg_id_pre_skip() {
6964 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
6965 }
6966 // spec order (see the comment below on `read_intrabc_info`): `skip`,
6967 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
6968 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
6969 istep!("cdef", 0);
6970 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, side == 64, skip);
6971 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, side == 64, skip);
6972 istep!("dq", 0);
6973 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
6974 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
6975 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
6976 // intra frame whose header set `allow_intrabc`. Actual intra block copy
6977 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
6978 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
6979 // draws the line at consuming this one flag symbol and refusing by name
6980 // when it fires, so the arithmetic decoder still resyncs for a stream
6981 // that merely allows (but never uses) intrabc.
6982 if allow_intrabc {
6983 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
6984 if trace {
6985 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
6986 }
6987 if use_intrabc {
6988 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
6989 if trace {
6990 eprintln!("TRACE intrabc dv={dv:?}");
6991 }
6992 INTRABC_DV.with(|c| c.set(Some(dv)));
6993 INTRABC_HITS.with(|c| c.set(c.get() + 1));
6994 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
6995 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
6996 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
6997 // `DC_PRED` (which is also what the neighbour mode contexts and
6998 // the loop filter then see).
6999 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
7000 }
7001 }
7002 let above_ctx = INTRA_MODE_CTX[above_mode];
7003 let left_ctx = INTRA_MODE_CTX[left_mode];
7004 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
7005 if trace {
7006 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
7007 }
7008 istep!("mode", mode as i32);
7009 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
7010 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
7011 if trace {
7012 eprintln!(
7013 "TRACE angle_delta value={}",
7014 delta + ANGLE_DELTA_ZERO as i32
7015 );
7016 }
7017 delta
7018 } else {
7019 0
7020 };
7021 istep!("angle_y", angle_delta_y);
7022 let uv_mode = if cfl {
7023 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
7024 } else {
7025 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
7026 };
7027 if trace {
7028 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
7029 }
7030 istep!("uv_mode", uv_mode as i32);
7031 let alpha = if cfl && uv_mode == UV_CFL_PRED {
7032 Some(read_cfl_alphas(dec, cdfs))
7033 } else {
7034 None
7035 };
7036 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
7037 // from this lane's directional chroma: a corner block with neither
7038 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
7039 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
7040 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
7041 // bug in that fallback this lane's own scope does not cover. Keep it
7042 // refused here rather than ship a silently-wrong decode.
7043 if (9..=12).contains(&uv_mode) {
7044 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
7045 }
7046 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
7047 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
7048 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
7049 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
7050 // the `else` branch below and never reads one either way.
7051 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
7052 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
7053 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
7054 } else {
7055 0
7056 };
7057 istep!("angle_uv", angle_delta_uv);
7058 if angle_delta_uv != 0 {
7059 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
7060 }
7061 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
7062 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
7063 // gated by `av1_allow_palette` (blockd.h -- size bound only,
7064 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
7065 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
7066 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
7067 // read the same CDF row whenever every neighbour really is non-palette).
7068 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
7069 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
7070 // neighbour lookup at all), so it is exact even at the excluded call
7071 // sites once Y decodes real syntax there too.
7072 //
7073 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
7074 // inline from `read_palette_mode_info` -- it runs later, from
7075 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
7076 // after the WHOLE mode-info read for the block, including UV palette
7077 // mode_info (`read_palette_mode_info`'s own second half, right below)
7078 // and `read_filter_intra_mode_info`. So this branch now only reads
7079 // mode/size/colours for both planes (deferring the two colour-index-map
7080 // decodes to after `filter_intra`, below) -- r6's range trace pinned
7081 // this exact ordering bug (`compare-range-not-tell`: ranges matched
7082 // bit-for-bit through the Y colours, diverged only at the old inline
7083 // `decode_color_index_map` call).
7084 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
7085 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
7086 if allow_screen_content_tools
7087 && let Some(bsize_ctx) = palette_bsize_ctx(side)
7088 {
7089 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
7090 if mode == DC_PRED {
7091 if trace {
7092 let (rng, _) = dec.debug_state();
7093 eprintln!(
7094 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
7095 );
7096 }
7097 }
7098 let use_palette_y =
7099 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
7100 if mode == DC_PRED && trace {
7101 let (rng, _) = dec.debug_state();
7102 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
7103 }
7104 if use_palette_y {
7105 if palette.is_none() {
7106 return Err(unsupported(
7107 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
7108 ));
7109 }
7110 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
7111 if trace {
7112 let (rng, _) = dec.debug_state();
7113 eprintln!("TRACE palette_y_size n={n} rng={rng}");
7114 }
7115 let colors = read_palette_colors_y(dec, n, cache);
7116 if trace {
7117 let (rng, _) = dec.debug_state();
7118 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
7119 }
7120 palette_y_pending = Some((n, colors));
7121 }
7122 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
7123 // unconditionally at this bit position whenever `uv_mode ==
7124 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
7125 // scope always reconstructs chroma alongside luma (`decode_block`
7126 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
7127 // is always true here and does not need threading in.
7128 let palette_uv_mode_ctx = usize::from(use_palette_y);
7129 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
7130 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
7131 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
7132 palette_uv_pending = Some((n, u_colors, v_colors));
7133 }
7134 }
7135 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
7136 // `use_filter_intra` symbol this decoder never read at all until
7137 // lane-av1real r10 -- silently skipping it left every bit past a
7138 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
7139 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
7140 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
7141 // symbol's bits were never consumed).
7142 let mut filter_intra = None;
7143 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
7144 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
7145 // `use_filter_intra` symbol for a Y-palette block, and reading one here
7146 // desynced every screen-content stream from the first palette block on
7147 // (it surfaced as a bogus "partition below 8x8" refusal further down the
7148 // tile).
7149 if mode == DC_PRED
7150 && enable_filter_intra
7151 && palette_y_pending.is_none()
7152 && let Some(class) = filter_intra_size_class(side)
7153 {
7154 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
7155 if trace {
7156 eprintln!(
7157 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
7158 use_filter_intra as i32
7159 );
7160 }
7161 istep!("use_filter_intra", use_filter_intra as i32);
7162 if use_filter_intra {
7163 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
7164 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
7165 if trace {
7166 eprintln!("TRACE filter_intra_mode value={fi_mode}");
7167 }
7168 istep!("filter_intra_mode", fi_mode as i32);
7169 filter_intra = Some(fi_mode);
7170 }
7171 }
7172 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
7173 // shared U/V map) -- the same order libaom's own loop visits them in.
7174 let palette_y = palette_y_pending.map(|(n, colors)| {
7175 let map = decode_color_index_map(dec, cdfs, n, side, false);
7176 PALETTE_HITS.with(|c| c.set(c.get() + 1));
7177 if trace {
7178 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
7179 }
7180 PaletteY { size: n, colors, map }
7181 });
7182 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
7183 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
7184 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
7185 if trace {
7186 eprintln!(
7187 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
7188 &u_colors[..n],
7189 &v_colors[..n]
7190 );
7191 }
7192 PaletteUv { size: n, u_colors, v_colors, map }
7193 });
7194 Ok((
7195 skip,
7196 mode,
7197 angle_delta_y,
7198 uv_mode,
7199 angle_delta_uv,
7200 alpha,
7201 filter_intra,
7202 palette_y,
7203 palette_uv,
7204 ))
7205}
7206
7207/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
7208/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
7209/// intra modes.
7210const UV_CFL_PRED: usize = 13;
7211
7212/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
7213/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
7214/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
7215/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
7216/// joint sign the same way. Returns each plane's final signed `alpha_q3`
7217/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
7218fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
7219 CFL_BLOCK_HITS.with(|c| c.set(c.get() + 1));
7220 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
7221 let sign_u = ((joint_sign + 1) * 11) >> 5;
7222 let sign_v = (joint_sign + 1) - 3 * sign_u;
7223 let alpha_u = if sign_u == 0 {
7224 0
7225 } else {
7226 let ctx_u = (joint_sign + 1 - 3) as usize;
7227 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
7228 if sign_u == 2 { mag } else { -mag }
7229 };
7230 let alpha_v = if sign_v == 0 {
7231 0
7232 } else {
7233 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
7234 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
7235 if sign_v == 2 { mag } else { -mag }
7236 };
7237 (alpha_u, alpha_v)
7238}
7239
7240/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
7241/// the reconstructed luma samples under a `side`-square block, subsampled
7242/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
7243/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
7244/// to give the AC values [`cfl_scaled`] scales by alpha.
7245fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
7246 let cside = side / 2;
7247 let mut ac = vec![0i32; cside * cside];
7248 let mut sum = 0i32;
7249 for cy in 0..cside {
7250 for cx in 0..cside {
7251 let (lx, ly) = (px + cx * 2, py + cy * 2);
7252 let q3 = (i32::from(y.data[ly * y.width + lx])
7253 + i32::from(y.data[ly * y.width + lx + 1])
7254 + i32::from(y.data[(ly + 1) * y.width + lx])
7255 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
7256 << 1;
7257 ac[cy * cside + cx] = q3;
7258 sum += q3;
7259 }
7260 }
7261 let num_pel = (cside * cside) as i32;
7262 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
7263 ac.iter_mut().for_each(|v| *v -= avg);
7264 ac
7265}
7266
7267/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
7268/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
7269/// ties away from zero on the shifted-out sign).
7270fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
7271 let v = alpha_q3 * ac_q3;
7272 if v >= 0 {
7273 (v + 32) >> 6
7274 } else {
7275 -((-v + 32) >> 6)
7276 }
7277}
7278
7279/// One plane's reconstruction buffer, `width * height` samples, and the
7280/// prediction/residual reads and writes into it — the decode-side twin of
7281/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
7282/// (own-edge and reach clamps both), passing what it gathers straight to
7283/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
7284/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
7285/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
7286fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
7287 use std::io::Write;
7288 if let Ok(path) = std::env::var(var)
7289 && let Ok(mut f) = std::fs::File::create(format!("{path}.f0"))
7290 {
7291 for p in [y, u, v] {
7292 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
7293 let _ = f.write_all(&narrow);
7294 }
7295 }
7296}
7297
7298#[derive(Clone)]
7299struct PlaneBuf {
7300 data: Vec<u16>,
7301 width: usize,
7302 height: usize,
7303 /// The frame's true, decodable extent in this plane's own units — past
7304 /// this, samples are the padded coding surface's invented tail, never a
7305 /// real decoder's edge or reach reads.
7306 true_width: usize,
7307 true_height: usize,
7308 /// This plane's own tile's top-left pixel origin (spec: intra prediction
7309 /// never reaches across a tile boundary even though an earlier-decoded
7310 /// tile's real pixels sit right there in the shared buffer) — set via
7311 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
7312 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
7313 /// is threaded (the two-tile column-split stage 1 fixture's tile always
7314 /// ends at the frame's own right/bottom edge); a non-last tile's own
7315 /// right/bottom reach bound is still open, tracked in the report.
7316 tile_x0: usize,
7317 tile_y0: usize,
7318 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
7319 /// (exclusive) -- a non-last tile column/row's own reach must stop at
7320 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
7321 /// full padded extent) for the single-tile/last-tile case, matching the
7322 /// old unclipped behaviour exactly.
7323 tile_x1: usize,
7324 tile_y1: usize,
7325}
7326
7327/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
7328/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
7329/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
7330/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
7331/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
7332/// `ALTREF2`/`ALTREF`).
7333type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
7334
7335impl PlaneBuf {
7336 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
7337 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
7338 /// are already in this plane's own units (luma pixels for `y`, chroma
7339 /// pixels — halved — for `u`/`v`).
7340 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
7341 self.tile_x0 = x0;
7342 self.tile_y0 = y0;
7343 self.tile_x1 = x1;
7344 self.tile_y1 = y1;
7345 }
7346
7347 fn edges(
7348 &self,
7349 x: usize,
7350 y: usize,
7351 side: usize,
7352 reach: Reach,
7353 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
7354 let own_across = x + side.min(self.true_width.saturating_sub(x));
7355 let across = if reach.above_right {
7356 own_across + side.min(self.true_width.saturating_sub(own_across))
7357 } else {
7358 own_across
7359 }
7360 .min(self.width)
7361 .min(self.tile_x1);
7362 let own_down = y + side.min(self.true_height.saturating_sub(y));
7363 let down = if reach.below_left {
7364 own_down + side.min(self.true_height.saturating_sub(own_down))
7365 } else {
7366 own_down
7367 }
7368 .min(self.height)
7369 .min(self.tile_y1);
7370 let above = (y > self.tile_y0 && across > x)
7371 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
7372 let left = (x > self.tile_x0 && down > y).then(|| {
7373 (y..down)
7374 .map(|row| self.data[row * self.width + x - 1])
7375 .collect::<Vec<_>>()
7376 });
7377 let corner =
7378 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
7379 (above, left, corner)
7380 }
7381
7382 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
7383 /// the above/left reach each extend by their OWN axis (`bw` across,
7384 /// `bh` down), not one shared `side`.
7385 fn edges_rect(
7386 &self,
7387 x: usize,
7388 y: usize,
7389 bw: usize,
7390 bh: usize,
7391 reach: Reach,
7392 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
7393 let own_across = x + bw.min(self.true_width.saturating_sub(x));
7394 let across = if reach.above_right {
7395 own_across + bw.min(self.true_width.saturating_sub(own_across))
7396 } else {
7397 own_across
7398 }
7399 .min(self.width)
7400 .min(self.tile_x1);
7401 let own_down = y + bh.min(self.true_height.saturating_sub(y));
7402 let down = if reach.below_left {
7403 own_down + bh.min(self.true_height.saturating_sub(own_down))
7404 } else {
7405 own_down
7406 }
7407 .min(self.height)
7408 .min(self.tile_y1);
7409 let above = (y > self.tile_y0 && across > x)
7410 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
7411 let left = (x > self.tile_x0 && down > y).then(|| {
7412 (y..down)
7413 .map(|row| self.data[row * self.width + x - 1])
7414 .collect::<Vec<_>>()
7415 });
7416 let corner =
7417 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
7418 if matches!((bw, bh), (16, 8) | (8, 16)) {
7419 RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1));
7420 if across > own_across || down > own_down {
7421 RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1));
7422 }
7423 }
7424 (above, left, corner)
7425 }
7426
7427 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
7428 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
7429 /// already-rect-capable `(bw, bh)` pair.
7430 #[allow(clippy::too_many_arguments)]
7431 fn reconstruct_rect(
7432 &mut self,
7433 x: usize,
7434 y: usize,
7435 bw: usize,
7436 bh: usize,
7437 mode: usize,
7438 angle_delta: i32,
7439 reach: Reach,
7440 residual: &[i32],
7441 cfl: Option<(i32, &[i32])>,
7442 filter_intra: Option<usize>,
7443 smooth_neighbor: bool,
7444 ) {
7445 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
7446 // (lane-palette2 r4): a palette block's prediction is the
7447 // reconstructed colour-index map, needing no edge pixels at all.
7448 let prediction = if let Some(buf) = take_palette_pred() {
7449 buf
7450 } else {
7451 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
7452 if std::env::var_os("EC_DEBUG_EDGES").is_some() {
7453 eprintln!(
7454 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
7455 above.as_ref().map(|a| (a.len(), a[0])),
7456 left.as_ref().map(|l| l.len()),
7457 left.as_ref().map(|l| l[0]),
7458 self.tile_x0, self.tile_y0, self.true_width, self.true_height
7459 );
7460 }
7461 let mut prediction = vec![0u16; bw * bh];
7462 if let Some(fi_mode) = filter_intra {
7463 crate::intra::predict_filter_intra(
7464 fi_mode,
7465 above.as_deref(),
7466 left.as_deref(),
7467 corner,
7468 bw,
7469 bh,
7470 &mut prediction,
7471 );
7472 } else {
7473 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
7474 predict(
7475 mode as u8,
7476 angle_delta,
7477 above.as_deref(),
7478 left.as_deref(),
7479 corner,
7480 bw,
7481 bh,
7482 enable_edge_filter,
7483 smooth_neighbor,
7484 &mut prediction,
7485 );
7486 }
7487 prediction
7488 };
7489 for row in 0..bh {
7490 for col in 0..bw {
7491 let idx = row * bw + col;
7492 let mut base = i32::from(prediction[idx]);
7493 if let Some((alpha_q3, ac_q3)) = cfl {
7494 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
7495 }
7496 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
7497 self.data[(y + row) * self.width + x + col] = sample;
7498 }
7499 }
7500 }
7501
7502 /// Predicts under `mode` then adds `residual` (side*side, raster),
7503 /// writing the clamped reconstruction back into the plane at `(x, y)`.
7504 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
7505 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
7506 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
7507 /// order (cfl.c).
7508 fn reconstruct(
7509 &mut self,
7510 x: usize,
7511 y: usize,
7512 side: usize,
7513 mode: usize,
7514 angle_delta: i32,
7515 reach: Reach,
7516 residual: &[i32],
7517 cfl: Option<(i32, &[i32])>,
7518 filter_intra: Option<usize>,
7519 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
7520 // libaom `get_filt_type`): true when the block's above OR left
7521 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
7522 // Callers pass their own plane's neighbour-mode check
7523 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
7524 // callers until a smooth/paeth `uv_mode` can reach this call at all
7525 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
7526 // keeps `false` exact for chroma without this fn needing to know why.
7527 smooth_neighbor: bool,
7528 ) {
7529 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
7530 // takes priority over `predict()`/`predict_filter_intra` entirely --
7531 // palette prediction needs no edge pixels at all.
7532 let prediction = if let Some(buf) = take_palette_pred() {
7533 buf
7534 } else {
7535 let (above, left, corner) = self.edges(x, y, side, reach);
7536 let mut prediction = vec![0u16; side * side];
7537 if let Some(fi_mode) = filter_intra {
7538 crate::intra::predict_filter_intra(
7539 fi_mode,
7540 above.as_deref(),
7541 left.as_deref(),
7542 corner,
7543 side,
7544 side,
7545 &mut prediction,
7546 );
7547 } else {
7548 // `enable_intra_edge_filter` is the sequence header's own flag
7549 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
7550 // call, never per-block) -- threading it through every
7551 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
7552 // dozen sites for a value that never changes mid-decode, so it
7553 // rides a thread-local instead (this decoder is single-threaded
7554 // per stream).
7555 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
7556 predict(
7557 mode as u8,
7558 angle_delta,
7559 above.as_deref(),
7560 left.as_deref(),
7561 corner,
7562 side,
7563 side,
7564 enable_edge_filter,
7565 smooth_neighbor,
7566 &mut prediction,
7567 );
7568 }
7569 prediction
7570 };
7571 for row in 0..side {
7572 for col in 0..side {
7573 let idx = row * side + col;
7574 let mut base = i32::from(prediction[idx]);
7575 if let Some((alpha_q3, ac_q3)) = cfl {
7576 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
7577 }
7578 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
7579 self.data[(y + row) * self.width + x + col] = sample;
7580 }
7581 }
7582 }
7583}
7584
7585/// Reads one plane's transform block, reconstructs it into `plane` at
7586/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
7587#[allow(clippy::too_many_arguments)]
7588fn read_plane(
7589 dec: &mut SymbolDecoder,
7590 cdfs: &mut Cdfs,
7591 set: TxbSet,
7592 scan: &[u16],
7593 plane_idx: usize,
7594 around: (bool, bool, i32),
7595 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
7596 // it for every plane's `txb` lookup (it is what an intra transform type's
7597 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
7598 tx_mode: usize,
7599 predict_mode: usize,
7600 angle_delta: i32,
7601 reach: Reach,
7602 plane: &mut PlaneBuf,
7603 x: usize,
7604 y: usize,
7605 side: usize,
7606 tx_side: usize,
7607 base_q_idx: u8,
7608 cfl: Option<(i32, &[i32])>,
7609 filter_intra: Option<usize>,
7610 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
7611 // smaller than its own block (spec `get_txb_ctx_general`'s
7612 // `plane_bsize != tx_size` branch), carrying the already-looked-up
7613 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
7614 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
7615 // formula below.
7616 luma_skip_ctx: Option<usize>,
7617 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
7618 smooth_neighbor: bool,
7619) -> Result<Vec<i32>> {
7620 let skip_ctx = if plane_idx == 0 {
7621 luma_skip_ctx.unwrap_or(0)
7622 } else {
7623 usize::from(around.0) + usize::from(around.1)
7624 };
7625 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
7626 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
7627 // not by the block's ordinary `mode` (which is always DC_PRED whenever
7628 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
7629 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
7630 // filter-intra in AV1).
7631 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
7632 let mut coding = cdfs.txb(set, tx_mode);
7633 // Luma's `default_tx_type` is only a fallback for the sizes whose
7634 // `TxbSet` carries no symbol at all (32-point and up), which the spec
7635 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
7636 // *never* its own coded symbol (`coding.tx_type` is always `None` for
7637 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
7638 // the plane's own predicted mode (`default_intra_tx_type`) -- except
7639 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
7640 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
7641 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
7642 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
7643 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
7644 // narrows there — only `Chroma32` and up do).
7645 let default_tx_type = if plane_idx == 0 || side >= 32 {
7646 TxType::DctDct
7647 } else {
7648 default_intra_tx_type(predict_mode as u8)
7649 };
7650 let (grid, tx_type) = read_coeffs(
7651 dec,
7652 &mut coding,
7653 scan,
7654 skip_ctx,
7655 dc_sign_ctx(around.2),
7656 default_tx_type,
7657 None,
7658 )?;
7659 note_chroma_class1(plane_idx, tx_type);
7660 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
7661 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
7662 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
7663 // guard also assumes.
7664 let levels = if tx_side == side {
7665 grid
7666 } else {
7667 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
7668 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
7669 // keyed by that true size, not the coded corner's -- so the corner
7670 // goes into the top-left of a `side`-sized grid, not the reverse.
7671 let mut full = vec![0i32; side * side];
7672 for row in 0..tx_side {
7673 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
7674 }
7675 full
7676 };
7677 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
7678 let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
7679 if std::env::var_os("EC_AV1_TRACE").is_some() {
7680 eprintln!(
7681 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
7682 );
7683 }
7684 plane.reconstruct(
7685 x,
7686 y,
7687 side,
7688 predict_mode,
7689 angle_delta,
7690 reach,
7691 &residual,
7692 cfl,
7693 filter_intra,
7694 smooth_neighbor,
7695 );
7696 Ok(if tx_side == side {
7697 residual_grid_placeholder(&levels, side)
7698 } else {
7699 levels
7700 })
7701}
7702
7703/// `record`'s neighbour state only reads whether *the coded grid* (not the
7704/// residual) has nonzero entries, so the levels this function already built
7705/// are what it wants back; this helper exists only to name that clearly at
7706/// the one call site where `tx_side == side`.
7707fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
7708 levels.to_vec()
7709}
7710
7711/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
7712/// three planes, reconstructing them into `y`/`u`/`v` and updating
7713/// `neighbours`.
7714#[allow(clippy::too_many_arguments)]
7715fn decode_block(
7716 dec: &mut SymbolDecoder,
7717 cdfs: &mut Cdfs,
7718 neighbours: &mut Neighbours,
7719 at: (usize, usize),
7720 side: usize,
7721 luma_set: TxbSet,
7722 chroma_set: TxbSet,
7723 luma_tx: usize,
7724 chroma_tx: usize,
7725 scans: (&[u16], &[u16]),
7726 cfl: bool,
7727 y: &mut PlaneBuf,
7728 u: &mut PlaneBuf,
7729 v: &mut PlaneBuf,
7730 base_q_idx: u8,
7731 enable_filter_intra: bool,
7732 allow_screen_content_tools: bool,
7733 allow_intrabc: bool,
7734 scan32: &[u16],
7735 scan16: &[u16],
7736 scan8: &[u16],
7737 scan4: &[u16],
7738 tx_select: bool,
7739 reduced_tx_set: bool,
7740) -> Result<()> {
7741 let (r, c) = at;
7742 let (px, py) = (c * SUB, r * SUB);
7743 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
7744 let palette_uv_cache = neighbours.palette_uv_cache(at);
7745 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
7746 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
7747 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
7748 read_intra_mode(
7749 dec,
7750 cdfs,
7751 nb_above_mode,
7752 nb_left_mode,
7753 cfl,
7754 side,
7755 enable_filter_intra,
7756 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
7757 allow_screen_content_tools,
7758 allow_intrabc,
7759 Some((palette_ctx, &palette_cache)),
7760 &palette_uv_cache,
7761 r * (SUB / MI),
7762 c * (SUB / MI),
7763 )?;
7764 if at_tile_left && palette_y.is_some() {
7765 PALETTE_TILE_LEFT_HITS.with(|c| c.set(c.get() + 1));
7766 }
7767 let intrabc_dv = INTRABC_DV.with(|c| c.take());
7768 // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
7769 // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
7770 // partition tree (`read_var_tx_size`), a syntax element this decoder has
7771 // nowhere -- reading the intra `tx_depth` symbol instead would desync.
7772 if intrabc_dv.is_some() && tx_select && !skip {
7773 return Err(unsupported(
7774 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
7775 ));
7776 }
7777 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
7778 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
7779 // actual chroma-from-luma correlation, same as this decoder always did.
7780 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
7781 DC_PRED
7782 } else {
7783 uv_mode
7784 };
7785 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
7786 if smooth_neighbor {
7787 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
7788 }
7789 let smooth_neighbor_uv =
7790 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
7791 if std::env::var_os("EC_AV1_TRACE").is_some() {
7792 eprintln!(
7793 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
7794 angle_delta_uv={angle_delta_uv}"
7795 );
7796 }
7797 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
7798 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
7799 // block, skipped or not. `logical_tx` is what the loop filter's edge
7800 // lookup and the next block's own `tx_size_context` want (the *nominal*
7801 // transform size -- 64 even for the 64x64 corner-scanned case, spec
7802 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
7803 // which only differs from it at that one corner case.
7804 let (logical_tx, coeff_tx_side) = if tx_select {
7805 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
7806 (resolved, if resolved == 64 { 32 } else { resolved })
7807 } else {
7808 (side, luma_tx)
7809 };
7810 if tx_select && logical_tx < side && uv_mode != DC_PRED {
7811 SQ_CHROMA_TX_HITS.with(|c| c.set(c.get() + 1));
7812 }
7813 let luma_set = if tx_select {
7814 txbset_for(logical_tx, reduced_tx_set)
7815 } else {
7816 luma_set
7817 };
7818 let luma_set = if intrabc_dv.is_some() {
7819 txbset_for_inter(logical_tx, reduced_tx_set)
7820 } else {
7821 luma_set
7822 };
7823 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
7824 let reach = Reach::of(side, px, py, y.width, y.height);
7825 let (cpx, cpy) = (px / 2, py / 2);
7826 let chroma_side = side / 2;
7827 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
7828 // frame's own pre-loop-filter reconstruction (all loop filters are off
7829 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
7830 // block vector, with the BILINEAR kernel libaom forces for intrabc --
7831 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
7832 // odd, which is exactly what the bilinear taps then interpolate.
7833 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
7834 let mut yb = vec![0u16; side * side];
7835 mc::predict_with_filter(
7836 &y.data, y.width, y.true_width, y.true_height,
7837 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
7838 side, side, mc::InterpFilterKind::Bilinear, &mut yb,
7839 );
7840 let mut ub = vec![0u16; chroma_side * chroma_side];
7841 mc::predict_with_filter(
7842 &u.data, u.width, u.true_width, u.true_height,
7843 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
7844 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
7845 );
7846 let mut vb = vec![0u16; chroma_side * chroma_side];
7847 mc::predict_with_filter(
7848 &v.data, v.width, v.true_width, v.true_height,
7849 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
7850 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
7851 );
7852 (yb, ub, vb)
7853 });
7854 if let Some((yb, _, _)) = &intrabc_bufs {
7855 set_palette_pred(yb.clone());
7856 }
7857 // A palette-Y block's own prediction is the reconstructed colour-index
7858 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
7859 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
7860 // parameter through this function's dozen `y.reconstruct`/`read_plane`
7861 // sites. A split luma transform (`tx_select && logical_tx != side`)
7862 // would need the map sliced per-TU -- untested against a real
7863 // `--enable-palette=1` stream this round, so refuse by name rather than
7864 // guess at the slicing (charter's own named-acceptable fallback).
7865 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
7866 py.map
7867 .iter()
7868 .map(|&idx| py.colors[idx as usize])
7869 .collect()
7870 });
7871 // With one luma transform unit the whole `side`x`side` map is the
7872 // prediction; with several (`logical_tx != side`) each unit takes its own
7873 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
7874 // below (lane-palette2 r7) -- setting the full-block buffer here would be
7875 // taken by the FIRST unit and indexed at the wrong stride.
7876 if let Some(buf) = &palette_y_buf
7877 && logical_tx == side
7878 {
7879 set_palette_pred(buf.clone());
7880 }
7881 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
7882 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
7883 // plane's own `reconstruct`/`read_plane` call below (never both planes at
7884 // once), since Y's own set-then-take already emptied the slot by the time
7885 // either of these run.
7886 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
7887 (
7888 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
7889 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
7890 )
7891 });
7892 // The chroma half of the intrabc prediction rides the same per-plane
7893 // override slot the UV-palette buffers do (set fresh before each plane's
7894 // own `reconstruct`/`read_plane` call below).
7895 let palette_uv_bufs = match &intrabc_bufs {
7896 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
7897 None => palette_uv_bufs,
7898 };
7899 if skip {
7900 // A skipped block codes no residual syntax at all (spec 5.11.34):
7901 // straight prediction, on every plane.
7902 y.reconstruct(
7903 px,
7904 py,
7905 side,
7906 mode,
7907 angle_delta_y,
7908 reach,
7909 &vec![0i32; side * side],
7910 None,
7911 filter_intra,
7912 smooth_neighbor,
7913 );
7914 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7915 if let Some((ub, _)) = &palette_uv_bufs {
7916 set_palette_pred(ub.clone());
7917 }
7918 u.reconstruct(
7919 cpx,
7920 cpy,
7921 chroma_side,
7922 uv_predict_mode,
7923 angle_delta_uv,
7924 reach,
7925 &vec![0i32; chroma_side * chroma_side],
7926 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7927 None,
7928 smooth_neighbor_uv,
7929 );
7930 if let Some((_, vb)) = &palette_uv_bufs {
7931 set_palette_pred(vb.clone());
7932 }
7933 v.reconstruct(
7934 cpx,
7935 cpy,
7936 chroma_side,
7937 uv_predict_mode,
7938 angle_delta_uv,
7939 reach,
7940 &vec![0i32; chroma_side * chroma_side],
7941 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7942 None,
7943 smooth_neighbor_uv,
7944 );
7945 let luma_grid = vec![0i32; side * side];
7946 let u_grid = vec![0i32; chroma_side * chroma_side];
7947 let v_grid = vec![0i32; chroma_side * chroma_side];
7948 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
7949 } else if !tx_select || logical_tx == side {
7950 // A single luma transform unit -- the old path, unchanged (including
7951 // the 64x64 corner case, `logical_tx == side == 64` with
7952 // `coeff_tx_side == 32`).
7953 let around = neighbours.around(at, side);
7954 let luma_grid = read_plane(
7955 dec,
7956 cdfs,
7957 luma_set,
7958 luma_scan,
7959 0,
7960 around[0],
7961 mode,
7962 mode,
7963 angle_delta_y,
7964 reach,
7965 y,
7966 px,
7967 py,
7968 side,
7969 coeff_tx_side,
7970 base_q_idx,
7971 None,
7972 filter_intra,
7973 None,
7974 smooth_neighbor,
7975 )?;
7976 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7977 if let Some((ub, _)) = &palette_uv_bufs {
7978 set_palette_pred(ub.clone());
7979 }
7980 let u_grid = read_plane(
7981 dec,
7982 cdfs,
7983 chroma_set,
7984 scans.1,
7985 1,
7986 around[1],
7987 mode,
7988 uv_predict_mode,
7989 angle_delta_uv,
7990 reach,
7991 u,
7992 cpx,
7993 cpy,
7994 chroma_side,
7995 chroma_tx,
7996 base_q_idx,
7997 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7998 None,
7999 None,
8000 smooth_neighbor_uv,
8001 )?;
8002 if std::env::var_os("EC_AV1_TRACE").is_some() {
8003 eprintln!(
8004 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
8005 &u.data[cpy * u.width + cpx..][..chroma_side]
8006 );
8007 }
8008 if let Some((_, vb)) = &palette_uv_bufs {
8009 set_palette_pred(vb.clone());
8010 }
8011 let v_grid = read_plane(
8012 dec,
8013 cdfs,
8014 chroma_set,
8015 scans.1,
8016 2,
8017 around[2],
8018 mode,
8019 uv_predict_mode,
8020 angle_delta_uv,
8021 reach,
8022 v,
8023 cpx,
8024 cpy,
8025 chroma_side,
8026 chroma_tx,
8027 base_q_idx,
8028 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8029 None,
8030 None,
8031 smooth_neighbor_uv,
8032 )?;
8033 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
8034 } else {
8035 // Several luma transform units, raster order (spec
8036 // `transform_block`'s loop): the block's resolved transform is
8037 // genuinely smaller than its own side, so each tile of it predicts
8038 // and codes independently, its own context read fresh off whatever
8039 // the earlier tiles in this same block already wrote -- the same
8040 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
8041 let n_axis = side / logical_tx;
8042 for tu_row in 0..n_axis {
8043 for tu_col in 0..n_axis {
8044 let tu_mi = (
8045 mi_r + tu_row * (logical_tx / MI),
8046 mi_c + tu_col * (logical_tx / MI),
8047 );
8048 let tu_px = px + tu_col * logical_tx;
8049 let tu_py = py + tu_row * logical_tx;
8050 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
8051 // A transform unit inside a block is NOT a block at that
8052 // position (lane-palette2 r12): `Reach::of` granted the
8053 // top-right 8x8 unit of a 16x16 D203 block bottom-left
8054 // pixels libaom refuses outright (`col_off > 0`), which is
8055 // the diagonal wedge seed 46 reconstructed wrong.
8056 let tu_reach = tu_reach(
8057 side,
8058 side,
8059 tu_col * logical_tx,
8060 tu_row * logical_tx,
8061 logical_tx,
8062 reach,
8063 px,
8064 py,
8065 y.width,
8066 y.height,
8067 );
8068 // This transform unit's own bsize (`logical_tx`) is smaller
8069 // than the block it sits in (`side`), so `txb_skip_ctx` is
8070 // the neighbour-magnitude table, not the lone-TU 0 (spec
8071 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
8072 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
8073 if let Some(buf) = &palette_y_buf {
8074 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8075 let mut window = vec![0u16; logical_tx * logical_tx];
8076 for row in 0..logical_tx {
8077 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
8078 window[row * logical_tx..][..logical_tx]
8079 .copy_from_slice(&buf[src..][..logical_tx]);
8080 }
8081 set_palette_pred(window);
8082 }
8083 let tu_grid = read_plane(
8084 dec,
8085 cdfs,
8086 luma_set,
8087 luma_scan,
8088 0,
8089 tu_around,
8090 mode,
8091 mode,
8092 angle_delta_y,
8093 tu_reach,
8094 y,
8095 tu_px,
8096 tu_py,
8097 logical_tx,
8098 logical_tx,
8099 base_q_idx,
8100 None,
8101 filter_intra,
8102 Some(tu_skip_ctx),
8103 smooth_neighbor,
8104 )?;
8105 if std::env::var_os("EC_AV1_TRACE").is_some() {
8106 eprintln!(
8107 "TRACE tu_bitpos mi=({},{}) tell={}",
8108 tu_mi.0,
8109 tu_mi.1,
8110 dec.debug_bitpos()
8111 );
8112 }
8113 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
8114 }
8115 }
8116 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8117 let chroma_around = neighbours.around(at, side);
8118 if let Some((ub, _)) = &palette_uv_bufs {
8119 set_palette_pred(ub.clone());
8120 }
8121 let u_grid = read_plane(
8122 dec,
8123 cdfs,
8124 chroma_set,
8125 scans.1,
8126 1,
8127 chroma_around[1],
8128 mode,
8129 uv_predict_mode,
8130 angle_delta_uv,
8131 reach,
8132 u,
8133 cpx,
8134 cpy,
8135 chroma_side,
8136 chroma_tx,
8137 base_q_idx,
8138 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8139 None,
8140 None,
8141 smooth_neighbor_uv,
8142 )?;
8143 if let Some((_, vb)) = &palette_uv_bufs {
8144 set_palette_pred(vb.clone());
8145 }
8146 let v_grid = read_plane(
8147 dec,
8148 cdfs,
8149 chroma_set,
8150 scans.1,
8151 2,
8152 chroma_around[2],
8153 mode,
8154 uv_predict_mode,
8155 angle_delta_uv,
8156 reach,
8157 v,
8158 cpx,
8159 cpy,
8160 chroma_side,
8161 chroma_tx,
8162 base_q_idx,
8163 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8164 None,
8165 None,
8166 smooth_neighbor_uv,
8167 )?;
8168 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]);
8169 }
8170 // Unconditional, `size == 0` for a non-palette block: clears any stale
8171 // neighbour palette state the same way [`Neighbours::record`] always
8172 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
8173 // (the split-luma-TU branch above always refuses before reaching here
8174 // when `palette_y` is `Some`, so it is never live for that branch).
8175 let (py_size, py_colors) = palette_y
8176 .as_ref()
8177 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8178 neighbours.record_palette_y(at, side, py_size, py_colors);
8179 let (puv_size, puv_colors) = palette_uv
8180 .as_ref()
8181 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8182 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
8183 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
8184 neighbours.fill_lf_grid(
8185 (r * (SUB / MI), c * (SUB / MI)),
8186 side / MI,
8187 logical_tx as u8,
8188 0,
8189 );
8190 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
8191 Ok(())
8192}
8193
8194/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
8195/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
8196/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
8197/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
8198/// just-decoded mode, not the enclosing slot's stale one, is the true
8199/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
8200/// units, which is what its coefficient context (finer than [`SUB`]) is read
8201/// at. Returns the mode this leaf decoded, for the caller's own
8202/// `prev_leaf`/final mode-writeback bookkeeping.
8203#[allow(clippy::too_many_arguments)]
8204/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
8205/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
8206/// `above_mode[col]`, and its true above neighbour is the mi directly above
8207/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
8208/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
8209/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
8210/// (bottom-right) into both, as this path did, is right only when all four
8211/// leaves happen to share a mode. `done` may be short at the true frame edge
8212/// (the straddle caller filters positions off the frame), so each side falls
8213/// back to the last leaf actually decoded.
8214fn write_back_split_modes(
8215 neighbours: &mut Neighbours,
8216 done: &[((usize, usize), usize)],
8217 parent_mi: (usize, usize),
8218 slot: (usize, usize),
8219) {
8220 let (sr, sc) = slot;
8221 let Some(&(_, last)) = done.last() else {
8222 return;
8223 };
8224 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
8225 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
8226 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
8227}
8228
8229fn decode_leaf8(
8230 dec: &mut SymbolDecoder,
8231 cdfs: &mut Cdfs,
8232 neighbours: &mut Neighbours,
8233 outer_at: (usize, usize),
8234 leaf_mi: (usize, usize),
8235 scans: (&[u16], &[u16]),
8236 prev_leaf: Option<((usize, usize), usize)>,
8237 y: &mut PlaneBuf,
8238 u: &mut PlaneBuf,
8239 v: &mut PlaneBuf,
8240 base_q_idx: u8,
8241 enable_filter_intra: bool,
8242 allow_screen_content_tools: bool,
8243 allow_intrabc: bool,
8244 tx_select: bool,
8245 reduced_tx_set: bool,
8246) -> Result<usize> {
8247 let (r, c) = outer_at;
8248 let mut above_mode = neighbours.above_mode[c];
8249 let mut left_mode = neighbours.left_mode[r];
8250 if let Some(((pr, pc), pmode)) = prev_leaf {
8251 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
8252 above_mode = pmode;
8253 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
8254 left_mode = pmode;
8255 }
8256 }
8257 // The mi-exact neighbour wins over both the coarse 16x16 slot and
8258 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
8259 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
8260 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
8261 if let Some(m) = neighbours.mode_above_mi(leaf_mi.0, leaf_mi.1) {
8262 above_mode = m;
8263 }
8264 if let Some(m) = neighbours.mode_left_mi(leaf_mi.0, leaf_mi.1) {
8265 left_mode = m;
8266 }
8267 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
8268 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
8269 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
8270 // this leaf's `smooth_neighbor` is built from -- passing `false` here
8271 // filtered a directional chroma block's edge at the wrong strength
8272 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
8273 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
8274 // with the coarse [`SUB`] slot as the fallback when no block recorded
8275 // that exact mi cell.
8276 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
8277 if smooth_neighbor {
8278 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8279 }
8280 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
8281 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
8282 // `decode_block` caller at 16x16 and up.
8283 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y, _palette_uv) =
8284 read_intra_mode(
8285 dec,
8286 cdfs,
8287 above_mode,
8288 left_mode,
8289 true,
8290 8,
8291 enable_filter_intra,
8292 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
8293 allow_screen_content_tools,
8294 allow_intrabc,
8295 None,
8296 &[],
8297 leaf_mi.0,
8298 leaf_mi.1,
8299 )?;
8300 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8301 DC_PRED
8302 } else {
8303 uv_mode
8304 };
8305 neighbours.above_uv_mode[c] = uv_predict_mode;
8306 neighbours.left_uv_mode[r] = uv_predict_mode;
8307 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
8308 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
8309 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
8310 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
8311 // transform units, same raster-order per-TU pattern `decode_block`'s
8312 // multi-TU branch runs).
8313 let resolved = if tx_select {
8314 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
8315 } else {
8316 8
8317 };
8318 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8319 let reach = Reach::of(8, px, py, y.width, y.height);
8320 let (cpx, cpy) = (px / 2, py / 2);
8321 let (luma_grid, u_grid, v_grid);
8322 if skip {
8323 y.reconstruct(
8324 px,
8325 py,
8326 8,
8327 mode,
8328 angle_delta_y,
8329 reach,
8330 &vec![0i32; 64],
8331 None,
8332 filter_intra,
8333 smooth_neighbor,
8334 );
8335 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8336 u.reconstruct(
8337 cpx,
8338 cpy,
8339 4,
8340 uv_predict_mode,
8341 angle_delta_uv,
8342 reach,
8343 &vec![0i32; 16],
8344 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8345 None,
8346 smooth_neighbor_uv,
8347 );
8348 v.reconstruct(
8349 cpx,
8350 cpy,
8351 4,
8352 uv_predict_mode,
8353 angle_delta_uv,
8354 reach,
8355 &vec![0i32; 16],
8356 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8357 None,
8358 smooth_neighbor_uv,
8359 );
8360 luma_grid = vec![0i32; 64];
8361 u_grid = vec![0i32; 16];
8362 v_grid = vec![0i32; 16];
8363 } else if resolved != 4 {
8364 let around = neighbours.around_mi(leaf_mi, 8);
8365 luma_grid = read_plane(
8366 dec,
8367 cdfs,
8368 if reduced_tx_set {
8369 TxbSet::Luma8
8370 } else {
8371 TxbSet::Luma8Set1
8372 },
8373 scans.0,
8374 0,
8375 around[0],
8376 mode,
8377 mode,
8378 angle_delta_y,
8379 reach,
8380 y,
8381 px,
8382 py,
8383 8,
8384 TX8,
8385 base_q_idx,
8386 None,
8387 filter_intra,
8388 None,
8389 smooth_neighbor,
8390 )?;
8391 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8392 u_grid = read_plane(
8393 dec,
8394 cdfs,
8395 TxbSet::Chroma4,
8396 scans.1,
8397 1,
8398 around[1],
8399 mode,
8400 uv_predict_mode,
8401 angle_delta_uv,
8402 reach,
8403 u,
8404 cpx,
8405 cpy,
8406 4,
8407 TX4,
8408 base_q_idx,
8409 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8410 None,
8411 None,
8412 smooth_neighbor_uv,
8413 )?;
8414 v_grid = read_plane(
8415 dec,
8416 cdfs,
8417 TxbSet::Chroma4,
8418 scans.1,
8419 2,
8420 around[2],
8421 mode,
8422 uv_predict_mode,
8423 angle_delta_uv,
8424 reach,
8425 v,
8426 cpx,
8427 cpy,
8428 4,
8429 TX4,
8430 base_q_idx,
8431 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8432 None,
8433 None,
8434 smooth_neighbor_uv,
8435 )?;
8436 } else {
8437 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
8438 // grid of 4x4 transform units, each predicted from the leaf's own
8439 // 8x8 `mode` and reading its own fresh context off the earlier
8440 // units in this same leaf (the same per-TU pattern `decode_block`'s
8441 // multi-TU branch runs at bigger blocks).
8442 luma_grid = vec![0i32; 64];
8443 for tu_row in 0..2 {
8444 for tu_col in 0..2 {
8445 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
8446 let tu_px = px + tu_col * 4;
8447 let tu_py = py + tu_row * 4;
8448 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
8449 if crate::encode::Reach::in_vert_ab() {
8450 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));
8451 }
8452 let tu_reach = tu_reach(
8453 8,
8454 8,
8455 tu_col * 4,
8456 tu_row * 4,
8457 4,
8458 reach,
8459 px,
8460 py,
8461 y.width,
8462 y.height,
8463 );
8464 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
8465 let tu_grid = read_plane(
8466 dec,
8467 cdfs,
8468 if reduced_tx_set {
8469 TxbSet::Luma4
8470 } else {
8471 TxbSet::Luma4Set1
8472 },
8473 scans.1,
8474 0,
8475 tu_around,
8476 mode,
8477 mode,
8478 angle_delta_y,
8479 tu_reach,
8480 y,
8481 tu_px,
8482 tu_py,
8483 4,
8484 4,
8485 base_q_idx,
8486 None,
8487 filter_intra,
8488 Some(tu_skip_ctx),
8489 smooth_neighbor,
8490 )?;
8491 if std::env::var_os("EC_AV1_TRACE").is_some() {
8492 eprintln!(
8493 "TRACE tu_bitpos mi=({},{}) tell={}",
8494 tu_mi.0,
8495 tu_mi.1,
8496 dec.debug_bitpos()
8497 );
8498 }
8499 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
8500 }
8501 }
8502 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8503 let chroma_around = neighbours.around_mi(leaf_mi, 8);
8504 u_grid = read_plane(
8505 dec,
8506 cdfs,
8507 TxbSet::Chroma4,
8508 scans.1,
8509 1,
8510 chroma_around[1],
8511 mode,
8512 uv_predict_mode,
8513 angle_delta_uv,
8514 reach,
8515 u,
8516 cpx,
8517 cpy,
8518 4,
8519 TX4,
8520 base_q_idx,
8521 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8522 None,
8523 None,
8524 smooth_neighbor_uv,
8525 )?;
8526 v_grid = read_plane(
8527 dec,
8528 cdfs,
8529 TxbSet::Chroma4,
8530 scans.1,
8531 2,
8532 chroma_around[2],
8533 mode,
8534 uv_predict_mode,
8535 angle_delta_uv,
8536 reach,
8537 v,
8538 cpx,
8539 cpy,
8540 4,
8541 TX4,
8542 base_q_idx,
8543 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8544 None,
8545 None,
8546 smooth_neighbor_uv,
8547 )?;
8548 // `record_split_luma` expects a `record`-style `(r, c)` position in
8549 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
8550 // already in mi units, so calling it here double-scaled the
8551 // position. Plane 0 is already correct per-TU from the
8552 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
8553 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
8554 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
8555 // leaf's own 8x8 side over `MI`).
8556 let side_mi = 2;
8557 for cell in 0..side_mi {
8558 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
8559 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
8560 }
8561 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8562 let bound_h = round_up_even(neighbours.mi_rows);
8563 let bound_w = round_up_even(neighbours.mi_cols);
8564 let u_state = neighbour_state(&u_grid);
8565 let v_state = neighbour_state(&v_grid);
8566 for cell in 0..side_mi {
8567 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
8568 neighbours.left[leaf_mi.0 + cell][1] = u_state;
8569 neighbours.left[leaf_mi.0 + cell][2] = v_state;
8570 }
8571 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
8572 neighbours.above[leaf_mi.1 + cell][1] = u_state;
8573 neighbours.above[leaf_mi.1 + cell][2] = v_state;
8574 }
8575 }
8576 // Non-palette 8x8 leaf (this path never reads a palette): clear the
8577 // above/left palette state over its own cell so the next block's ctx and
8578 // colour cache do not read a previous block's palette (lane-palette2 r8).
8579 {
8580 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
8581 neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
8582 neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
8583 }
8584 neighbours.fill_skip_grid(leaf_mi, 2, skip);
8585 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
8586 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
8587 return Ok(mode);
8588 }
8589 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
8590 // Non-palette 8x8 leaf (this path never reads a palette): clear the
8591 // above/left palette state over its own cell so the next block's ctx and
8592 // colour cache do not read a previous block's palette (lane-palette2 r8).
8593 {
8594 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
8595 neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
8596 neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
8597 }
8598 neighbours.fill_skip_grid(leaf_mi, 2, skip);
8599 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
8600 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
8601 Ok(mode)
8602}
8603
8604/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
8605/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
8606/// bottom, where no partition symbol is read at all -- `decode_block` runs
8607/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
8608/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
8609/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
8610/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
8611/// of the 2x2 4x4 group carries chroma syntax at all.
8612#[allow(clippy::too_many_arguments)]
8613fn read_intra_mode_sub8(
8614 dec: &mut SymbolDecoder,
8615 cdfs: &mut Cdfs,
8616 above_mode: usize,
8617 left_mode: usize,
8618 has_chroma: bool,
8619 enable_filter_intra: bool,
8620 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
8621 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
8622 // from the wrong row is the same VALUE with a different interval, so it
8623 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
8624 fi_class: usize,
8625 skip_ctx: usize,
8626 allow_intrabc: bool,
8627 mi_r: usize,
8628 mi_c: usize,
8629) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
8630 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
8631 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
8632 if trace {
8633 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
8634 }
8635 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
8636 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
8637 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
8638 if allow_intrabc {
8639 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
8640 if use_intrabc {
8641 return Err(unsupported(
8642 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
8643 ));
8644 }
8645 }
8646 let above_ctx = INTRA_MODE_CTX[above_mode];
8647 let left_ctx = INTRA_MODE_CTX[left_mode];
8648 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
8649 if trace {
8650 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
8651 }
8652 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
8653 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
8654 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
8655 // symbol. Reading one consumed a symbol the encoder never wrote and
8656 // desynced the tile at the very next element.
8657 let angle_delta_y = 0;
8658 let chroma = if has_chroma {
8659 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
8660 if trace {
8661 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
8662 }
8663 if (9..=12).contains(&uv_mode) {
8664 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
8665 }
8666 let alpha = if uv_mode == UV_CFL_PRED {
8667 Some(read_cfl_alphas(dec, cdfs))
8668 } else {
8669 None
8670 };
8671 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8672 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
8673 }
8674 // See the luma comment above: no angle delta below 8x8.
8675 let angle_delta_uv = 0;
8676 Some((uv_mode, angle_delta_uv, alpha))
8677 } else {
8678 None
8679 };
8680 let mut filter_intra = None;
8681 if mode == DC_PRED && enable_filter_intra {
8682 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
8683 if trace {
8684 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
8685 }
8686 if use_filter_intra {
8687 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
8688 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
8689 filter_intra = Some(fi_mode);
8690 }
8691 }
8692 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
8693}
8694
8695/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
8696/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
8697/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
8698/// bookkeeping needs no change. Each leaf reads its own luma mode info,
8699/// neighboured off the *previously decoded leaf in this same group* on
8700/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
8701/// pattern, one level deeper); chroma is read and reconstructed exactly
8702/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
8703/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
8704/// derivation.
8705#[allow(clippy::too_many_arguments)]
8706fn decode_leaf_split4(
8707 dec: &mut SymbolDecoder,
8708 cdfs: &mut Cdfs,
8709 neighbours: &mut Neighbours,
8710 outer_at: (usize, usize),
8711 leaf_mi: (usize, usize),
8712 scan4: &[u16],
8713 prev_leaf: Option<((usize, usize), usize)>,
8714 y: &mut PlaneBuf,
8715 u: &mut PlaneBuf,
8716 v: &mut PlaneBuf,
8717 base_q_idx: u8,
8718 enable_filter_intra: bool,
8719 allow_intrabc: bool,
8720 reduced_tx_set: bool,
8721 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
8722 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
8723 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1)).
8724) -> Result<(usize, usize)> {
8725 SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1));
8726 let (r, c) = outer_at;
8727 let mut above_mode = neighbours.above_mode[c];
8728 let mut left_mode = neighbours.left_mode[r];
8729 if let Some(((pr, pc), pmode)) = prev_leaf {
8730 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
8731 above_mode = pmode;
8732 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
8733 left_mode = pmode;
8734 }
8735 }
8736 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
8737 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
8738 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
8739 let mut leaf_modes = [0usize; 4];
8740 let mut leaf_skips = [false; 4];
8741 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
8742 for i in 0..4usize {
8743 let (dr, dc) = (i / 2, i % 2);
8744 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
8745 // Neighbour modes at real mi granularity: inside the group the
8746 // sibling leaf, outside it the split-leaf map when the adjacent mi
8747 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
8748 // `sub8_mode_col`'s doc).
8749 let leaf_above = if dr == 0 {
8750 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
8751 } else {
8752 leaf_modes[i - 2]
8753 };
8754 let leaf_left = if dc == 0 {
8755 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
8756 } else {
8757 leaf_modes[i - 1]
8758 };
8759 let has_chroma = i == 3;
8760 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
8761 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
8762 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
8763 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
8764 skip_ctx, allow_intrabc, lmi.0, lmi.1,
8765 )?;
8766 leaf_modes[i] = mode;
8767 leaf_skips[i] = skip;
8768 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
8769 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
8770 if smooth_neighbor {
8771 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8772 }
8773 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
8774 let reach = Reach::of(4, px, py, y.width, y.height);
8775 if skip {
8776 y.reconstruct(px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor);
8777 neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]);
8778 } else {
8779 let tu_around = neighbours.around_mi(lmi, 4)[0];
8780 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
8781 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
8782 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
8783 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
8784 // off the wrong CDF on the very first leaf and desynced the tile.
8785 let tu_grid = read_plane(
8786 dec,
8787 cdfs,
8788 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
8789 scan4,
8790 0,
8791 tu_around,
8792 mode,
8793 mode,
8794 angle_delta_y,
8795 reach,
8796 y,
8797 px,
8798 py,
8799 4,
8800 4,
8801 base_q_idx,
8802 None,
8803 filter_intra,
8804 None,
8805 smooth_neighbor,
8806 )?;
8807 neighbours.record_mi_luma(lmi, 4, &tu_grid);
8808 }
8809 neighbours.fill_skip_grid(lmi, 1, skip);
8810 neighbours.fill_lf_grid(lmi, 1, 4, 0);
8811 if has_chroma {
8812 last_uv = chroma;
8813 }
8814 }
8815 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8816 let (cpx, cpy) = (gpx / 2, gpy / 2);
8817 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
8818 let (uv_mode, angle_delta_uv, alpha) =
8819 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
8820 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
8821 neighbours.above_uv_mode[c] = uv_predict_mode;
8822 neighbours.left_uv_mode[r] = uv_predict_mode;
8823 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
8824 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[3] {
8825 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
8826 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
8827 (vec![0i32; 16], vec![0i32; 16])
8828 } else {
8829 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
8830 let chroma_around = neighbours.around_mi(leaf_mi, 8);
8831 let ug = read_plane(
8832 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
8833 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
8834 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
8835 )?;
8836 let vg = read_plane(
8837 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
8838 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
8839 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
8840 )?;
8841 (ug, vg)
8842 };
8843 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
8844 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
8845 // rescaling is wrong for an already-mi-unit position, so this inlines
8846 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
8847 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
8848 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
8849 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
8850 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
8851 // bottom). libaom's `update_ext_partition_context` writes
8852 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
8853 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
8854 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
8855 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
8856 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
8857 // round's bug) makes the very next sibling 8x8's `partition_w8` read
8858 // with the wrong context and desync immediately.
8859 let side_mi = 2;
8860 for cell in 0..side_mi {
8861 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
8862 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
8863 }
8864 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8865 let bound_h = round_up_even(neighbours.mi_rows);
8866 let bound_w = round_up_even(neighbours.mi_cols);
8867 let u_state = neighbour_state(&u_grid);
8868 let v_state = neighbour_state(&v_grid);
8869 for cell in 0..side_mi {
8870 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
8871 neighbours.left[leaf_mi.0 + cell][1] = u_state;
8872 neighbours.left[leaf_mi.0 + cell][2] = v_state;
8873 }
8874 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
8875 neighbours.above[leaf_mi.1 + cell][1] = u_state;
8876 neighbours.above[leaf_mi.1 + cell][2] = v_state;
8877 }
8878 }
8879 Ok((leaf_modes[2], leaf_modes[1]))
8880}
8881
8882/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
8883/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
8884/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
8885/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
8886/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
8887/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
8888/// every sub-block one mi wide or high but the last) -- differing only where
8889/// the shape does:
8890///
8891/// * the transform is a true `TX_4X8`/`TX_8X4`
8892/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
8893/// `av1_inv_txfm_shift_ls` row already cover this size pair);
8894/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
8895/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
8896/// row -- see that variant's doc comment;
8897/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
8898/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
8899/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
8900/// ([`Reach::of_rect`]);
8901/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
8902/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
8903/// `BLOCK_4X4` split writes.
8904///
8905/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
8906/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
8907/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
8908/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
8909/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
8910/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
8911#[allow(clippy::too_many_arguments)]
8912fn decode_leaf_rect8(
8913 dec: &mut SymbolDecoder,
8914 cdfs: &mut Cdfs,
8915 neighbours: &mut Neighbours,
8916 outer_at: (usize, usize),
8917 leaf_mi: (usize, usize),
8918 vert: bool,
8919 scan4: &[u16],
8920 y: &mut PlaneBuf,
8921 u: &mut PlaneBuf,
8922 v: &mut PlaneBuf,
8923 base_q_idx: u8,
8924 enable_filter_intra: bool,
8925 allow_intrabc: bool,
8926 tx_select: bool,
8927 reduced_tx_set: bool,
8928) -> Result<(usize, usize)> {
8929 let (r, c) = outer_at;
8930 let above_mode = neighbours.above_mode[c];
8931 let left_mode = neighbours.left_mode[r];
8932 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
8933 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
8934 let (w_mi, h_mi) = (bw / MI, bh / MI);
8935 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
8936 let mut leaf_modes = [0usize; 2];
8937 let mut leaf_skips = [false; 2];
8938 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
8939 for i in 0..2usize {
8940 let lmi = if vert {
8941 (leaf_mi.0, leaf_mi.1 + i)
8942 } else {
8943 (leaf_mi.0 + i, leaf_mi.1)
8944 };
8945 // Inside the pair the sibling is the neighbour on the split axis;
8946 // outside it the mi-granular map, else the coarse 16x16 slot.
8947 let leaf_above = if !vert && i == 1 {
8948 leaf_modes[0]
8949 } else {
8950 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
8951 };
8952 let leaf_left = if vert && i == 1 {
8953 leaf_modes[0]
8954 } else {
8955 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
8956 };
8957 let has_chroma = i == 1;
8958 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
8959 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
8960 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
8961 filter_intra_size_class_rect(bw, bh)
8962 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
8963 skip_ctx, allow_intrabc, lmi.0, lmi.1,
8964 )?;
8965 if filter_intra.is_some() {
8966 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
8967 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
8968 // same `reconstruct_rect`/`reconstruct` calls below -- and under
8969 // a split transform, per 4x4 unit with that unit's own edge,
8970 // which is exactly what the depth-1 loop already does.
8971 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
8972 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.set(c.get() + 1));
8973 }
8974 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
8975 // leaf too, and is read for every intra block, skipped or not. Its
8976 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
8977 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
8978 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
8979 // `tx_size_cat2` the 32x16 strips read -- with the rect context
8980 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
8981 // Missing this read consumed one symbol fewer than the encoder wrote
8982 // and desynced the tile at the very first rect leaf (class
8983 // `symbol-consumption-gap`).
8984 let depth = if tx_select {
8985 let ctx = tx_size_context_rect(neighbours, lmi, bw, bh);
8986 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
8987 } else {
8988 0
8989 };
8990 if depth != 0 {
8991 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8992 RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8993 }
8994 leaf_modes[i] = mode;
8995 leaf_skips[i] = skip;
8996 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
8997 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
8998 if smooth_neighbor {
8999 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
9000 }
9001 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
9002 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9003 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
9004 // two 4x4 transform units along its long axis, each predicted from
9005 // the previous unit's reconstruction and reading its own `txb_skip`
9006 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
9007 // four. The per-TU path writes its own neighbour state, so the
9008 // block-level write below is skipped for it.
9009 let split = depth != 0;
9010 if split {
9011 let mut done = 0usize;
9012 for tu in 0..2usize {
9013 let tu_mi = if vert {
9014 (lmi.0 + tu, lmi.1)
9015 } else {
9016 (lmi.0, lmi.1 + tu)
9017 };
9018 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
9019 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
9020 // Same per-TU rule as every other split-transform site
9021 // (lane-palette2 r12): a transform unit inside a block is not
9022 // a block at that position, so its reach comes from the
9023 // block's own row, offset by the unit's position.
9024 let tu_reach = tu_reach(
9025 bw,
9026 bh,
9027 tu_px - px,
9028 tu_py - py,
9029 4,
9030 reach,
9031 px,
9032 py,
9033 y.width,
9034 y.height,
9035 );
9036 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
9037 if skip {
9038 // A skipped leaf still predicts per transform unit: the
9039 // second 4x4 takes its above/left edge from the first
9040 // one's reconstruction, which is NOT what a single 4x8
9041 // prediction of the same mode produces.
9042 let zeros = vec![0i32; 16];
9043 y.reconstruct(
9044 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
9045 filter_intra, smooth_neighbor,
9046 );
9047 neighbours.record_mi_luma(tu_mi, 4, &zeros);
9048 continue;
9049 }
9050 let tu_grid = read_plane(
9051 dec,
9052 cdfs,
9053 if reduced_tx_set {
9054 TxbSet::Luma4
9055 } else {
9056 TxbSet::Luma4Set1
9057 },
9058 scan4,
9059 0,
9060 tu_around,
9061 mode,
9062 mode,
9063 angle_delta_y,
9064 tu_reach,
9065 y,
9066 tu_px,
9067 tu_py,
9068 4,
9069 TX4,
9070 base_q_idx,
9071 None,
9072 filter_intra,
9073 Some(tu_skip_ctx),
9074 smooth_neighbor,
9075 )?;
9076 if tu_grid.iter().any(|&l| l != 0) {
9077 done += 1;
9078 }
9079 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
9080 }
9081 if done > 0 {
9082 if vert {
9083 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
9084 } else {
9085 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
9086 }
9087 }
9088 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
9089 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0);
9090 if has_chroma {
9091 last_uv = chroma;
9092 }
9093 continue;
9094 }
9095 let grid = if skip {
9096 let zeros = vec![0i32; bw * bh];
9097 y.reconstruct_rect(
9098 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
9099 smooth_neighbor,
9100 );
9101 zeros
9102 } else {
9103 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
9104 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
9105 // at 0 -- see `decode_leaf_split4`'s own note.
9106 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
9107 let set = if reduced_tx_set {
9108 TxbSet::LumaRect4x8
9109 } else {
9110 TxbSet::LumaRect4x8Set1
9111 };
9112 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
9113 let (levels, tx_type) = read_coeffs_rect(
9114 dec,
9115 &mut coding,
9116 scan,
9117 bw,
9118 bh,
9119 0,
9120 dc_sign_ctx(around.2),
9121 TxType::DctDct,
9122 )?;
9123 if levels.iter().any(|&l| l != 0) {
9124 if vert {
9125 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
9126 } else {
9127 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
9128 }
9129 }
9130 let residual = dequant_and_inverse_typed_wh(
9131 &levels,
9132 bw,
9133 bh,
9134 crate::decode::bit_depth(),
9135 CURRENT_Q_IDX.with(|q| q.get()),
9136 plane_q_delta(0).0,
9137 plane_q_delta(0).1,
9138 tx_type,
9139 );
9140 y.reconstruct_rect(
9141 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
9142 smooth_neighbor,
9143 );
9144 levels
9145 };
9146 // Plane 0's per-TU coefficient context over this leaf's own mi span
9147 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
9148 // for the whole 8x8 group below).
9149 let state = neighbour_state(&grid);
9150 for cell in 0..h_mi {
9151 if lmi.0 + cell < neighbours.mi_rows {
9152 neighbours.left[lmi.0 + cell][0] = state;
9153 }
9154 }
9155 for cell in 0..w_mi {
9156 if lmi.1 + cell < neighbours.mi_cols {
9157 neighbours.above[lmi.1 + cell][0] = state;
9158 }
9159 }
9160 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
9161 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
9162 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0);
9163 if has_chroma {
9164 last_uv = chroma;
9165 }
9166 }
9167 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
9168 let (cpx, cpy) = (gpx / 2, gpy / 2);
9169 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
9170 let (uv_mode, angle_delta_uv, alpha) =
9171 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
9172 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
9173 neighbours.above_uv_mode[c] = uv_predict_mode;
9174 neighbours.left_uv_mode[r] = uv_predict_mode;
9175 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
9176 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[1] {
9177 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
9178 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
9179 (vec![0i32; 16], vec![0i32; 16])
9180 } else {
9181 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
9182 let chroma_around = neighbours.around_mi(leaf_mi, 8);
9183 let ug = read_plane(
9184 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
9185 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
9186 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
9187 )?;
9188 let vg = read_plane(
9189 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
9190 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
9191 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
9192 )?;
9193 (ug, vg)
9194 };
9195 // `update_partition_context` at the 8x8 level writes
9196 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
9197 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
9198 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
9199 // `partition_ctx_mi` reads back off these side values.
9200 for cell in 0..2 {
9201 neighbours.above_side_mi[leaf_mi.1 + cell] = bw;
9202 neighbours.left_side_mi[leaf_mi.0 + cell] = bh;
9203 }
9204 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9205 let bound_h = round_up_even(neighbours.mi_rows);
9206 let bound_w = round_up_even(neighbours.mi_cols);
9207 let u_state = neighbour_state(&u_grid);
9208 let v_state = neighbour_state(&v_grid);
9209 for cell in 0..2usize {
9210 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
9211 neighbours.left[leaf_mi.0 + cell][1] = u_state;
9212 neighbours.left[leaf_mi.0 + cell][2] = v_state;
9213 }
9214 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
9215 neighbours.above[leaf_mi.1 + cell][1] = u_state;
9216 neighbours.above[leaf_mi.1 + cell][2] = v_state;
9217 }
9218 }
9219 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
9220 // bottom one (the second under HORZ, the left one under VERT), the one a
9221 // neighbour to the right sees is the top-right (the second under VERT).
9222 Ok(if vert {
9223 (leaf_modes[0], leaf_modes[1])
9224 } else {
9225 (leaf_modes[1], leaf_modes[0])
9226 })
9227}
9228
9229/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
9230/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
9231/// (mod 8) reuse the same table.
9232const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
9233 [(-1, 1), (-2, 2)],
9234 [(0, 1), (-1, 2)],
9235 [(0, 1), (0, 2)],
9236 [(0, 1), (1, 2)],
9237 [(1, 1), (2, 2)],
9238 [(1, 0), (2, 1)],
9239 [(1, 0), (2, 0)],
9240 [(1, 0), (2, -1)],
9241];
9242/// A neighbour tap outside the frame's true extent -- `constrain` reads this
9243/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
9244const CDEF_VERY_LARGE: i32 = 0x4000;
9245const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
9246const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
9247
9248fn cdef_msb(x: i32) -> i32 {
9249 31 - x.leading_zeros() as i32
9250}
9251
9252/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
9253/// centre sample a filter tap is allowed to contribute.
9254fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
9255 if threshold == 0 {
9256 return 0;
9257 }
9258 let shift = (damping - cdef_msb(threshold)).max(0);
9259 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
9260}
9261
9262/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
9263/// direction of an 8x8 luma window and the variance gap between it and its
9264/// orthogonal, `sample(row, col)` reading that window's own pixels.
9265fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
9266 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
9267 let mut partial = [[0i64; 15]; 8];
9268 for i in 0..8i64 {
9269 for j in 0..8i64 {
9270 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
9271 // accumulating, same as `constrain`'s threshold shift below.
9272 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
9273 partial[0][(i + j) as usize] += x;
9274 partial[1][(i + j / 2) as usize] += x;
9275 partial[2][i as usize] += x;
9276 partial[3][(3 + i - j / 2) as usize] += x;
9277 partial[4][(7 + i - j) as usize] += x;
9278 partial[5][(3 - i / 2 + j) as usize] += x;
9279 partial[6][j as usize] += x;
9280 partial[7][(i / 2 + j) as usize] += x;
9281 }
9282 }
9283 let mut cost = [0i64; 8];
9284 for i in 0..8usize {
9285 cost[2] += partial[2][i] * partial[2][i];
9286 cost[6] += partial[6][i] * partial[6][i];
9287 }
9288 cost[2] *= DIV_TABLE[8];
9289 cost[6] *= DIV_TABLE[8];
9290 for i in 0..7usize {
9291 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
9292 * DIV_TABLE[i + 1];
9293 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
9294 * DIV_TABLE[i + 1];
9295 }
9296 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
9297 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
9298 for i in (1..8).step_by(2) {
9299 for j in 0..5usize {
9300 cost[i] += partial[i][3 + j] * partial[i][3 + j];
9301 }
9302 cost[i] *= DIV_TABLE[8];
9303 for j in 0..3usize {
9304 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
9305 * DIV_TABLE[2 * j + 2];
9306 }
9307 }
9308 let mut best_cost = 0i64;
9309 let mut best_dir = 0usize;
9310 for (i, &c) in cost.iter().enumerate() {
9311 if c > best_cost {
9312 best_cost = c;
9313 best_dir = i;
9314 }
9315 }
9316 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
9317 (best_dir, var as i32)
9318}
9319
9320/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
9321/// (high variance gap) gets more deringing than a flat or non-directional
9322/// one, only ever applied to the luma primary strength.
9323fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
9324 if var == 0 {
9325 return 0;
9326 }
9327 let i = if var >> 6 != 0 {
9328 cdef_msb(var >> 6).min(12)
9329 } else {
9330 0
9331 };
9332 (strength * (4 + i) + 8) >> 4
9333}
9334
9335/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
9336/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
9337/// previously-filtered neighbour must never feed this block's own sum).
9338#[allow(clippy::too_many_arguments)]
9339fn cdef_filter_block(
9340 sample: impl Fn(i32, i32) -> i32,
9341 dst: &mut PlaneBuf,
9342 ox: usize,
9343 oy: usize,
9344 bw: usize,
9345 bh: usize,
9346 pri_strength: i32,
9347 sec_strength: i32,
9348 dir: usize,
9349 pri_damping: i32,
9350 sec_damping: i32,
9351 enable_primary: bool,
9352 enable_secondary: bool,
9353 coeff_shift: i32,
9354) {
9355 let clipping_required = enable_primary && enable_secondary;
9356 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
9357 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
9358 // derivative) carries the bit-depth shift, so the tap-set parity bit
9359 // must be read back above that shift, not off the raw low bit.
9360 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
9361 for i in 0..bh {
9362 for j in 0..bw {
9363 let x = sample(i as i32, j as i32);
9364 let mut sum = 0i32;
9365 let mut max = x;
9366 let mut min = x;
9367 for k in 0..2usize {
9368 if enable_primary {
9369 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
9370 let p0 = sample(i as i32 + tr, j as i32 + tc);
9371 let p1 = sample(i as i32 - tr, j as i32 - tc);
9372 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
9373 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
9374 if clipping_required {
9375 if p0 != CDEF_VERY_LARGE {
9376 max = max.max(p0);
9377 }
9378 if p1 != CDEF_VERY_LARGE {
9379 max = max.max(p1);
9380 }
9381 min = min.min(p0).min(p1);
9382 }
9383 }
9384 if enable_secondary {
9385 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
9386 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
9387 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
9388 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
9389 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
9390 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
9391 if clipping_required {
9392 for s in [s0, s1, s2, s3] {
9393 if s != CDEF_VERY_LARGE {
9394 max = max.max(s);
9395 }
9396 }
9397 min = min.min(s0).min(s1).min(s2).min(s3);
9398 }
9399 sum += CDEF_SEC_TAPS[k]
9400 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
9401 + cdef_constrain(s1 - x, sec_strength, sec_damping)
9402 + cdef_constrain(s2 - x, sec_strength, sec_damping)
9403 + cdef_constrain(s3 - x, sec_strength, sec_damping));
9404 }
9405 }
9406 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
9407 if clipping_required {
9408 y = y.clamp(min, max);
9409 }
9410 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, sample_max()) as u16;
9411 }
9412 }
9413}
9414
9415/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
9416/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
9417/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
9418/// every block's level comes from [`LoopFilterParams::level`] plus the
9419/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
9420/// `get_filter_level`, precomputed per-block here rather than cached in a
9421/// table the way libaom's `av1_loop_filter_frame_init` does).
9422///
9423/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
9424/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
9425fn apply_deblock(
9426 y: &mut PlaneBuf,
9427 u: &mut PlaneBuf,
9428 v: &mut PlaneBuf,
9429 lf: &LoopFilterParams,
9430 n: &Neighbours,
9431 frame_width: usize,
9432 frame_height: usize,
9433) {
9434 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
9435 // mismatch between the raw reconstruction and post-filter output.
9436 if std::env::var_os("EC_AV1_DEBUG_SKIP_DEBLOCK").is_some() {
9437 return;
9438 }
9439 if lf.level[0] != 0 || lf.level[1] != 0 {
9440 deblock_plane(y, 0, lf, n, frame_width, frame_height);
9441 }
9442 if lf.level[2] != 0 {
9443 deblock_plane(u, 1, lf, n, frame_width, frame_height);
9444 }
9445 if lf.level[3] != 0 {
9446 deblock_plane(v, 2, lf, n, frame_width, frame_height);
9447 }
9448}
9449
9450/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
9451/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
9452/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
9453/// mi unit under this decoder's assumed 4:2:0 subsampling).
9454fn plane_to_mi(chroma: bool, coord: usize) -> usize {
9455 if chroma { coord / 2 } else { coord / 4 }
9456}
9457
9458/// This plane's own transform width in pixels at the covering block, spec
9459/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
9460/// width directly; chroma halves it (this decoder's UV transform is always
9461/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
9462/// under 4:2:0 and a block that never splits its own transform).
9463fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
9464 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
9465 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
9466}
9467
9468/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
9469/// edges step and gate by transform height, which differs from width only
9470/// on rect partition strips.
9471fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
9472 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
9473 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
9474}
9475
9476/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
9477/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
9478/// present only when its neighbour exists inside the true frame -- whether
9479/// the block immediately above (at this block's own leftmost mi column) or
9480/// to the left (at its own topmost mi row) coded a transform at least as wide
9481/// as `own_side`.
9482fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
9483 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
9484 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
9485 usize::from(above) + usize::from(left)
9486}
9487
9488/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
9489/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
9490/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
9491/// inter path maintains), except that an *inter* neighbour contributes its
9492/// own BLOCK size rather than its transform size -- the two differ the moment
9493/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
9494/// approximation coincides with this only while every neighbour codes one
9495/// whole-block transform, which is exactly what `TxMode::Select` ends.
9496fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
9497 let has_above = mi_r > n.tile_row0_mi;
9498 let has_left = mi_c > n.tile_col0_mi;
9499 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
9500 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
9501 if has_above && n.above_inter[mi_c / (SUB / MI)] {
9502 above = n.above_side_mi[mi_c] >= side;
9503 }
9504 if has_left && n.left_inter[mi_r / (SUB / MI)] {
9505 left = n.left_side_mi[mi_r] >= side;
9506 }
9507 match (has_above, has_left) {
9508 (true, true) => usize::from(above) + usize::from(left),
9509 (true, false) => usize::from(above),
9510 (false, true) => usize::from(left),
9511 (false, false) => 0,
9512 }
9513}
9514
9515/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
9516/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
9517/// the transform's own side in pixels (`side >> depth`) -- this decoder's
9518/// four square categories (8/16/32/64) each halve at most twice, matching
9519/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
9520fn read_tx_size(
9521 dec: &mut SymbolDecoder,
9522 cdfs: &mut Cdfs,
9523 n: &Neighbours,
9524 at_mi: (usize, usize),
9525 side: usize,
9526 // lane-txselect: `get_tx_size_context`'s real context, for the callers
9527 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
9528 // key-frame path's own deblock-grid approximation.
9529 ctx_override: Option<usize>,
9530) -> usize {
9531 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, side));
9532 let depth = match side {
9533 8 => {
9534 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
9535 }
9536 16 => {
9537 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
9538 }
9539 32 => {
9540 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
9541 }
9542 64 => {
9543 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
9544 }
9545 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
9546 };
9547 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
9548 let (rng, _) = dec.debug_state();
9549 let (mi_r, mi_c) = at_mi;
9550 eprintln!(
9551 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
9552 );
9553 }
9554 if depth != 0 {
9555 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
9556 }
9557 side >> depth
9558}
9559
9560/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
9561/// `txfm_split` context -- a category from the block's own largest square
9562/// transform and whether this unit already sits below it, times three, plus
9563/// the two neighbour terms (whether the transform last written above/left of
9564/// this unit is narrower/shorter than the unit itself).
9565fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
9566 let above = usize::from(usize::from(above_px) < tx_px);
9567 let left = usize::from(usize::from(left_px) < tx_px);
9568 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
9569 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
9570 // `log2(px) - 2`.
9571 let max_tx = blk_max_px.min(64);
9572 let max_idx = max_tx.trailing_zeros() as usize - 2;
9573 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
9574 category * 3 + above + left
9575}
9576
9577/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
9578/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
9579/// resolved transform's own size.
9580fn txfm_partition_update(
9581 n: &mut Neighbours,
9582 (mi_r, mi_c): (usize, usize),
9583 tx_px: usize,
9584 txb_px: usize,
9585) {
9586 for i in 0..txb_px / MI {
9587 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
9588 *cell = tx_px as u8;
9589 }
9590 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
9591 *cell = tx_px as u8;
9592 }
9593 }
9594}
9595
9596/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
9597/// same contexts -- a skipped *inter* block records its own block size rather
9598/// than its transform size.
9599fn set_txfm_ctxs(
9600 n: &mut Neighbours,
9601 (mi_r, mi_c): (usize, usize),
9602 tx_px: usize,
9603 w_mi: usize,
9604 h_mi: usize,
9605 skip_inter: bool,
9606) {
9607 let bw = if skip_inter { w_mi * MI } else { tx_px };
9608 let bh = if skip_inter { h_mi * MI } else { tx_px };
9609 for i in 0..w_mi {
9610 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
9611 *cell = bw as u8;
9612 }
9613 }
9614 for i in 0..h_mi {
9615 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
9616 *cell = bh as u8;
9617 }
9618 }
9619}
9620
9621/// The value libaom initialises both transform contexts to -- NOT zero:
9622/// `av1_zero_above_context` memsets the txfm row to
9623/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
9624/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
9625/// pixels, so an unwritten neighbour reads as the *widest* possible
9626/// transform, not the narrowest.
9627const TXFM_CTX_INIT: u8 = 64;
9628
9629/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
9630/// twice below its own largest transform.
9631const MAX_VARTX_DEPTH: usize = 2;
9632
9633/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
9634/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
9635/// max-transform-sized unit of an inter block, collecting the resolved leaf
9636/// transform units into `out` as `(row offset, col offset, side)` in mi units
9637/// -- exactly the order `decode_reconstruct_tx` later reads their
9638/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
9639/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
9640/// `max_block_high`).
9641#[allow(clippy::too_many_arguments)]
9642fn read_var_tx_size(
9643 dec: &mut SymbolDecoder,
9644 cdfs: &mut Cdfs,
9645 n: &mut Neighbours,
9646 at_mi: (usize, usize),
9647 blk_max_px: usize,
9648 (max_w_mi, max_h_mi): (usize, usize),
9649 tx_px: usize,
9650 depth: usize,
9651 blk_row: usize,
9652 blk_col: usize,
9653 out: &mut Vec<(usize, usize, usize)>,
9654) {
9655 if blk_row >= max_h_mi || blk_col >= max_w_mi {
9656 return;
9657 }
9658 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
9659 if depth == MAX_VARTX_DEPTH {
9660 out.push((blk_row, blk_col, tx_px));
9661 txfm_partition_update(n, unit, tx_px, tx_px);
9662 return;
9663 }
9664 let ctx = txfm_partition_ctx(n.above_txfm[unit.1], n.left_txfm[unit.0], blk_max_px, tx_px);
9665 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
9666 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
9667 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
9668 let (rng, _) = dec.debug_state();
9669 eprintln!(
9670 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
9671 unit.0,
9672 unit.1,
9673 u8::from(split)
9674 );
9675 }
9676 if !split {
9677 out.push((blk_row, blk_col, tx_px));
9678 txfm_partition_update(n, unit, tx_px, tx_px);
9679 return;
9680 }
9681 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
9682 let sub = tx_px / 2;
9683 if sub == 4 {
9684 // libaom's `sub_txs == TX_4X4` early return: the whole 8x8 unit is
9685 // marked 4x4 (four transform units, raster order) without recursing.
9686 for row in 0..2 {
9687 for col in 0..2 {
9688 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
9689 out.push((blk_row + row, blk_col + col, 4));
9690 }
9691 }
9692 }
9693 txfm_partition_update(n, unit, 4, tx_px);
9694 return;
9695 }
9696 for row in (0..tx_px / MI).step_by(sub / MI) {
9697 for col in (0..tx_px / MI).step_by(sub / MI) {
9698 read_var_tx_size(
9699 dec,
9700 cdfs,
9701 n,
9702 at_mi,
9703 blk_max_px,
9704 (max_w_mi, max_h_mi),
9705 sub,
9706 depth + 1,
9707 blk_row + row,
9708 blk_col + col,
9709 out,
9710 );
9711 }
9712 }
9713}
9714
9715/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
9716/// branch): every block of a `TxMode::Select` inter frame codes its transform
9717/// size right after its own mode info -- an inter non-skip block through the
9718/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
9719/// every other block through the intra `tx_depth` symbol (a skipped inter
9720/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
9721/// block's own resolved transform side and the leaf list, the latter only
9722/// when the tree resolved to more than one transform unit.
9723#[allow(clippy::too_many_arguments)]
9724fn read_block_tx_size(
9725 dec: &mut SymbolDecoder,
9726 cdfs: &mut Cdfs,
9727 n: &mut Neighbours,
9728 at_mi: (usize, usize),
9729 side: usize,
9730 (mi_cols, mi_rows): (usize, usize),
9731 is_inter: bool,
9732 skip: bool,
9733) -> Result<(usize, Option<Vec<(usize, usize, usize)>>)> {
9734 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
9735 return Ok((side, None));
9736 }
9737 let side_mi = side / MI;
9738 if is_inter && !skip {
9739 let max_tx = side.min(64);
9740 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
9741 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
9742 let mut leaves = Vec::new();
9743 let step = max_tx / MI;
9744 for row in (0..side_mi).step_by(step) {
9745 for col in (0..side_mi).step_by(step) {
9746 read_var_tx_size(
9747 dec,
9748 cdfs,
9749 n,
9750 at_mi,
9751 side,
9752 (max_w_mi, max_h_mi),
9753 max_tx,
9754 0,
9755 row,
9756 col,
9757 &mut leaves,
9758 );
9759 }
9760 }
9761 let single = leaves.len() == 1 && leaves[0].2 == side;
9762 if !single && leaves.iter().any(|leaf| leaf.2 > 32) {
9763 // Only a block wider than a superblock's own 64x64 max transform
9764 // reaches here; this crate has no 64-point *inter* coefficient
9765 // table set ([`inter_txbset_for`] stops at 32).
9766 return Err(unsupported(
9767 "an inter var-tx tree with a leaf transform larger than 32x32",
9768 ));
9769 }
9770 let resolved = leaves.last().map_or(side, |l| l.2);
9771 return Ok((resolved, (!single).then_some(leaves)));
9772 }
9773 let tx = if is_inter {
9774 side.min(64)
9775 } else {
9776 let resolved = read_tx_size(
9777 dec,
9778 cdfs,
9779 n,
9780 at_mi,
9781 side,
9782 Some(tx_size_context_txfm(n, at_mi, side)),
9783 );
9784 if resolved != side {
9785 // An intra block inside an inter frame whose `tx_depth` splits its
9786 // luma transform needs the per-transform-unit intra prediction
9787 // loop `decode_block` runs for a key frame; this path predicts the
9788 // whole block at once, so refuse rather than mis-reconstruct.
9789 return Err(unsupported(
9790 "an intra block in an inter frame whose tx_depth splits its luma transform \
9791 (round 1)",
9792 ));
9793 }
9794 resolved
9795 };
9796 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
9797 Ok((tx, None))
9798}
9799
9800/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
9801/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
9802/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
9803/// raster order, each reading its own coefficient context off the units
9804/// already decoded before it. Returns the block's luma grid (all-zero in the
9805/// split case, whose reconstruction has already happened unit by unit) and
9806/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
9807/// which for a split block lands on the top-left unit.
9808#[allow(clippy::too_many_arguments)]
9809fn read_inter_luma8(
9810 dec: &mut SymbolDecoder,
9811 cdfs: &mut Cdfs,
9812 neighbours: &mut Neighbours,
9813 leaf_mi: (usize, usize),
9814 y: &mut PlaneBuf,
9815 px: usize,
9816 py: usize,
9817 pred_y: &[u16],
9818 mode_for_tx: usize,
9819 base_q_idx: u8,
9820 scan8: &[u16],
9821 scan4: &[u16],
9822 reduced_tx_set: bool,
9823 split: bool,
9824) -> Result<(Vec<i32>, TxType)> {
9825 if !split {
9826 return read_inter_plane(
9827 dec,
9828 cdfs,
9829 if reduced_tx_set {
9830 TxbSet::Luma8Inter
9831 } else {
9832 TxbSet::Luma8InterSet1
9833 },
9834 scan8,
9835 0,
9836 neighbours.around_mi(leaf_mi, 8)[0],
9837 mode_for_tx,
9838 y,
9839 px,
9840 py,
9841 8,
9842 base_q_idx,
9843 pred_y,
9844 None,
9845 None,
9846 );
9847 }
9848 let mut first = TxType::DctDct;
9849 for tu_row in 0..2 {
9850 for tu_col in 0..2 {
9851 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
9852 let mut tu_pred = Vec::with_capacity(16);
9853 for rr in 0..4 {
9854 let start = (tu_row * 4 + rr) * 8 + tu_col * 4;
9855 tu_pred.extend_from_slice(&pred_y[start..start + 4]);
9856 }
9857 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
9858 let (tu_grid, tu_tx_type) = read_inter_plane(
9859 dec,
9860 cdfs,
9861 if reduced_tx_set {
9862 TxbSet::Luma4Inter
9863 } else {
9864 TxbSet::Luma4InterSet1
9865 },
9866 scan4,
9867 0,
9868 neighbours.around_mi(tu_mi, 4)[0],
9869 mode_for_tx,
9870 y,
9871 px + tu_col * 4,
9872 py + tu_row * 4,
9873 4,
9874 base_q_idx,
9875 &tu_pred,
9876 None,
9877 Some(tu_skip_ctx),
9878 )?;
9879 if tu_row == 0 && tu_col == 0 {
9880 first = tu_tx_type;
9881 }
9882 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
9883 }
9884 }
9885 Ok((vec![0i32; 64], first))
9886}
9887
9888/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
9889/// coefficient tables from -- the inter counterpart of [`txbset_for`].
9890fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
9891 match tx_px {
9892 32 => TxbSet::Luma32Inter,
9893 16 if reduced_tx_set => TxbSet::Luma16Inter,
9894 16 => TxbSet::Luma16InterSet1,
9895 8 if reduced_tx_set => TxbSet::Luma8Inter,
9896 8 => TxbSet::Luma8InterSet1,
9897 4 if reduced_tx_set => TxbSet::Luma4Inter,
9898 4 => TxbSet::Luma4InterSet1,
9899 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
9900 }
9901}
9902
9903/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
9904/// the only four sizes a `TxMode::Select` block's coded coefficient grid
9905/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
9906fn scan_for<'a>(
9907 tx_px: usize,
9908 scan32: &'a [u16],
9909 scan16: &'a [u16],
9910 scan8: &'a [u16],
9911 scan4: &'a [u16],
9912) -> &'a [u16] {
9913 match tx_px {
9914 32 => scan32,
9915 16 => scan16,
9916 8 => scan8,
9917 4 => scan4,
9918 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
9919 }
9920}
9921
9922/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
9923/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
9924/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
9925/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
9926/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
9927/// regardless of the flag (`av1_get_ext_tx_set_type`'s
9928/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
9929/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
9930/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
9931/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
9932/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
9933/// inter `ext_tx` sets, never the mode-indexed intra ones.
9934fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
9935 match tx_px {
9936 64 => TxbSet::Luma64,
9937 32 => TxbSet::Luma32Inter,
9938 16 if reduced_tx_set => TxbSet::Luma16Inter,
9939 16 => TxbSet::Luma16InterSet1,
9940 8 if reduced_tx_set => TxbSet::Luma8Inter,
9941 8 => TxbSet::Luma8InterSet1,
9942 _ => TxbSet::Luma64,
9943 }
9944}
9945
9946fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
9947 match tx_px {
9948 64 => TxbSet::Luma64,
9949 32 => TxbSet::Luma32,
9950 16 => TxbSet::Luma16,
9951 8 if reduced_tx_set => TxbSet::Luma8,
9952 8 => TxbSet::Luma8Set1,
9953 4 if reduced_tx_set => TxbSet::Luma4,
9954 4 => TxbSet::Luma4Set1,
9955 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
9956 }
9957}
9958
9959/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
9960/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
9961fn unit_log2(px: u32) -> i32 {
9962 if px == 0 {
9963 0
9964 } else {
9965 px.trailing_zeros() as i32 - 2
9966 }
9967}
9968
9969/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
9970/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
9971/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
9972/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
9973/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
9974/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
9975/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
9976/// block anywhere aborted the whole stream's decode before comparison).
9977fn lf_level(
9978 lf: &LoopFilterParams,
9979 plane_idx: usize,
9980 dir: usize,
9981 ref_frame: i8,
9982 delta_lf: i32,
9983 segment_id: u8,
9984) -> i32 {
9985 let base = i32::from(if plane_idx == 0 {
9986 lf.level[dir]
9987 } else if plane_idx == 1 {
9988 lf.level[2]
9989 } else {
9990 lf.level[3]
9991 });
9992 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
9993 // ref/mode delta scaling below, and regardless of `delta_enabled`
9994 // (that flag only gates `ref_deltas`/`mode_deltas`).
9995 let base = (base + delta_lf).clamp(0, 63);
9996 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
9997 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
9998 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
9999 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
10000 // for chroma.
10001 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
10002 let base = match seg_feature(usize::from(segment_id), feature) {
10003 Some(data) => (base + data).clamp(0, 63),
10004 None => base,
10005 };
10006 if !lf.delta_enabled {
10007 return base;
10008 }
10009 let scale = 1i32 << (base >> 5);
10010 let is_inter = ref_frame != 0;
10011 let is_globalmv = ref_frame < 0;
10012 let ref_idx = ref_frame.unsigned_abs() as usize;
10013 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
10014 if is_inter {
10015 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
10016 }
10017 lvl.clamp(0, 63)
10018}
10019
10020/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
10021/// no-segmentation, no-delta-LF path and to this decoder's own invariant
10022/// that a coded block's transform is always its own full size -- so a TU
10023/// edge is always also a PU edge, and the "both sides skipped, not a PU
10024/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
10025/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
10026/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
10027fn edge_params(
10028 lf: &LoopFilterParams,
10029 n: &Neighbours,
10030 plane_idx: usize,
10031 dir: usize,
10032 chroma: bool,
10033 x0: usize,
10034 y0: usize,
10035) -> Option<(u8, i32)> {
10036 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
10037 let cur_tx = if dir == 0 {
10038 tx_px_at(n, chroma, mi_r, mi_c)
10039 } else {
10040 tx_h_px_at(n, chroma, mi_r, mi_c)
10041 };
10042 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
10043 return None;
10044 }
10045 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
10046 let (pv_mi_r, pv_mi_c) = if dir == 0 {
10047 (mi_r, mi_c - 1)
10048 } else {
10049 (mi_r - 1, mi_c)
10050 };
10051 let pv_tx = if dir == 0 {
10052 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
10053 } else {
10054 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
10055 };
10056 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
10057 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
10058 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
10059 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
10060
10061 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
10062 let pv_level = lf_level(
10063 lf,
10064 plane_idx,
10065 dir,
10066 pv_ref,
10067 pv_delta_lf,
10068 segment_id_at(pv_mi_r, pv_mi_c),
10069 );
10070 if cur_level == 0 && pv_level == 0 {
10071 return None;
10072 }
10073 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
10074 let len: u8 = if chroma {
10075 if dim == 0 { 4 } else { 6 }
10076 } else {
10077 [4, 8, 14, 14, 14][dim]
10078 };
10079 let level = if cur_level != 0 { cur_level } else { pv_level };
10080 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
10081 Some((len, level))
10082}
10083
10084/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
10085fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
10086 let sharpness = i32::from(sharpness);
10087 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
10088 let mut lim = level >> shift;
10089 if sharpness > 0 {
10090 lim = lim.min(9 - sharpness);
10091 }
10092 lim = lim.max(1);
10093 (2 * (level + 2) + lim, lim, level >> 4)
10094}
10095
10096fn sclamp(v: i32) -> i32 {
10097 // libaom's `signed_char_clamp_high`: the clamp range scales with
10098 // `128 << (bit_depth - 8)` alongside the centering constant below.
10099 let scale = 1i32 << (bit_depth() - 8);
10100 v.clamp(-128 * scale, 128 * scale - 1)
10101}
10102
10103fn round_pow2(v: i32, n: u32) -> i32 {
10104 (v + (1 << (n - 1))) >> n
10105}
10106
10107/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
10108/// fallback.
10109fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
10110 if !mask {
10111 return [p1, p0, q0, q1];
10112 }
10113 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
10114 let centre = 128i32 << (bit_depth() - 8);
10115 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
10116 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
10117 let filter = sclamp(outer + 3 * (qs0 - ps0));
10118 let filter1 = sclamp(filter + 4) >> 3;
10119 let filter2 = sclamp(filter + 3) >> 3;
10120 let oq0 = sclamp(qs0 - filter1) + centre;
10121 let op0 = sclamp(ps0 + filter2) + centre;
10122 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
10123 let oq1 = sclamp(qs1 - tap) + centre;
10124 let op1 = sclamp(ps1 + tap) + centre;
10125 [op1, op0, oq0, oq1]
10126}
10127
10128/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
10129/// `filter4`'s narrow taps.
10130#[allow(clippy::too_many_arguments)]
10131fn filter6(
10132 mask: bool,
10133 thresh: i32,
10134 flat: bool,
10135 p2: i32,
10136 p1: i32,
10137 p0: i32,
10138 q0: i32,
10139 q1: i32,
10140 q2: i32,
10141) -> [i32; 4] {
10142 if flat && mask {
10143 [
10144 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
10145 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
10146 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
10147 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
10148 ]
10149 } else {
10150 filter4(mask, thresh, p1, p0, q0, q1)
10151 }
10152}
10153
10154/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
10155#[allow(clippy::too_many_arguments)]
10156fn filter8(
10157 mask: bool,
10158 thresh: i32,
10159 flat: bool,
10160 p3: i32,
10161 p2: i32,
10162 p1: i32,
10163 p0: i32,
10164 q0: i32,
10165 q1: i32,
10166 q2: i32,
10167 q3: i32,
10168) -> [i32; 6] {
10169 if flat && mask {
10170 [
10171 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
10172 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
10173 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
10174 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
10175 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
10176 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
10177 ]
10178 } else {
10179 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
10180 [p2, op1, op0, oq0, oq1, q2]
10181 }
10182}
10183
10184/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
10185/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
10186/// way -- they are only ever taps here, never written).
10187#[allow(clippy::too_many_arguments)]
10188fn filter14(
10189 mask: bool,
10190 thresh: i32,
10191 flat: bool,
10192 flat2: bool,
10193 p6: i32,
10194 p5: i32,
10195 p4: i32,
10196 p3: i32,
10197 p2: i32,
10198 p1: i32,
10199 p0: i32,
10200 q0: i32,
10201 q1: i32,
10202 q2: i32,
10203 q3: i32,
10204 q4: i32,
10205 q5: i32,
10206 q6: i32,
10207) -> [i32; 12] {
10208 if flat2 && flat && mask {
10209 [
10210 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
10211 round_pow2(
10212 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
10213 4,
10214 ),
10215 round_pow2(
10216 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
10217 4,
10218 ),
10219 round_pow2(
10220 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
10221 4,
10222 ),
10223 round_pow2(
10224 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
10225 4,
10226 ),
10227 round_pow2(
10228 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
10229 4,
10230 ),
10231 round_pow2(
10232 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
10233 4,
10234 ),
10235 round_pow2(
10236 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
10237 4,
10238 ),
10239 round_pow2(
10240 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
10241 4,
10242 ),
10243 round_pow2(
10244 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
10245 4,
10246 ),
10247 round_pow2(
10248 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
10249 4,
10250 ),
10251 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
10252 ]
10253 } else {
10254 let [op2, op1, op0, oq0, oq1, oq2] =
10255 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
10256 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
10257 }
10258}
10259
10260/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
10261/// the first (`q0`) sample past the edge, `outer_stride` advances to the
10262/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
10263/// the next along the edge's own filtering direction.
10264#[allow(clippy::too_many_arguments)]
10265fn filter_edge(
10266 data: &mut [u16],
10267 base: usize,
10268 outer_stride: isize,
10269 tap_stride: isize,
10270 len: u8,
10271 level: i32,
10272 sharpness: u8,
10273) {
10274 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
10275 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
10276 // every 8-bit threshold (including the flat masks' fixed `1`) is
10277 // compared against a raw pixel difference on the stream's own bit-depth
10278 // scale, so each is shifted left by `bit_depth - 8` before use.
10279 let shift = bit_depth() - 8;
10280 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
10281 let flat_thresh = 1i32 << shift;
10282 for i in 0..4isize {
10283 let center = (base as isize + i * outer_stride) as usize;
10284 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
10285 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
10286 match len {
10287 4 => {
10288 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
10289 let mask = (p1 - p0).abs() <= limit
10290 && (q1 - q0).abs() <= limit
10291 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10292 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
10293 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10294 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10295 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10296 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10297 }
10298 6 => {
10299 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
10300 let mask = (p2 - p1).abs() <= limit
10301 && (p1 - p0).abs() <= limit
10302 && (q1 - q0).abs() <= limit
10303 && (q2 - q1).abs() <= limit
10304 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10305 let flat = (p1 - p0).abs() <= flat_thresh
10306 && (q1 - q0).abs() <= flat_thresh
10307 && (p2 - p0).abs() <= flat_thresh
10308 && (q2 - q0).abs() <= flat_thresh;
10309 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
10310 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10311 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10312 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10313 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10314 }
10315 8 => {
10316 let (p3, p2, p1, p0, q0, q1, q2, q3) =
10317 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
10318 let mask = (p3 - p2).abs() <= limit
10319 && (p2 - p1).abs() <= limit
10320 && (p1 - p0).abs() <= limit
10321 && (q1 - q0).abs() <= limit
10322 && (q2 - q1).abs() <= limit
10323 && (q3 - q2).abs() <= limit
10324 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10325 let flat = (p1 - p0).abs() <= flat_thresh
10326 && (q1 - q0).abs() <= flat_thresh
10327 && (p2 - p0).abs() <= flat_thresh
10328 && (q2 - q0).abs() <= flat_thresh
10329 && (p3 - p0).abs() <= flat_thresh
10330 && (q3 - q0).abs() <= flat_thresh;
10331 let [op2, op1, op0, oq0, oq1, oq2] =
10332 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
10333 data[idx(-3)] = op2.clamp(0, sample_max()) as u16;
10334 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10335 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10336 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10337 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10338 data[idx(2)] = oq2.clamp(0, sample_max()) as u16;
10339 }
10340 _ => {
10341 let (p6, p5, p4, p3, p2, p1, p0) =
10342 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
10343 let (q0, q1, q2, q3, q4, q5, q6) =
10344 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
10345 let mask = (p3 - p2).abs() <= limit
10346 && (p2 - p1).abs() <= limit
10347 && (p1 - p0).abs() <= limit
10348 && (q1 - q0).abs() <= limit
10349 && (q2 - q1).abs() <= limit
10350 && (q3 - q2).abs() <= limit
10351 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10352 let flat = (p1 - p0).abs() <= flat_thresh
10353 && (q1 - q0).abs() <= flat_thresh
10354 && (p2 - p0).abs() <= flat_thresh
10355 && (q2 - q0).abs() <= flat_thresh
10356 && (p3 - p0).abs() <= flat_thresh
10357 && (q3 - q0).abs() <= flat_thresh;
10358 let flat2 = (p4 - p0).abs() <= flat_thresh
10359 && (q4 - q0).abs() <= flat_thresh
10360 && (p5 - p0).abs() <= flat_thresh
10361 && (q5 - q0).abs() <= flat_thresh
10362 && (p6 - p0).abs() <= flat_thresh
10363 && (q6 - q0).abs() <= flat_thresh;
10364 let out = filter14(
10365 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
10366 q6,
10367 );
10368 for (k, v) in (-6..=5isize).zip(out) {
10369 data[idx(k)] = v.clamp(0, sample_max()) as u16;
10370 }
10371 }
10372 }
10373 }
10374}
10375
10376/// One plane's worth of spec 7.14: every vertical edge across the plane,
10377/// then every horizontal edge (the order the spec and libaom both use).
10378fn deblock_plane(
10379 plane: &mut PlaneBuf,
10380 plane_idx: usize,
10381 lf: &LoopFilterParams,
10382 n: &Neighbours,
10383 frame_width: usize,
10384 frame_height: usize,
10385) {
10386 let chroma = plane_idx != 0;
10387 // r7: libaom clips the deblock loop to the CODED frame's own
10388 // width/height, not the mi-aligned `true_width`/`true_height` margin
10389 // (the padding up to the next 8-pixel/superblock boundary that
10390 // reconstruction still fills in but the loop filter never visits).
10391 // Confirmed against the superres gate: with the margin included, the
10392 // last coded mi column's horizontal edges were filtered when libaom's
10393 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
10394 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
10395 let (cw, ch) = if chroma {
10396 (frame_width.div_ceil(2), frame_height.div_ceil(2))
10397 } else {
10398 (frame_width, frame_height)
10399 };
10400 let (tw, th, stride) = (
10401 plane.true_width.min(cw),
10402 plane.true_height.min(ch),
10403 plane.width,
10404 );
10405 let mut y0 = 0usize;
10406 while y0 < th {
10407 let mut x0 = 4usize;
10408 while x0 < tw {
10409 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
10410 filter_edge(
10411 &mut plane.data,
10412 y0 * stride + x0,
10413 stride as isize,
10414 1,
10415 len,
10416 level,
10417 lf.sharpness,
10418 );
10419 }
10420 x0 += 4;
10421 }
10422 y0 += 4;
10423 }
10424 let mut x0 = 0usize;
10425 while x0 < tw {
10426 let mut y0 = 4usize;
10427 while y0 < th {
10428 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
10429 if std::env::var_os("EC_AV1_DEBLOCK_TRACE").is_some()
10430 && plane_idx == 0
10431 && x0 == 44
10432 {
10433 eprintln!(
10434 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
10435 lf.sharpness
10436 );
10437 }
10438 filter_edge(
10439 &mut plane.data,
10440 y0 * stride + x0,
10441 1,
10442 stride as isize,
10443 len,
10444 level,
10445 lf.sharpness,
10446 );
10447 }
10448 y0 += 4;
10449 }
10450 x0 += 4;
10451 }
10452}
10453
10454fn apply_cdef(
10455 y: &mut PlaneBuf,
10456 u: &mut PlaneBuf,
10457 v: &mut PlaneBuf,
10458 cdef: &CdefParams,
10459 skip_grid: &Neighbours,
10460) {
10461 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
10462 if std::env::var_os("EC_AV1_DEBUG_SKIP_CDEF").is_some() {
10463 return;
10464 }
10465 // `cdef.bits == 0` still means "no filtering at all" whenever the single
10466 // (index 0) strength pair is all-zero -- the fast path every existing
10467 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
10468 // at every index, but that is rare enough not to special-case; the
10469 // per-superblock lookup below degrades to the same index-0 read anyway
10470 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
10471 if cdef.bits == 0
10472 && cdef.y_pri_strength[0] == 0
10473 && cdef.y_sec_strength[0] == 0
10474 && cdef.uv_pri_strength[0] == 0
10475 && cdef.uv_sec_strength[0] == 0
10476 {
10477 return;
10478 }
10479 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
10480 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
10481 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
10482 if sb_cols == 0 {
10483 return 0;
10484 }
10485 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
10486 idx_grid
10487 .get(sb_r * sb_cols + sb_c)
10488 .copied()
10489 .unwrap_or(0) as usize
10490 };
10491 let src_y = y.data.clone();
10492 let src_u = u.data.clone();
10493 let src_v = v.data.clone();
10494 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
10495 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
10496 let coeff_shift = i32::from(bit_depth()) - 8;
10497 let damping = i32::from(cdef.damping) + coeff_shift;
10498 let damping_uv = (damping - 1).max(0);
10499 let mut mi_r = 0usize;
10500 while mi_r < skip_grid.mi_rows {
10501 let mut mi_c = 0usize;
10502 while mi_c < skip_grid.mi_cols {
10503 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
10504 let sidx = strength_idx(mi_r, mi_c);
10505 let (ox, oy) = (mi_c * 4, mi_r * 4);
10506 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
10507 let sample_y = |r: i32, c: i32| -> i32 {
10508 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
10509 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
10510 CDEF_VERY_LARGE
10511 } else {
10512 i32::from(src_y[ny as usize * y_stride + nx as usize])
10513 }
10514 };
10515 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| {
10516 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
10517 i32::from(src_y[ny * y_stride + nx])
10518 });
10519
10520 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
10521 // -- each plane zeroes the shared direction when *its own*
10522 // frame-level primary strength is 0, independent of the
10523 // per-block adjusted `t` and of the other plane's strength.
10524 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
10525 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
10526 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
10527 let t = cdef_adjust_strength(y_pri_strength, var);
10528 let enable_primary = t != 0;
10529 let enable_secondary = y_sec_strength != 0;
10530 if enable_primary || enable_secondary {
10531 cdef_filter_block(
10532 sample_y,
10533 y,
10534 ox,
10535 oy,
10536 8,
10537 8,
10538 t,
10539 y_sec_strength,
10540 y_dir,
10541 damping,
10542 damping,
10543 enable_primary,
10544 enable_secondary,
10545 coeff_shift,
10546 );
10547 }
10548
10549 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
10550 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
10551 let uv_dir = if t_uv != 0 { dir } else { 0 };
10552 let enable_primary_uv = t_uv != 0;
10553 let enable_secondary_uv = uv_sec_strength != 0;
10554 if enable_primary_uv || enable_secondary_uv {
10555 let (cox, coy) = (ox / 2, oy / 2);
10556 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
10557 let (tw, th) = (plane.true_width, plane.true_height);
10558 let stride = plane.width;
10559 let sample_uv = |r: i32, c: i32| -> i32 {
10560 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
10561 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
10562 CDEF_VERY_LARGE
10563 } else {
10564 i32::from(src_p[ny as usize * stride + nx as usize])
10565 }
10566 };
10567 cdef_filter_block(
10568 sample_uv,
10569 plane,
10570 cox,
10571 coy,
10572 4,
10573 4,
10574 t_uv,
10575 uv_sec_strength,
10576 uv_dir,
10577 damping_uv,
10578 damping_uv,
10579 enable_primary_uv,
10580 enable_secondary_uv,
10581 coeff_shift,
10582 );
10583 }
10584 }
10585 }
10586 mi_c += 2;
10587 }
10588 mi_r += 2;
10589 }
10590}
10591
10592/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
10593/// ordering note: libaom also runs `superres_post_decode` between the two,
10594/// but this decoder never implements super-resolution, so there is nothing
10595/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
10596/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
10597/// restoration's stripe-boundary rows read from it instead of the
10598/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
10599#[allow(clippy::too_many_arguments)]
10600fn apply_loop_restoration(
10601 y: &mut PlaneBuf,
10602 u: &mut PlaneBuf,
10603 v: &mut PlaneBuf,
10604 deblocked_y: &PlaneBuf,
10605 deblocked_u: &PlaneBuf,
10606 deblocked_v: &PlaneBuf,
10607 lr: &LoopRestorationParams,
10608 grid: &crate::restoration::RestorationGrid,
10609) {
10610 y.data = crate::restoration::apply_loop_restoration_plane(
10611 &y.data,
10612 &deblocked_y.data,
10613 y.width,
10614 y.true_width,
10615 y.true_height,
10616 0,
10617 lr.frame_restoration_type[0],
10618 lr.loop_restoration_size[0],
10619 grid,
10620 0,
10621 );
10622 u.data = crate::restoration::apply_loop_restoration_plane(
10623 &u.data,
10624 &deblocked_u.data,
10625 u.width,
10626 u.true_width,
10627 u.true_height,
10628 1,
10629 lr.frame_restoration_type[1],
10630 lr.loop_restoration_size[1],
10631 grid,
10632 1,
10633 );
10634 v.data = crate::restoration::apply_loop_restoration_plane(
10635 &v.data,
10636 &deblocked_v.data,
10637 v.width,
10638 v.true_width,
10639 v.true_height,
10640 1,
10641 lr.frame_restoration_type[2],
10642 lr.loop_restoration_size[2],
10643 grid,
10644 2,
10645 );
10646}
10647
10648/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
10649/// returning the picture it reconstructs to.
10650///
10651/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
10652/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
10653/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
10654/// `compute_image_size` derives one from the other, but not losslessly: a
10655/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
10656/// what the reconstruction is cropped to on the way out, mirroring
10657/// [`crate::encode::crop_encoded`].
10658///
10659/// # Errors
10660/// Returns an error when a block's partition, mode, skip flag or transform
10661/// type is anything this decoder does not reconstruct (round 2: inter, tx
10662/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
10663/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
10664/// or when the tile payload runs out of the symbols this decode expects (a
10665/// genuinely foreign stream).
10666pub fn decode_key_frame_tile(
10667 data: &[u8],
10668 mi_cols: u32,
10669 mi_rows: u32,
10670 base_q_idx: u8,
10671 frame_width: u32,
10672 frame_height: u32,
10673 enable_filter_intra: bool,
10674 cdef: &CdefParams,
10675 loop_filter: &LoopFilterParams,
10676 tx_select: bool,
10677 reduced_tx_set: bool,
10678 allow_screen_content_tools: bool,
10679 allow_intrabc: bool,
10680) -> Result<Picture> {
10681 let delta = DeltaParams::default();
10682 let single_tile = TileInfo {
10683 mi_col_starts: vec![0, mi_cols],
10684 mi_row_starts: vec![0, mi_rows],
10685 ..TileInfo::default()
10686 };
10687 decode_key_frame_tile_with_cdfs(
10688 &[data],
10689 &single_tile,
10690 mi_cols,
10691 mi_rows,
10692 base_q_idx,
10693 crate::quant::QuantDeltas::default(),
10694 frame_width,
10695 frame_height,
10696 enable_filter_intra,
10697 false,
10698 cdef,
10699 loop_filter,
10700 &LoopRestorationParams::default(),
10701 None,
10702 tx_select,
10703 reduced_tx_set,
10704 allow_screen_content_tools,
10705 allow_intrabc,
10706 delta,
10707 )
10708 .map(|(picture, _)| picture)
10709}
10710
10711thread_local! {
10712 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
10713 /// the mi-aligned `true_width`, set by the most recent
10714 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
10715 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
10716 /// their reconstructed buffer down from the same mi-aligned extent, so
10717 /// they share this one slot. See each function's own comment at its
10718 /// write site. `None` when there was no margin to save.
10719 static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
10720 const { std::cell::RefCell::new(None) };
10721}
10722
10723/// The margin the most recent key- or inter-frame tile decode stashed
10724/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
10725/// reads this immediately after the call, before any other frame
10726/// decode can overwrite it.
10727pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
10728 LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
10729}
10730
10731/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
10732/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
10733/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
10734/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
10735/// since a key frame's own header always forces `primary_ref_frame ==
10736/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
10737/// alongside the picture, for the caller to save into whichever reference
10738/// slots this frame's `refresh_frame_flags` names.
10739/// The order the 64x64 superblock quadrants of a tile are decoded in.
10740///
10741/// At `sb_size == 64` this is plain raster order over the tile's own
10742/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
10743/// each 128x128 superblock in raster order and visits its four 64x64
10744/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
10745/// 64-level bodies must run in that nested order. `row_start` marks the first
10746/// item of each *superblock* row (where the left neighbour context resets),
10747/// `sb_start` the first item of each superblock (where the 128 root's own
10748/// loop-restoration units and partition symbol are read).
10749fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
10750 let mut out = Vec::new();
10751 if !sb128 {
10752 for r in r0..r1 {
10753 for c in c0..c1 {
10754 out.push((r, c, c == c0, true));
10755 }
10756 }
10757 return out;
10758 }
10759 let mut r = r0;
10760 while r < r1 {
10761 let mut first_in_row = true;
10762 let mut c = c0;
10763 while c < c1 {
10764 let mut first_in_sb = true;
10765 for qr in 0..2 {
10766 for qc in 0..2 {
10767 let (rr, cc) = (r + qr, c + qc);
10768 if rr >= r1 || cc >= c1 {
10769 continue;
10770 }
10771 out.push((rr, cc, first_in_row, first_in_sb));
10772 first_in_row = false;
10773 first_in_sb = false;
10774 }
10775 }
10776 c += 2;
10777 }
10778 r += 2;
10779 }
10780 out
10781}
10782
10783pub(crate) fn decode_key_frame_tile_with_cdfs(
10784 tiles: &[&[u8]],
10785 tile_info: &TileInfo,
10786 mi_cols: u32,
10787 mi_rows: u32,
10788 base_q_idx: u8,
10789 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
10790 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
10791 // tile alongside [`CURRENT_Q_IDX`].
10792 deltas: crate::quant::QuantDeltas,
10793 frame_width: u32,
10794 frame_height: u32,
10795 enable_filter_intra: bool,
10796 enable_edge_filter: bool,
10797 cdef: &CdefParams,
10798 loop_filter: &LoopFilterParams,
10799 lr: &LoopRestorationParams,
10800 initial_cdfs: Option<Cdfs>,
10801 tx_select: bool,
10802 reduced_tx_set: bool,
10803 allow_screen_content_tools: bool,
10804 allow_intrabc: bool,
10805 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
10806 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
10807 // `stream.rs` still refuses a frame with `lf_present` set before this
10808 // function is ever called.
10809 delta: DeltaParams,
10810) -> Result<(Picture, Cdfs)> {
10811 if mi_cols == 0 || mi_rows == 0 {
10812 return Err(unsupported("a frame with no mode-info grid"));
10813 }
10814 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
10815 let sb128 = sb128();
10816 if sb128 && allow_intrabc {
10817 return Err(unsupported(
10818 "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)",
10819 ));
10820 }
10821 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
10822 INTRABC_MI_GRID.with(|g| {
10823 *g.borrow_mut() = allow_intrabc.then(|| {
10824 (
10825 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
10826 mi_cols as usize,
10827 mi_rows as usize,
10828 )
10829 });
10830 });
10831 INTRABC_DV.with(|c| c.set(None));
10832 CDEF_BITS.with(|c| c.set(cdef.bits));
10833 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
10834 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
10835 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
10836 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
10837 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
10838 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
10839 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
10840 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
10841 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
10842 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
10843
10844 let mut y = PlaneBuf {
10845 data: vec![0u16; width * height],
10846 width,
10847 height,
10848 true_width,
10849 true_height,
10850 tile_x0: 0,
10851 tile_y0: 0,
10852 tile_x1: width,
10853 tile_y1: height,
10854 };
10855 let mut u = PlaneBuf {
10856 data: vec![0u16; width * height / 4],
10857 width: width / 2,
10858 height: height / 2,
10859 true_width: true_width / 2,
10860 true_height: true_height / 2,
10861 tile_x0: 0,
10862 tile_y0: 0,
10863 tile_x1: width / 2,
10864 tile_y1: height / 2,
10865 };
10866 let mut v = PlaneBuf {
10867 data: vec![0u16; width * height / 4],
10868 width: width / 2,
10869 height: height / 2,
10870 true_width: true_width / 2,
10871 true_height: true_height / 2,
10872 tile_x0: 0,
10873 tile_y0: 0,
10874 tile_x1: width / 2,
10875 tile_y1: height / 2,
10876 };
10877
10878 let scan32 = default_scan(TX32);
10879 let scan16 = default_scan(TX16);
10880 let scan8 = default_scan(TX8);
10881 let scan4 = default_scan(TX4);
10882
10883 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
10884 let mut result_cdfs = base_cdfs.clone();
10885 let mut neighbours = Neighbours::new(
10886 cols32 as usize * 2,
10887 rows32 as usize * 2,
10888 mi_cols as usize,
10889 mi_rows as usize,
10890 );
10891 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
10892 let mut lr_reference = [(
10893 crate::restoration::WienerInfo::default(),
10894 crate::restoration::SgrprojInfo::default(),
10895 ); 3];
10896
10897 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
10898 // own byte range and its own fresh copy of the frame's initial CDFs
10899 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
10900 // `context_update_tile_id` has its end-of-tile adapted table kept as the
10901 // frame's own output (spec `exit_symbol`) -- every other tile's
10902 // adaptation is discarded, matching the refusal this replaces.
10903 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
10904 let tile_num = tile_idx as u32;
10905 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
10906 let mi_row0 = tile_info.mi_row_starts[trow as usize];
10907 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
10908 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
10909 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
10910 // Tile boundaries are always superblock-aligned in mi units (spec
10911 // 5.9.15's uniform/non-uniform derivation both only ever emit
10912 // multiples of the superblock's own mi size), so plain division is
10913 // exact here -- no rounding needed.
10914 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
10915 // tile boundary) are always superblock-aligned by spec 5.9.15; the
10916 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
10917 // last entry) is not, so the upper bound needs `div_ceil` the same
10918 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
10919 // trailing partial superblock row/column in scope.
10920 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
10921 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
10922
10923 let mut cdfs = base_cdfs.clone();
10924 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
10925 // `base_q_idx` at the top of every tile, not once per frame.
10926 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
10927 QUANT_DELTAS.with(|c| c.set(deltas));
10928 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
10929 if std::env::var_os("EC_AV1_TRACE").is_some() {
10930 eprintln!(
10931 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
10932 tile_bytes.len(),
10933 &tile_bytes[..tile_bytes.len().min(8)]
10934 );
10935 }
10936 let mut dec = SymbolDecoder::new(tile_bytes);
10937 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
10938 y.set_tile_origin(
10939 mi_col0 as usize * 4,
10940 mi_row0 as usize * 4,
10941 (mi_col1 as usize * 4).min(y.width),
10942 (mi_row1 as usize * 4).min(y.height),
10943 );
10944 u.set_tile_origin(
10945 mi_col0 as usize * 2,
10946 mi_row0 as usize * 2,
10947 (mi_col1 as usize * 2).min(u.width),
10948 (mi_row1 as usize * 2).min(u.height),
10949 );
10950 v.set_tile_origin(
10951 mi_col0 as usize * 2,
10952 mi_row0 as usize * 2,
10953 (mi_col1 as usize * 2).min(v.width),
10954 (mi_row1 as usize * 2).min(v.height),
10955 );
10956 TILE_HITS.with(|c| c.set(c.get() + 1));
10957
10958 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
10959 if row_start {
10960 neighbours.start_row();
10961 }
10962 {
10963 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
10964 // once for the whole 128x128 (spec 5.11.57 is called with the
10965 // superblock's own size), then one partition symbol off the
10966 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
10967 // recurses into the four 64x64 quadrants this decoder codes.
10968 if sb128 && sb_start {
10969 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
10970 crate::restoration::read_lr(
10971 &mut dec,
10972 &mut cdfs,
10973 lr,
10974 &mut lr_grid,
10975 &mut lr_reference,
10976 mi_r128,
10977 mi_c128,
10978 SB_MI * 2,
10979 );
10980 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
10981 let ctx128 = neighbours.partition_ctx(at128, 128);
10982 let (has_cols128, has_rows128) =
10983 (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
10984 let part128 = if has_cols128 && has_rows128 {
10985 PART128_SYMBOLS.with(|c| c.set(c.get() + 1));
10986 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
10987 if std::env::var_os("EC_AV1_TRACE").is_some() {
10988 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
10989 }
10990 p
10991 } else {
10992 match (has_cols128, has_rows128) {
10993 (true, false) => {
10994 dec.symbol_fixed(&gather_of(
10995 &cdfs.partition_w128[ctx128],
10996 &VERT_ALIKE128,
10997 ));
10998 }
10999 (false, true) => {
11000 dec.symbol_fixed(&gather_of(
11001 &cdfs.partition_w128[ctx128],
11002 &HORZ_ALIKE128,
11003 ));
11004 }
11005 _ => {}
11006 }
11007 PARTITION_SPLIT
11008 };
11009 if part128 != PARTITION_SPLIT {
11010 return Err(unsupported(
11011 "a 128x128 superblock partition other than SPLIT (NONE/HORZ/VERT and the four AB arms at the 128 root are not decoded)",
11012 ));
11013 }
11014 PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1));
11015 }
11016 if !sb128 {
11017 crate::restoration::read_lr(
11018 &mut dec,
11019 &mut cdfs,
11020 lr,
11021 &mut lr_grid,
11022 &mut lr_reference,
11023 sb_r * SB_MI,
11024 sb_c * SB_MI,
11025 SB_MI,
11026 );
11027 }
11028 CDEF_TRANSMITTED.with(|c| c.set(false));
11029 let at = (sb_r as usize * 4, sb_c as usize * 4);
11030 let ctx = neighbours.partition_ctx(at, SB);
11031 let (has_cols, has_rows) = (
11032 sb_c * SB_MI + SB_MI / 2 < mi_cols,
11033 sb_r * SB_MI + SB_MI / 2 < mi_rows,
11034 );
11035 // Recomputed at this superblock's own half (spec
11036 // `decode_partition`): a full alphabet symbol when both halves are
11037 // inside the true frame, a single gathered bit when just one is
11038 // (the superblock cannot be left whole, so this is forced split),
11039 // and nothing at all (SPLIT inferred, no bits) when neither is —
11040 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
11041 // three-way write exactly.
11042 let part = if has_cols && has_rows {
11043 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
11044 if std::env::var_os("EC_AV1_TRACE").is_some() {
11045 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
11046 }
11047 p
11048 } else {
11049 match (has_cols, has_rows) {
11050 (true, false) => {
11051 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
11052 }
11053 (false, true) => {
11054 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
11055 }
11056 _ => {}
11057 }
11058 PARTITION_SPLIT
11059 };
11060 match part {
11061 PARTITION_NONE => {
11062 decode_block(
11063 &mut dec,
11064 &mut cdfs,
11065 &mut neighbours,
11066 at,
11067 SB,
11068 TxbSet::Luma64,
11069 TxbSet::Chroma32,
11070 TX32,
11071 TX32,
11072 (&scan32, &scan32),
11073 false,
11074 &mut y,
11075 &mut u,
11076 &mut v,
11077 base_q_idx,
11078 enable_filter_intra,
11079 allow_screen_content_tools,
11080 allow_intrabc,
11081 &scan32,
11082 &scan16,
11083 &scan8,
11084 &scan4,
11085 tx_select,
11086 reduced_tx_set,
11087 )?;
11088 }
11089 PARTITION_SPLIT => {
11090 for q in 0..4 {
11091 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
11092 if r32 >= rows32 || c32 >= cols32 {
11093 continue;
11094 }
11095 let at32 = (r32 as usize * 2, c32 as usize * 2);
11096 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
11097 let (has_cols32, has_rows32) = (
11098 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
11099 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
11100 );
11101 let part32 = if has_cols32 && has_rows32 {
11102 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
11103 if std::env::var_os("EC_AV1_TRACE").is_some() {
11104 let (rng, _) = dec.debug_state();
11105 eprintln!(
11106 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
11107 r32 * BLOCK_MI,
11108 c32 * BLOCK_MI
11109 );
11110 }
11111 p
11112 } else {
11113 match (has_cols32, has_rows32) {
11114 (true, false) => {
11115 dec.symbol_fixed(&gather(
11116 &cdfs.partition_w32[ctx32],
11117 VERT_ALIKE,
11118 ));
11119 }
11120 (false, true) => {
11121 dec.symbol_fixed(&gather(
11122 &cdfs.partition_w32[ctx32],
11123 HORZ_ALIKE,
11124 ));
11125 }
11126 _ => {}
11127 }
11128 PARTITION_SPLIT
11129 };
11130 match part32 {
11131 PARTITION_NONE => {
11132 decode_block(
11133 &mut dec,
11134 &mut cdfs,
11135 &mut neighbours,
11136 at32,
11137 BLOCK,
11138 TxbSet::Luma32,
11139 TxbSet::Chroma16,
11140 TX32,
11141 TX16,
11142 (&scan32, &scan16),
11143 true,
11144 &mut y,
11145 &mut u,
11146 &mut v,
11147 base_q_idx,
11148 enable_filter_intra,
11149 allow_screen_content_tools,
11150 allow_intrabc,
11151 &scan32,
11152 &scan16,
11153 &scan8,
11154 &scan4,
11155 tx_select,
11156 reduced_tx_set,
11157 )?;
11158 }
11159 PARTITION_SPLIT => {
11160 for sub in 0..4 {
11161 let (sr, sc) =
11162 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
11163 if (sr as u32) * SUB_MI >= mi_rows
11164 || (sc as u32) * SUB_MI >= mi_cols
11165 {
11166 continue;
11167 }
11168 let (has_cols16, has_rows16) = (
11169 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
11170 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
11171 );
11172 let at16 = (sr, sc);
11173 let ctx16 = neighbours.partition_ctx(at16, SUB);
11174 if has_cols16 && has_rows16 {
11175 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
11176 if std::env::var_os("EC_AV1_TRACE").is_some() {
11177 eprintln!(
11178 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
11179 at16.0, at16.1
11180 );
11181 }
11182 if part16 == PARTITION_NONE {
11183 decode_block(
11184 &mut dec,
11185 &mut cdfs,
11186 &mut neighbours,
11187 at16,
11188 SUB,
11189 TxbSet::Luma16,
11190 TxbSet::Chroma8,
11191 TX16,
11192 TX8,
11193 (&scan16, &scan8),
11194 true,
11195 &mut y,
11196 &mut u,
11197 &mut v,
11198 base_q_idx,
11199 enable_filter_intra,
11200 allow_screen_content_tools,
11201 allow_intrabc,
11202 &scan32,
11203 &scan16,
11204 &scan8,
11205 &scan4,
11206 tx_select,
11207 reduced_tx_set,
11208 )?;
11209 continue;
11210 }
11211 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
11212 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
11213 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
11214 // `decode_partition` visit order (decodeframe.c):
11215 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
11216 // HORZ_B: top 16x8, BL 8x8, BR 8x8
11217 // VERT_A: TL 8x8, BL 8x8, right 8x16
11218 // VERT_B: left 8x16, TR 8x8, BR 8x8
11219 // The squares go through `decode_leaf8`, the strip through
11220 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
11221 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
11222 // used refuses the non-skip case at this size). Both writers keep
11223 // mi-granular mode/skip/palette records, so a later block's
11224 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
11225 // 16x16 cell.
11226 //
11227 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
11228 // top-right neighbour is the partition's own not-yet-decoded
11229 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
11230 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
11231 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
11232 let arm = part16 - PARTITION_HORZ_A;
11233 bump_ab16(arm);
11234 if part16 == PARTITION_VERT_B {
11235 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
11236 }
11237 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
11238 Some(crate::encode::Reach::vert_ab_partition())
11239 } else {
11240 None
11241 };
11242 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
11243 macro_rules! ab_leaf8 {
11244 ($mi:expr, $prev:expr) => {
11245 decode_leaf8(
11246 &mut dec,
11247 &mut cdfs,
11248 &mut neighbours,
11249 at16,
11250 $mi,
11251 (&scan8, &scan4),
11252 $prev,
11253 &mut y,
11254 &mut u,
11255 &mut v,
11256 base_q_idx,
11257 enable_filter_intra,
11258 allow_screen_content_tools,
11259 allow_intrabc,
11260 tx_select,
11261 reduced_tx_set,
11262 )?
11263 };
11264 }
11265 macro_rules! ab_strip {
11266 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
11267 decode_leaf_rect(
11268 &mut dec,
11269 &mut cdfs,
11270 &mut neighbours,
11271 at16,
11272 $mi,
11273 $bw,
11274 $bh,
11275 $prev,
11276 &mut y,
11277 &mut u,
11278 &mut v,
11279 enable_filter_intra,
11280 allow_screen_content_tools,
11281 base_q_idx,
11282 tx_select,
11283 reduced_tx_set,
11284 )?
11285 };
11286 }
11287 let tl = (mi_row0, mi_col0);
11288 let tr = (mi_row0, mi_col0 + 2);
11289 let bl = (mi_row0 + 2, mi_col0);
11290 let br = (mi_row0 + 2, mi_col0 + 2);
11291 let mut done: Vec<((usize, usize), usize)> = Vec::new();
11292 match part16 {
11293 PARTITION_HORZ_A => {
11294 let m_tl = ab_leaf8!(tl, done.last().copied());
11295 done.push((tl, m_tl));
11296 let m_tr = ab_leaf8!(tr, done.last().copied());
11297 done.push((tr, m_tr));
11298 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
11299 done.push((bl, m_bot));
11300 }
11301 PARTITION_HORZ_B => {
11302 let m_top = ab_strip!(tl, 16, 8, None);
11303 done.push((tl, m_top));
11304 let m_bl = ab_leaf8!(bl, done.last().copied());
11305 done.push((bl, m_bl));
11306 let m_br = ab_leaf8!(br, done.last().copied());
11307 done.push((br, m_br));
11308 }
11309 PARTITION_VERT_A => {
11310 let m_tl = ab_leaf8!(tl, done.last().copied());
11311 done.push((tl, m_tl));
11312 let m_bl = ab_leaf8!(bl, done.last().copied());
11313 done.push((bl, m_bl));
11314 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
11315 done.push((tr, m_right));
11316 }
11317 _ => {
11318 let m_left = ab_strip!(tl, 8, 16, None);
11319 done.push((tl, m_left));
11320 let m_tr = ab_leaf8!(tr, done.last().copied());
11321 done.push((tr, m_tr));
11322 let m_br = ab_leaf8!(br, done.last().copied());
11323 done.push((br, m_br));
11324 }
11325 }
11326 // Same coarse-slot write-back the real SPLIT path takes: the
11327 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
11328 // sub-block on the parent's bottom / right edge (the mi-exact map
11329 // above wins wherever it has an entry).
11330 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
11331 continue;
11332 }
11333 if part16 == PARTITION_HORZ {
11334 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
11335 let (mi_row0, mi_col0) = (
11336 sr as u32 * SUB_MI,
11337 sc as u32 * SUB_MI,
11338 );
11339 let top = (mi_row0 as usize, mi_col0 as usize);
11340 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
11341 let mode_top = decode_leaf_rect(
11342 &mut dec,
11343 &mut cdfs,
11344 &mut neighbours,
11345 at16,
11346 top,
11347 16,
11348 8,
11349 None,
11350 &mut y,
11351 &mut u,
11352 &mut v,
11353 enable_filter_intra,
11354 allow_screen_content_tools,
11355 base_q_idx,
11356 tx_select,
11357 reduced_tx_set,
11358 )?;
11359 let mode_bot = decode_leaf_rect(
11360 &mut dec,
11361 &mut cdfs,
11362 &mut neighbours,
11363 at16,
11364 bot,
11365 16,
11366 8,
11367 Some((top, mode_top)),
11368 &mut y,
11369 &mut u,
11370 &mut v,
11371 enable_filter_intra,
11372 allow_screen_content_tools,
11373 base_q_idx,
11374 tx_select,
11375 reduced_tx_set,
11376 )?;
11377 neighbours.above_mode[sc] = mode_bot;
11378 neighbours.left_mode[sr] = mode_bot;
11379 continue;
11380 }
11381 if part16 == PARTITION_VERT {
11382 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
11383 let (mi_row0, mi_col0) = (
11384 sr as u32 * SUB_MI,
11385 sc as u32 * SUB_MI,
11386 );
11387 let left = (mi_row0 as usize, mi_col0 as usize);
11388 let right = (mi_row0 as usize, mi_col0 as usize + 2);
11389 let mode_left = decode_leaf_rect(
11390 &mut dec,
11391 &mut cdfs,
11392 &mut neighbours,
11393 at16,
11394 left,
11395 8,
11396 16,
11397 None,
11398 &mut y,
11399 &mut u,
11400 &mut v,
11401 enable_filter_intra,
11402 allow_screen_content_tools,
11403 base_q_idx,
11404 tx_select,
11405 reduced_tx_set,
11406 )?;
11407 let mode_right = decode_leaf_rect(
11408 &mut dec,
11409 &mut cdfs,
11410 &mut neighbours,
11411 at16,
11412 right,
11413 8,
11414 16,
11415 Some((left, mode_left)),
11416 &mut y,
11417 &mut u,
11418 &mut v,
11419 enable_filter_intra,
11420 allow_screen_content_tools,
11421 base_q_idx,
11422 tx_select,
11423 reduced_tx_set,
11424 )?;
11425 neighbours.above_mode[sc] = mode_right;
11426 neighbours.left_mode[sr] = mode_right;
11427 continue;
11428 }
11429 if part16 != PARTITION_SPLIT {
11430 return Err(unsupported(
11431 "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)",
11432 ));
11433 }
11434 // A real (non-straddle) SPLIT of a
11435 // whole 16x16 into four 8x8 leaves --
11436 // the same recursion the straddle
11437 // path below already runs when the
11438 // true frame edge forces it, just
11439 // over all four positions instead of
11440 // the one or two the edge leaves.
11441 let (mi_row0, mi_col0) =
11442 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
11443 // Each 8x8 leaf's intra-mode context
11444 // must see its own siblings: the
11445 // bottom-left leaf's ABOVE neighbour
11446 // is leaf 0, not the previously
11447 // decoded leaf 1 (and the bottom-right
11448 // leaf's above is leaf 1, while
11449 // `prev_leaf` only ever carried the
11450 // immediately preceding one). The
11451 // coarse `above_mode`/`left_mode`
11452 // arrays hold one slot per 16x16, so
11453 // the sibling modes are swapped in
11454 // around each leaf call and restored
11455 // after; the loop tail writes the last
11456 // leaf's mode as before.
11457 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
11458 for i in 0..4 {
11459 let (mr, mc) =
11460 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
11461 let leaf_mi = (mr as usize, mc as usize);
11462 let li = i as usize;
11463 let saved_modes =
11464 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
11465 if li >= 2 {
11466 if let Some((below, _)) = sib_modes[li - 2] {
11467 neighbours.above_mode[sc] = below;
11468 }
11469 }
11470 if li % 2 == 1 {
11471 if let Some((_, right)) = sib_modes[li - 1] {
11472 neighbours.left_mode[sr] = right;
11473 }
11474 }
11475 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
11476 let part8 =
11477 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
11478 if std::env::var_os("EC_AV1_TRACE").is_some() {
11479 eprintln!(
11480 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
11481 );
11482 }
11483 let leaf_mode = if part8 == PARTITION_NONE {
11484 decode_leaf8(
11485 &mut dec,
11486 &mut cdfs,
11487 &mut neighbours,
11488 at16,
11489 leaf_mi,
11490 (&scan8, &scan4),
11491 None,
11492 &mut y,
11493 &mut u,
11494 &mut v,
11495 base_q_idx,
11496 enable_filter_intra,
11497 allow_screen_content_tools,
11498 allow_intrabc,
11499 tx_select,
11500 reduced_tx_set,
11501 ).map(|m| (m, m))?
11502 } else if part8 == PARTITION_SPLIT {
11503 decode_leaf_split4(
11504 &mut dec,
11505 &mut cdfs,
11506 &mut neighbours,
11507 at16,
11508 leaf_mi,
11509 &scan4,
11510 None,
11511 &mut y,
11512 &mut u,
11513 &mut v,
11514 base_q_idx,
11515 enable_filter_intra,
11516 allow_intrabc,
11517 reduced_tx_set,
11518 )?
11519 } else if part8 == PARTITION_HORZ
11520 || part8 == PARTITION_VERT
11521 {
11522 decode_leaf_rect8(
11523 &mut dec,
11524 &mut cdfs,
11525 &mut neighbours,
11526 at16,
11527 leaf_mi,
11528 part8 == PARTITION_VERT,
11529 &scan4,
11530 &mut y,
11531 &mut u,
11532 &mut v,
11533 base_q_idx,
11534 enable_filter_intra,
11535 allow_intrabc,
11536 tx_select,
11537 reduced_tx_set,
11538 )?
11539 } else {
11540 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
11541 };
11542 neighbours.above_mode[sc] = saved_modes.0;
11543 neighbours.left_mode[sr] = saved_modes.1;
11544 sib_modes[li] = Some(leaf_mode);
11545 }
11546 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
11547 neighbours.above_mode[sc] = below;
11548 }
11549 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
11550 neighbours.left_mode[sr] = right;
11551 }
11552 continue;
11553 }
11554 // The true edge falls inside this 16x16
11555 // leaf itself (mod-32==8 target sizes,
11556 // lane-av1-rect): one axis only -- an 8x8
11557 // leaf never itself straddles, so the
11558 // block splits cleanly along whichever
11559 // axis is short.
11560 if !has_cols16 && !has_rows16 {
11561 return Err(unsupported(
11562 "a 16x16 block whose true edge cuts through both \
11563 axes needs a rectangular transform this decoder \
11564 does not code yet",
11565 ));
11566 }
11567 if has_cols16 {
11568 dec.symbol_fixed(&gather(
11569 &cdfs.partition_w16[ctx16],
11570 VERT_ALIKE,
11571 ));
11572 } else {
11573 dec.symbol_fixed(&gather(
11574 &cdfs.partition_w16[ctx16],
11575 HORZ_ALIKE,
11576 ));
11577 }
11578 let (mi_row0, mi_col0) =
11579 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
11580 let leaf_positions: Vec<(u32, u32)> = (0..4)
11581 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
11582 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
11583 .collect();
11584 // See the sibling-mode note in the clean
11585 // SPLIT path above.
11586 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
11587 for (mr, mc) in leaf_positions {
11588 let leaf_mi = (mr as usize, mc as usize);
11589 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
11590 as usize;
11591 let saved_modes =
11592 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
11593 if li >= 2 {
11594 if let Some((below, _)) = sib_modes[li - 2] {
11595 neighbours.above_mode[sc] = below;
11596 }
11597 }
11598 if li % 2 == 1 {
11599 if let Some((_, right)) = sib_modes[li - 1] {
11600 neighbours.left_mode[sr] = right;
11601 }
11602 }
11603 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
11604 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
11605 if std::env::var_os("EC_AV1_TRACE").is_some() {
11606 eprintln!(
11607 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
11608 );
11609 }
11610 let leaf_mode = if part8 == PARTITION_NONE {
11611 decode_leaf8(
11612 &mut dec,
11613 &mut cdfs,
11614 &mut neighbours,
11615 at16,
11616 leaf_mi,
11617 (&scan8, &scan4),
11618 None,
11619 &mut y,
11620 &mut u,
11621 &mut v,
11622 base_q_idx,
11623 enable_filter_intra,
11624 allow_screen_content_tools,
11625 allow_intrabc,
11626 tx_select,
11627 reduced_tx_set,
11628 ).map(|m| (m, m))?
11629 } else if part8 == PARTITION_SPLIT {
11630 decode_leaf_split4(
11631 &mut dec,
11632 &mut cdfs,
11633 &mut neighbours,
11634 at16,
11635 leaf_mi,
11636 &scan4,
11637 None,
11638 &mut y,
11639 &mut u,
11640 &mut v,
11641 base_q_idx,
11642 enable_filter_intra,
11643 allow_intrabc,
11644 reduced_tx_set,
11645 )?
11646 } else if part8 == PARTITION_HORZ
11647 || part8 == PARTITION_VERT
11648 {
11649 decode_leaf_rect8(
11650 &mut dec,
11651 &mut cdfs,
11652 &mut neighbours,
11653 at16,
11654 leaf_mi,
11655 part8 == PARTITION_VERT,
11656 &scan4,
11657 &mut y,
11658 &mut u,
11659 &mut v,
11660 base_q_idx,
11661 enable_filter_intra,
11662 allow_intrabc,
11663 tx_select,
11664 reduced_tx_set,
11665 )?
11666 } else {
11667 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
11668 };
11669 neighbours.above_mode[sc] = saved_modes.0;
11670 neighbours.left_mode[sr] = saved_modes.1;
11671 sib_modes[li] = Some(leaf_mode);
11672 }
11673 // `record()`'s `above_mode`/`left_mode`
11674 // write is a no-op at an 8x8 leaf's own
11675 // side, so force the write once the whole
11676 // 16x16 slot's leaves are done, from the
11677 // last leaf (mirrors the writer's r15
11678 // fix).
11679 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
11680 neighbours.above_mode[sc] = below;
11681 }
11682 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
11683 neighbours.left_mode[sr] = right;
11684 }
11685 }
11686 }
11687 PARTITION_HORZ => {
11688 // lane-intradisp r1: two true 32x16 strips.
11689 decode_block_rect(
11690 &mut dec,
11691 &mut cdfs,
11692 &mut neighbours,
11693 at32,
11694 32,
11695 16,
11696 &mut y,
11697 &mut u,
11698 &mut v,
11699 enable_filter_intra,
11700 allow_screen_content_tools,
11701 base_q_idx,
11702 tx_select,
11703 reduced_tx_set,
11704 )?;
11705 decode_block_rect(
11706 &mut dec,
11707 &mut cdfs,
11708 &mut neighbours,
11709 (at32.0 + 1, at32.1),
11710 32,
11711 16,
11712 &mut y,
11713 &mut u,
11714 &mut v,
11715 enable_filter_intra,
11716 allow_screen_content_tools,
11717 base_q_idx,
11718 tx_select,
11719 reduced_tx_set,
11720 )?;
11721 }
11722 PARTITION_VERT => {
11723 // lane-intradisp r1: mirror of PARTITION_HORZ
11724 // above with width/height swapped.
11725 decode_block_rect(
11726 &mut dec,
11727 &mut cdfs,
11728 &mut neighbours,
11729 at32,
11730 16,
11731 32,
11732 &mut y,
11733 &mut u,
11734 &mut v,
11735 enable_filter_intra,
11736 allow_screen_content_tools,
11737 base_q_idx,
11738 tx_select,
11739 reduced_tx_set,
11740 )?;
11741 decode_block_rect(
11742 &mut dec,
11743 &mut cdfs,
11744 &mut neighbours,
11745 (at32.0, at32.1 + 1),
11746 16,
11747 32,
11748 &mut y,
11749 &mut u,
11750 &mut v,
11751 enable_filter_intra,
11752 allow_screen_content_tools,
11753 base_q_idx,
11754 tx_select,
11755 reduced_tx_set,
11756 )?;
11757 }
11758 PARTITION_HORZ_A => {
11759 // lane-part32 r1: two 16x16 squares on top +
11760 // a true 32x16 strip below (mirrors
11761 // decode_inter_block's cd6cb6d HORZ_A: TL,
11762 // TR, bottom strip).
11763 INTRA_HORZ_A_HITS.with(|c| c.set(c.get() + 1));
11764 decode_block(
11765 &mut dec,
11766 &mut cdfs,
11767 &mut neighbours,
11768 at32,
11769 SUB,
11770 TxbSet::Luma16,
11771 TxbSet::Chroma8,
11772 TX16,
11773 TX8,
11774 (&scan16, &scan8),
11775 true,
11776 &mut y,
11777 &mut u,
11778 &mut v,
11779 base_q_idx,
11780 enable_filter_intra,
11781 allow_screen_content_tools,
11782 allow_intrabc,
11783 &scan32,
11784 &scan16,
11785 &scan8,
11786 &scan4,
11787 tx_select,
11788 reduced_tx_set,
11789 )?;
11790 decode_block(
11791 &mut dec,
11792 &mut cdfs,
11793 &mut neighbours,
11794 (at32.0, at32.1 + 1),
11795 SUB,
11796 TxbSet::Luma16,
11797 TxbSet::Chroma8,
11798 TX16,
11799 TX8,
11800 (&scan16, &scan8),
11801 true,
11802 &mut y,
11803 &mut u,
11804 &mut v,
11805 base_q_idx,
11806 enable_filter_intra,
11807 allow_screen_content_tools,
11808 allow_intrabc,
11809 &scan32,
11810 &scan16,
11811 &scan8,
11812 &scan4,
11813 tx_select,
11814 reduced_tx_set,
11815 )?;
11816 decode_block_rect(
11817 &mut dec,
11818 &mut cdfs,
11819 &mut neighbours,
11820 (at32.0 + 1, at32.1),
11821 32,
11822 16,
11823 &mut y,
11824 &mut u,
11825 &mut v,
11826 enable_filter_intra,
11827 allow_screen_content_tools,
11828 base_q_idx,
11829 tx_select,
11830 reduced_tx_set,
11831 )?;
11832 }
11833 PARTITION_HORZ_B => {
11834 // lane-part32 r1: a true 32x16 strip on top +
11835 // two 16x16 squares below (mirrors HORZ_A
11836 // with the strip/squares order flipped, same
11837 // shape as libaom decode_partition's HORZ_B).
11838 INTRA_HORZ_B_HITS.with(|c| c.set(c.get() + 1));
11839 decode_block_rect(
11840 &mut dec,
11841 &mut cdfs,
11842 &mut neighbours,
11843 at32,
11844 32,
11845 16,
11846 &mut y,
11847 &mut u,
11848 &mut v,
11849 enable_filter_intra,
11850 allow_screen_content_tools,
11851 base_q_idx,
11852 tx_select,
11853 reduced_tx_set,
11854 )?;
11855 decode_block(
11856 &mut dec,
11857 &mut cdfs,
11858 &mut neighbours,
11859 (at32.0 + 1, at32.1),
11860 SUB,
11861 TxbSet::Luma16,
11862 TxbSet::Chroma8,
11863 TX16,
11864 TX8,
11865 (&scan16, &scan8),
11866 true,
11867 &mut y,
11868 &mut u,
11869 &mut v,
11870 base_q_idx,
11871 enable_filter_intra,
11872 allow_screen_content_tools,
11873 allow_intrabc,
11874 &scan32,
11875 &scan16,
11876 &scan8,
11877 &scan4,
11878 tx_select,
11879 reduced_tx_set,
11880 )?;
11881 decode_block(
11882 &mut dec,
11883 &mut cdfs,
11884 &mut neighbours,
11885 (at32.0 + 1, at32.1 + 1),
11886 SUB,
11887 TxbSet::Luma16,
11888 TxbSet::Chroma8,
11889 TX16,
11890 TX8,
11891 (&scan16, &scan8),
11892 true,
11893 &mut y,
11894 &mut u,
11895 &mut v,
11896 base_q_idx,
11897 enable_filter_intra,
11898 allow_screen_content_tools,
11899 allow_intrabc,
11900 &scan32,
11901 &scan16,
11902 &scan8,
11903 &scan4,
11904 tx_select,
11905 reduced_tx_set,
11906 )?;
11907 }
11908 PARTITION_VERT_A => {
11909 // lane-part32 r1: mirror of HORZ_A with
11910 // width/height swapped (TL, BL, right 16x32
11911 // strip).
11912 INTRA_VERT_A_HITS.with(|c| c.set(c.get() + 1));
11913 let _vert_ab = crate::encode::Reach::vert_ab_partition();
11914 decode_block(
11915 &mut dec,
11916 &mut cdfs,
11917 &mut neighbours,
11918 at32,
11919 SUB,
11920 TxbSet::Luma16,
11921 TxbSet::Chroma8,
11922 TX16,
11923 TX8,
11924 (&scan16, &scan8),
11925 true,
11926 &mut y,
11927 &mut u,
11928 &mut v,
11929 base_q_idx,
11930 enable_filter_intra,
11931 allow_screen_content_tools,
11932 allow_intrabc,
11933 &scan32,
11934 &scan16,
11935 &scan8,
11936 &scan4,
11937 tx_select,
11938 reduced_tx_set,
11939 )?;
11940 decode_block(
11941 &mut dec,
11942 &mut cdfs,
11943 &mut neighbours,
11944 (at32.0 + 1, at32.1),
11945 SUB,
11946 TxbSet::Luma16,
11947 TxbSet::Chroma8,
11948 TX16,
11949 TX8,
11950 (&scan16, &scan8),
11951 true,
11952 &mut y,
11953 &mut u,
11954 &mut v,
11955 base_q_idx,
11956 enable_filter_intra,
11957 allow_screen_content_tools,
11958 allow_intrabc,
11959 &scan32,
11960 &scan16,
11961 &scan8,
11962 &scan4,
11963 tx_select,
11964 reduced_tx_set,
11965 )?;
11966 decode_block_rect(
11967 &mut dec,
11968 &mut cdfs,
11969 &mut neighbours,
11970 (at32.0, at32.1 + 1),
11971 16,
11972 32,
11973 &mut y,
11974 &mut u,
11975 &mut v,
11976 enable_filter_intra,
11977 allow_screen_content_tools,
11978 base_q_idx,
11979 tx_select,
11980 reduced_tx_set,
11981 )?;
11982 }
11983 PARTITION_VERT_B => {
11984 // lane-part32 r1: a true 16x32 strip on the
11985 // left + two 16x16 squares on the right
11986 // (libaom decode_partition VERT_B: left
11987 // strip, TR, BR).
11988 INTRA_VERT_B_HITS.with(|c| c.set(c.get() + 1));
11989 let _vert_ab = crate::encode::Reach::vert_ab_partition();
11990 decode_block_rect(
11991 &mut dec,
11992 &mut cdfs,
11993 &mut neighbours,
11994 at32,
11995 16,
11996 32,
11997 &mut y,
11998 &mut u,
11999 &mut v,
12000 enable_filter_intra,
12001 allow_screen_content_tools,
12002 base_q_idx,
12003 tx_select,
12004 reduced_tx_set,
12005 )?;
12006 decode_block(
12007 &mut dec,
12008 &mut cdfs,
12009 &mut neighbours,
12010 (at32.0, at32.1 + 1),
12011 SUB,
12012 TxbSet::Luma16,
12013 TxbSet::Chroma8,
12014 TX16,
12015 TX8,
12016 (&scan16, &scan8),
12017 true,
12018 &mut y,
12019 &mut u,
12020 &mut v,
12021 base_q_idx,
12022 enable_filter_intra,
12023 allow_screen_content_tools,
12024 allow_intrabc,
12025 &scan32,
12026 &scan16,
12027 &scan8,
12028 &scan4,
12029 tx_select,
12030 reduced_tx_set,
12031 )?;
12032 decode_block(
12033 &mut dec,
12034 &mut cdfs,
12035 &mut neighbours,
12036 (at32.0 + 1, at32.1 + 1),
12037 SUB,
12038 TxbSet::Luma16,
12039 TxbSet::Chroma8,
12040 TX16,
12041 TX8,
12042 (&scan16, &scan8),
12043 true,
12044 &mut y,
12045 &mut u,
12046 &mut v,
12047 base_q_idx,
12048 enable_filter_intra,
12049 allow_screen_content_tools,
12050 allow_intrabc,
12051 &scan32,
12052 &scan16,
12053 &scan8,
12054 &scan4,
12055 tx_select,
12056 reduced_tx_set,
12057 )?;
12058 }
12059 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
12060 // lane-tx64x16 r3: the 1:4 pair at the 32x32
12061 // level -- four 32x8 (or 8x32) strips in
12062 // raster order, `quarter_step` = 2 mi, with
12063 // libaom `decode_partition`'s own `i > 0`
12064 // frame-edge break.
12065 let horz = part32 == PARTITION_HORZ_4;
12066 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
12067 let mut prev: Option<((usize, usize), usize)> = None;
12068 for i in 0..4 {
12069 let strip_mi = if horz {
12070 (base_mi.0 + i * 2, base_mi.1)
12071 } else {
12072 (base_mi.0, base_mi.1 + i * 2)
12073 };
12074 if i > 0
12075 && (strip_mi.0 >= mi_rows as usize
12076 || strip_mi.1 >= mi_cols as usize)
12077 {
12078 break;
12079 }
12080 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
12081 let (mode, _uv) = decode_block_rect4(
12082 &mut dec,
12083 &mut cdfs,
12084 &mut neighbours,
12085 strip_mi,
12086 bw,
12087 bh,
12088 prev,
12089 &mut y,
12090 &mut u,
12091 &mut v,
12092 enable_filter_intra,
12093 allow_screen_content_tools,
12094 base_q_idx,
12095 tx_select,
12096 )?;
12097 prev = Some((strip_mi, mode));
12098 }
12099 }
12100 _ => {
12101 return Err(unsupported(format!(
12102 "a 32x32 partition type this decoder does not code (value={part32})"
12103 )));
12104 }
12105 }
12106 }
12107 }
12108 PARTITION_HORZ => {
12109 // lane-sbpart r2: two true 64x32 strips.
12110 decode_block_rect64(
12111 &mut dec,
12112 &mut cdfs,
12113 &mut neighbours,
12114 at,
12115 64,
12116 32,
12117 &mut y,
12118 &mut u,
12119 &mut v,
12120 enable_filter_intra,
12121 allow_screen_content_tools,
12122 base_q_idx,
12123 tx_select,
12124 reduced_tx_set,
12125 )?;
12126 decode_block_rect64(
12127 &mut dec,
12128 &mut cdfs,
12129 &mut neighbours,
12130 (at.0 + 2, at.1),
12131 64,
12132 32,
12133 &mut y,
12134 &mut u,
12135 &mut v,
12136 enable_filter_intra,
12137 allow_screen_content_tools,
12138 base_q_idx,
12139 tx_select,
12140 reduced_tx_set,
12141 )?;
12142 }
12143 PARTITION_VERT => {
12144 // lane-sbpart r2: mirror of PARTITION_HORZ above with
12145 // width/height swapped.
12146 decode_block_rect64(
12147 &mut dec,
12148 &mut cdfs,
12149 &mut neighbours,
12150 at,
12151 32,
12152 64,
12153 &mut y,
12154 &mut u,
12155 &mut v,
12156 enable_filter_intra,
12157 allow_screen_content_tools,
12158 base_q_idx,
12159 tx_select,
12160 reduced_tx_set,
12161 )?;
12162 decode_block_rect64(
12163 &mut dec,
12164 &mut cdfs,
12165 &mut neighbours,
12166 (at.0, at.1 + 2),
12167 32,
12168 64,
12169 &mut y,
12170 &mut u,
12171 &mut v,
12172 enable_filter_intra,
12173 allow_screen_content_tools,
12174 base_q_idx,
12175 tx_select,
12176 reduced_tx_set,
12177 )?;
12178 }
12179 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
12180 // lane-part32 r4: the four superblock-level AB arms, each
12181 // two 32x32 squares plus one 64x32/32x64 strip, in
12182 // libaom's own `decode_partition` order (decodeframe.c:
12183 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
12184 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
12185 // TR, BR). The pieces are exactly the ones already proven
12186 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
12187 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
12188 SB_AB_HITS.with(|c| {
12189 let mut h = c.get();
12190 h[part - PARTITION_HORZ_A] += 1;
12191 c.set(h);
12192 });
12193 // lane-part32 r5: only the two VERTICAL arms reorder the
12194 // square sub-blocks (TL, BL, TR, BR), so only they switch
12195 // libaom's `has_tr`/`has_bl` tables.
12196 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
12197 .then(crate::encode::Reach::vert_ab_partition);
12198 macro_rules! square32 {
12199 ($at:expr) => {
12200 decode_block(
12201 &mut dec,
12202 &mut cdfs,
12203 &mut neighbours,
12204 $at,
12205 BLOCK,
12206 TxbSet::Luma32,
12207 TxbSet::Chroma16,
12208 TX32,
12209 TX16,
12210 (&scan32, &scan16),
12211 true,
12212 &mut y,
12213 &mut u,
12214 &mut v,
12215 base_q_idx,
12216 enable_filter_intra,
12217 allow_screen_content_tools,
12218 allow_intrabc,
12219 &scan32,
12220 &scan16,
12221 &scan8,
12222 &scan4,
12223 tx_select,
12224 reduced_tx_set,
12225 )?
12226 };
12227 }
12228 macro_rules! strip64 {
12229 ($at:expr, $bw:expr, $bh:expr) => {
12230 decode_block_rect64(
12231 &mut dec,
12232 &mut cdfs,
12233 &mut neighbours,
12234 $at,
12235 $bw,
12236 $bh,
12237 &mut y,
12238 &mut u,
12239 &mut v,
12240 enable_filter_intra,
12241 allow_screen_content_tools,
12242 base_q_idx,
12243 tx_select,
12244 reduced_tx_set,
12245 )?
12246 };
12247 }
12248 let (br, bc) = (at.0 + 2, at.1 + 2);
12249 match part {
12250 PARTITION_HORZ_A => {
12251 square32!(at);
12252 square32!((at.0, bc));
12253 strip64!((br, at.1), 64, 32);
12254 }
12255 PARTITION_HORZ_B => {
12256 strip64!(at, 64, 32);
12257 square32!((br, at.1));
12258 square32!((br, bc));
12259 }
12260 PARTITION_VERT_A => {
12261 square32!(at);
12262 square32!((br, at.1));
12263 strip64!((at.0, bc), 32, 64);
12264 }
12265 _ => {
12266 strip64!(at, 32, 64);
12267 square32!((at.0, bc));
12268 square32!((br, bc));
12269 }
12270 }
12271 }
12272 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
12273 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
12274 // 16x64) strips in raster order. `decode_partition`
12275 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
12276 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
12277 // frame edge for `i > 0`, so a partial superblock codes
12278 // only the strips whose origin is inside the frame.
12279 let horz = part == PARTITION_HORZ_4;
12280 for i in 0..4 {
12281 let step_mi = i * (SB_MI as usize / 4);
12282 let (this_r_mi, this_c_mi) = if horz {
12283 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
12284 } else {
12285 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
12286 };
12287 if i > 0
12288 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
12289 {
12290 break;
12291 }
12292 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
12293 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
12294 decode_block_rect64(
12295 &mut dec,
12296 &mut cdfs,
12297 &mut neighbours,
12298 strip_at,
12299 bw,
12300 bh,
12301 &mut y,
12302 &mut u,
12303 &mut v,
12304 enable_filter_intra,
12305 allow_screen_content_tools,
12306 base_q_idx,
12307 tx_select,
12308 reduced_tx_set,
12309 )?;
12310 }
12311 }
12312 _ => {
12313 return Err(unsupported(
12314 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
12315 ));
12316 }
12317 }
12318 }
12319 }
12320
12321 if tile_num == tile_info.context_update_tile_id {
12322 result_cdfs = cdfs;
12323 }
12324 }
12325
12326 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
12327 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
12328 // that isolate whether a decode-order frame's mismatch already exists
12329 // in reconstruction (this dump) vs is introduced by the loop filter
12330 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
12331 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
12332 use std::io::Write;
12333 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12334 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12335 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
12336 let _ = f.write_all(&narrow(&y));
12337 let _ = f.write_all(&narrow(&u));
12338 let _ = f.write_all(&narrow(&v));
12339 }
12340 } else {
12341 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12342 }
12343 if let Ok(path) = std::env::var("EC_AV1_PREFILT_WIDE_DUMP") {
12344 use std::io::Write;
12345 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12346 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12347 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
12348 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
12349 for row in 0..plane.true_height {
12350 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
12351 }
12352 out
12353 };
12354 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12355 let _ = f.write_all(&crop_wide(&y));
12356 let _ = f.write_all(&crop_wide(&u));
12357 let _ = f.write_all(&crop_wide(&v));
12358 }
12359 }
12360 apply_deblock(
12361 &mut y,
12362 &mut u,
12363 &mut v,
12364 loop_filter,
12365 &neighbours,
12366 frame_width as usize,
12367 frame_height as usize,
12368 );
12369 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
12370 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
12371 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
12372 // dump above these bisect WHICH filter stage introduced a mismatch.
12373 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
12374 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
12375 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
12376 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
12377
12378 let (fw, fh) = (frame_width as usize, frame_height as usize);
12379 if fw == width && fh == height {
12380 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
12381 return Ok((
12382 Picture {
12383 width,
12384 height,
12385 y: y.data,
12386 u: u.data,
12387 v: v.data,
12388 },
12389 result_cdfs,
12390 ));
12391 }
12392 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
12393 let mut out = Vec::with_capacity(w * h);
12394 for row in 0..h {
12395 out.extend(plane.data[row * plane.width..][..w].iter().copied());
12396 }
12397 out
12398 };
12399 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
12400 // is the real reconstructed extent -- columns `[fw, true_width)` hold
12401 // genuine decoded samples (the last coding block straddles the frame
12402 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
12403 // libaom's superres upscale runs on that buffer's own border-extended
12404 // margin, so it reads those real columns, not a synthetic replicate of
12405 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
12406 // aomenc 43->64 stream pinned column-by-column against libaom's own
12407 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
12408 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
12409 // decoder used before was off by 1 at the columns the tap window
12410 // reaches into that real margin; `None` when there is no margin (this
12411 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
12412 // non-superres frame whose width just isn't 32-block aligned).
12413 LAST_FRAME_WIDE_MARGIN.with(|m| {
12414 *m.borrow_mut() = if true_width > fw || true_height > fh {
12415 let yc = crop(&y, true_width, true_height);
12416 if let Ok(path) = std::env::var("EC_AV1_MARGIN_DUMP") {
12417 use std::io::Write;
12418 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12419 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12420 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12421 // corner-cut: this diagnostic dump stays 8-bit-narrowed
12422 // regardless of the stream's real bit depth (debug-only,
12423 // never read by a gate); widen if a >8-bit margin dump
12424 // is ever needed.
12425 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
12426 }
12427 }
12428 Some(Picture {
12429 width: true_width,
12430 height: true_height,
12431 y: yc,
12432 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
12433 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
12434 })
12435 } else {
12436 None
12437 }
12438 });
12439 Ok((
12440 Picture {
12441 width: fw,
12442 height: fh,
12443 y: crop(&y, fw, fh),
12444 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
12445 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
12446 },
12447 result_cdfs,
12448 ))
12449}
12450
12451/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
12452/// -- `above`/`left` are the neighbour's own resolved index for this
12453/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
12454/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
12455/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
12456/// block itself has a second reference) -- lane-av1idx: a stale "this
12457/// decoder never codes a compound reference" assumption baked this to
12458/// always-0, which desynced the CDF context bucket (not the decoded value
12459/// outright, hence small pixel deltas rather than a hard desync) the moment
12460/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
12461/// filter frame.
12462fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
12463 let base = dir * 8 + if is_compound { 4 } else { 0 };
12464 let term = if left == above {
12465 left
12466 } else if left == 3 {
12467 above
12468 } else if above == 3 {
12469 left
12470 } else {
12471 3
12472 };
12473 base + term as usize
12474}
12475
12476/// Resolves the interpolation filter kernel(s) an inter block's motion
12477/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
12478/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
12479/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
12480/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
12481/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
12482/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
12483/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
12484/// which forces `EIGHTTAP` without reading anything.
12485#[allow(clippy::too_many_arguments)]
12486fn resolve_interp_filter(
12487 dec: &mut SymbolDecoder,
12488 cdfs: &mut Cdfs,
12489 interp_fixed: Option<mc::InterpFilterKind>,
12490 enable_dual_filter: bool,
12491 force_regular: bool,
12492 above: [u8; 2],
12493 left: [u8; 2],
12494 is_compound: bool,
12495) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
12496 if let Some(kind) = interp_fixed {
12497 return (kind, kind, [3, 3]);
12498 }
12499 if force_regular {
12500 return (
12501 mc::InterpFilterKind::Regular,
12502 mc::InterpFilterKind::Regular,
12503 [0, 0],
12504 );
12505 }
12506 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
12507 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
12508 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
12509 // "horizontal then vertical" despite `predict_with_filters`' own
12510 // `h_kind`/`v_kind` argument order, which is why this function returns
12511 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
12512 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
12513 if std::env::var_os("EC_AV1_IFDBG").is_some() {
12514 eprintln!(
12515 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
12516 &cdfs.switchable_interp[ctx0][..3]
12517 );
12518 }
12519 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
12520 let sym1 = if enable_dual_filter {
12521 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
12522 if std::env::var_os("EC_AV1_IFDBG").is_some() {
12523 eprintln!(
12524 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
12525 &cdfs.switchable_interp[ctx1][..3]
12526 );
12527 }
12528 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
12529 } else {
12530 sym0
12531 };
12532 (
12533 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
12534 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
12535 [sym0, sym1],
12536 )
12537}
12538
12539/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
12540/// duplicating [`crate::tile`]'s private copy of the same rule.
12541pub(crate) fn intra_inter_ctx(
12542 has_above: bool,
12543 has_left: bool,
12544 above_inter: bool,
12545 left_inter: bool,
12546) -> usize {
12547 match (has_above, has_left) {
12548 (true, true) => {
12549 let (above_intra, left_intra) = (!above_inter, !left_inter);
12550 if above_intra && left_intra {
12551 3
12552 } else {
12553 usize::from(above_intra || left_intra)
12554 }
12555 }
12556 (true, false) => 2 * usize::from(!above_inter),
12557 (false, true) => 2 * usize::from(!left_inter),
12558 (false, false) => 0,
12559 }
12560}
12561
12562/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
12563/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
12564/// bits start counting from.
12565fn mv_class_base(class: usize) -> i32 {
12566 if class == 0 { 0 } else { 2i32 << (class + 2) }
12567}
12568
12569/// One motion vector component's non-zero diff (spec 5.11.32
12570/// `read_mv_component`), the inverse of [`crate::tile`]'s private
12571/// `write_mv_component`.
12572fn read_mv_component(
12573 dec: &mut SymbolDecoder,
12574 c: &mut MvComponentCdfs,
12575 allow_high_precision_mv: bool,
12576 force_integer_mv: bool,
12577) -> i32 {
12578 let sign = dec.symbol(&mut c.sign);
12579 let class = dec.symbol(&mut c.class);
12580 let local = if class == 0 {
12581 let bit = dec.symbol(&mut c.class0_bit);
12582 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
12583 // forces integer motion vectors -- implicitly `3` (the top
12584 // fractional value) rather than read, else every symbol after it
12585 // in the tile desyncs by one read.
12586 let fr = if force_integer_mv {
12587 3
12588 } else {
12589 dec.symbol(&mut c.class0_fr[bit])
12590 };
12591 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
12592 // high-precision motion vectors, else implicitly 1 (the low bit
12593 // stays at half-pel precision) -- this crate's own writer always
12594 // leaves the flag off, but a foreign stream can set it per frame.
12595 let hp = if allow_high_precision_mv {
12596 dec.symbol(&mut c.class0_hp)
12597 } else {
12598 1
12599 };
12600 (bit << 3) | (fr << 1) | hp
12601 } else {
12602 let mut d = 0;
12603 for i in 0..class {
12604 d |= dec.symbol(&mut c.bit[i]) << i;
12605 }
12606 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
12607 // `mv_class0_fr` above.
12608 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
12609 let hp = if allow_high_precision_mv {
12610 dec.symbol(&mut c.hp)
12611 } else {
12612 1
12613 };
12614 (d << 3) | (fr << 1) | hp
12615 };
12616 let mag = mv_class_base(class) + local as i32 + 1;
12617 if sign == 1 { -mag } else { mag }
12618}
12619
12620/// A motion vector coded as a residual against `pred` (spec 5.11.32
12621/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
12622fn read_mv(
12623 dec: &mut SymbolDecoder,
12624 mv_comp: &mut [MvComponentCdfs; 2],
12625 mv_joint: &mut [u16; 5],
12626 pred: (i32, i32),
12627 allow_high_precision_mv: bool,
12628 force_integer_mv: bool,
12629) -> (i32, i32) {
12630 let joint = dec.symbol(mv_joint);
12631 let mut diff = (0, 0);
12632 if joint == 2 || joint == 3 {
12633 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
12634 }
12635 if joint == 1 || joint == 3 {
12636 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
12637 }
12638 (pred.0 + diff.0, pred.1 + diff.1)
12639}
12640
12641/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
12642/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
12643///
12644/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
12645/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
12646/// when that is zero, or -- when both are -- the fixed fallback DV one
12647/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
12648/// left when this is the tile's first superblock row. The predictor is then
12649/// rounded to full pel, and the difference reads off the *dv* nmv context
12650/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
12651/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
12652/// symbol is coded for a DV, so none of this can move the bitstream
12653/// position -- only the reconstructed vector.
12654fn read_intrabc_dv(
12655 dec: &mut SymbolDecoder,
12656 cdfs: &mut Cdfs,
12657 mi_r: usize,
12658 mi_c: usize,
12659 side: usize,
12660) -> (i32, i32) {
12661 const INTRABC_DELAY_PIXELS: i32 = 256;
12662 let n4 = side / MI;
12663 let stack_pred = INTRABC_MI_GRID.with(|g| {
12664 let g = g.borrow();
12665 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
12666 let stack = crate::mvstack::find_mv_stack(
12667 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
12668 *mi_cols, *mi_rows,
12669 );
12670 if stack.nearest_mv == (0, 0) {
12671 stack.near_mv
12672 } else {
12673 stack.nearest_mv
12674 }
12675 })
12676 });
12677 let mut pred = stack_pred.unwrap_or((0, 0));
12678 if pred == (0, 0) {
12679 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
12680 // single-tile-row case every intrabc gate stream is).
12681 let sb_px = SB_MI as i32 * MI as i32;
12682 pred = if mi_r < SB_MI as usize {
12683 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
12684 } else {
12685 (-sb_px * 8, 0)
12686 };
12687 }
12688 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
12689 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
12690 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
12691}
12692
12693/// A 1/8-pel motion vector component converted to the 1/16-pel offset
12694/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
12695/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
12696fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
12697 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
12698}
12699
12700impl PlaneBuf {
12701 /// Adds `residual` onto an already-computed `prediction` (motion
12702 /// compensation's output, rather than [`predict`]'s intra one), writing
12703 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
12704 /// counterpart of [`PlaneBuf::reconstruct`].
12705 fn reconstruct_mc(
12706 &mut self,
12707 x: usize,
12708 y: usize,
12709 side: usize,
12710 prediction: &[u16],
12711 residual: &[i32],
12712 ) {
12713 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
12714 }
12715
12716 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
12717 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
12718 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
12719 /// VERT strip is predicted at its enclosing square `side` (matching
12720 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
12721 /// but only its own true `w`x`h` footprint is committed to the plane, so
12722 /// two strips sharing a square's coordinate origin never clobber each
12723 /// other's real pixels.
12724 fn reconstruct_mc_rect(
12725 &mut self,
12726 x: usize,
12727 y: usize,
12728 side: usize,
12729 w: usize,
12730 h: usize,
12731 prediction: &[u16],
12732 residual: &[i32],
12733 ) {
12734 for row in 0..h {
12735 for col in 0..w {
12736 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
12737 .clamp(0, crate::decode::sample_max()) as u16;
12738 self.data[(y + row) * self.width + x + col] = sample;
12739 }
12740 }
12741 }
12742}
12743
12744/// Reads one inter-coded plane's transform block and reconstructs it by
12745/// adding its residual onto a motion-compensated `prediction` -- the inter
12746/// counterpart of [`read_plane`] (every inter transform this decoder reads is
12747/// `side`-square with no oversized-64 case, so there is no padded-grid
12748/// branch to mirror).
12749#[allow(clippy::too_many_arguments)]
12750fn read_inter_plane(
12751 dec: &mut SymbolDecoder,
12752 cdfs: &mut Cdfs,
12753 set: TxbSet,
12754 scan: &[u16],
12755 plane_idx: usize,
12756 around: (bool, bool, i32),
12757 tx_mode: usize,
12758 plane: &mut PlaneBuf,
12759 x: usize,
12760 y: usize,
12761 side: usize,
12762 base_q_idx: u8,
12763 prediction: &[u16],
12764 // lane-chromau: this block's own luma transform's *actual coded*
12765 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
12766 // chroma plane never codes its own `tx_type` symbol, but (unlike an
12767 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
12768 // the colocated luma transform's coded type verbatim, clamped back to
12769 // `DCT_DCT` at the chroma tx sizes the spec forces DCT-only
12770 // (`av1_get_ext_tx_set_type`: `tx_size_sqr_up >= TX_32X32`, i.e. this
12771 // function's own `side >= 32`). `None` for the luma call itself
12772 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
12773 // `DCT_DCT` default at 32-point+) already resolves it without help.
12774 inherited_luma_tx_type: Option<TxType>,
12775 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
12776 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
12777 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
12778 // transform every non-var-tx caller reads, whose plane-0 context is the
12779 // lone-transform-unit 0.
12780 luma_skip_ctx: Option<usize>,
12781) -> Result<(Vec<i32>, TxType)> {
12782 let skip_ctx = if plane_idx == 0 {
12783 luma_skip_ctx.unwrap_or(0)
12784 } else {
12785 usize::from(around.0) + usize::from(around.1)
12786 };
12787 let mut coding = cdfs.txb(set, tx_mode);
12788 let default_tx_type = match inherited_luma_tx_type {
12789 Some(t) if side < 32 => t,
12790 _ => TxType::DctDct,
12791 };
12792 let (grid, tx_type) = read_coeffs(
12793 dec,
12794 &mut coding,
12795 scan,
12796 skip_ctx,
12797 dc_sign_ctx(around.2),
12798 default_tx_type,
12799 None,
12800 )?;
12801 note_chroma_class1(plane_idx, tx_type);
12802 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
12803 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
12804 // caller hands the 32-point `scan` there, and the coded corner goes into
12805 // the top-left of the true `side`-sized grid before dequantization
12806 // (dqDenom is keyed by the true size, not the corner's), mirroring
12807 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
12808 // this decoder codes has `tx_side == side`, so this is inert below 64.
12809 let tx_side = side.min(32);
12810 let grid = if tx_side == side {
12811 grid
12812 } else {
12813 let mut full = vec![0i32; side * side];
12814 for row in 0..tx_side {
12815 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
12816 }
12817 full
12818 };
12819 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
12820 let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
12821 plane.reconstruct_mc(x, y, side, prediction, &residual);
12822 Ok((grid, tx_type))
12823}
12824
12825/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
12826/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
12827/// `reference_select` set before this is ever called, so that read is never
12828/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
12829/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
12830fn read_single_ref(
12831 dec: &mut SymbolDecoder,
12832 cdfs: &mut Cdfs,
12833 above_ref: i8,
12834 above_ref1: Option<i8>,
12835 left_ref: i8,
12836 left_ref1: Option<i8>,
12837) -> i8 {
12838 let above = (above_ref > 0).then_some(above_ref);
12839 let left = (left_ref > 0).then_some(left_ref);
12840 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
12841 let ref_frame = if p1 == 1 {
12842 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
12843 if p2 == 1 {
12844 ALTREF_FRAME
12845 } else {
12846 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
12847 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
12848 }
12849 } else {
12850 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
12851 if p3 == 1 {
12852 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
12853 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
12854 } else {
12855 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
12856 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
12857 }
12858 };
12859 if ref_frame != LAST_FRAME {
12860 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
12861 let c = match ref_frame {
12862 LAST2_FRAME => &LAST2_HITS,
12863 LAST3_FRAME => &LAST3_HITS,
12864 GOLDEN_FRAME => &GOLDEN_HITS,
12865 BWDREF_FRAME => &BWDREF_HITS,
12866 ALTREF2_FRAME => &ALTREF2_HITS,
12867 ALTREF_FRAME => &ALTREF_HITS,
12868 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
12869 };
12870 c.with(|v| v.set(v.get() + 1));
12871 }
12872 ref_frame
12873}
12874
12875/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
12876/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
12877/// `reference_select` header bit lets a block choose per-block instead of
12878/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
12879/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
12880/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
12881/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
12882/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
12883/// Resolves a compound reference's own planes -- the same `ref_frame ==
12884/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
12885/// [`decode_inter_block`]'s single-ref path already does, factored out so
12886/// the compound path can call it twice (lane-av1comp).
12887fn ref_planes<'a>(
12888 ref_frame: i8,
12889 ref_y: &'a PlaneBuf,
12890 ref_u: &'a PlaneBuf,
12891 ref_v: &'a PlaneBuf,
12892 other_refs: &'a RefSlots,
12893) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
12894 if ref_frame == LAST_FRAME {
12895 Ok((ref_y, ref_u, ref_v))
12896 } else {
12897 match other_refs[ref_frame as usize] {
12898 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
12899 None => Err(unsupported(
12900 "a reference frame selected with no picture at this frame's own \
12901 ref_frame_idx slot for it",
12902 )),
12903 }
12904 }
12905}
12906
12907/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
12908/// directly above this block's own column span, one bordering block at a
12909/// time (stepping by that neighbour's own `MiInfo::size`, which is always
12910/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
12911/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
12912/// unit at a time, and does not itself count as a step). `max_neighbors`
12913/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
12914/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
12915/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
12916/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
12917/// not ported -- no block this decoder codes is narrower than 8px, so it
12918/// never fires here regardless of what a neighbour's own decoder was.
12919fn overlappable_above(
12920 grid: &MiGrid,
12921 mi_row: usize,
12922 mi_col: usize,
12923 bw4: usize,
12924 mi_cols: usize,
12925 max_neighbors: usize,
12926) -> Vec<(usize, usize, MiInfo)> {
12927 let mut out = Vec::new();
12928 if mi_row == 0 {
12929 return out;
12930 }
12931 let end_col = (mi_col + bw4).min(mi_cols);
12932 let mut col = mi_col;
12933 while col < end_col && out.len() < max_neighbors {
12934 let cell = grid.get(mi_row - 1, col);
12935 let step = cell.map_or(1, |c| c.size).max(1);
12936 if let Some(info) = cell {
12937 if info.is_inter {
12938 out.push((col - mi_col, step.min(end_col - col), *info));
12939 }
12940 }
12941 col += step;
12942 }
12943 out
12944}
12945
12946/// `foreach_overlappable_nb_left`'s left-column mirror of
12947/// [`overlappable_above`] -- see its doc for the shared corner-cut.
12948fn overlappable_left(
12949 grid: &MiGrid,
12950 mi_row: usize,
12951 mi_col: usize,
12952 bh4: usize,
12953 mi_rows: usize,
12954 max_neighbors: usize,
12955) -> Vec<(usize, usize, MiInfo)> {
12956 let mut out = Vec::new();
12957 if mi_col == 0 {
12958 return out;
12959 }
12960 let end_row = (mi_row + bh4).min(mi_rows);
12961 let mut row = mi_row;
12962 while row < end_row && out.len() < max_neighbors {
12963 let cell = grid.get(row, mi_col - 1);
12964 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
12965 // width (8) would swallow the strip below it.
12966 let step = cell.map_or(1, |c| c.size_h).max(1);
12967 if let Some(info) = cell {
12968 if info.is_inter {
12969 out.push((row - mi_row, step.min(end_row - row), *info));
12970 }
12971 }
12972 row += step;
12973 }
12974 out
12975}
12976
12977/// `has_top_right` (`av1/common/mvref_common.c`), reduced to the
12978/// square-block, fixed-64px-superblock case this decoder ever reaches: no
12979/// rectangular partition (`VERT`/`HORZ`/`_4`/`VERT_A`) ever produces an
12980/// inter leaf here (`xd->width == xd->height` always), so libaom's own
12981/// rect-partition branches (`xd->width < xd->height`, `xd->width >
12982/// xd->height`, `PARTITION_VERT_A`) never fire and are dropped. `bs` is the
12983/// block's own side in 4x4 (`mi`) units.
12984fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
12985 let sb_mi_size = SB_MI as usize;
12986 let mask_row = mi_row & (sb_mi_size - 1);
12987 let mask_col = mi_col & (sb_mi_size - 1);
12988 if bs > sb_mi_size {
12989 return false;
12990 }
12991 let mut has_tr = !((mask_row & bs != 0) && (mask_col & bs != 0));
12992 let mut b = bs;
12993 while b < sb_mi_size {
12994 if mask_col & b != 0 {
12995 if (mask_col & (2 * b) != 0) && (mask_row & (2 * b) != 0) {
12996 has_tr = false;
12997 break;
12998 }
12999 } else {
13000 break;
13001 }
13002 b <<= 1;
13003 }
13004 has_tr
13005}
13006
13007/// `av1_findSamples` (`mvref_common.c`), full port: the up to
13008/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
13009/// samples (`record_samples`) that share this block's own single reference
13010/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
13011/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
13012/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
13013/// libaom are also mi units of that same square side here). Each sample's
13014/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
13015/// come from the *neighbour* cell's own coded size, not this block's.
13016#[allow(clippy::too_many_arguments)]
13017fn find_samples(
13018 grid: &MiGrid,
13019 mi_row: usize,
13020 mi_col: usize,
13021 bw4: usize,
13022 bh4: usize,
13023 mi_cols: usize,
13024 mi_rows: usize,
13025 ref_frame: i8,
13026) -> Vec<crate::warp::Sample> {
13027 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
13028 let up_available = mi_row > 0;
13029 let left_available = mi_col > 0;
13030 let mut samples = Vec::with_capacity(MAX);
13031 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
13032 let mut do_tl = true;
13033 let mut do_tr = true;
13034 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
13035 let nb_bw = (info.size * 4) as i32;
13036 // lane-rect r2: the neighbour's own true height -- a rect strip
13037 // neighbour donates its sample at ITS center (aom pts y=-72 for a
13038 // 32x16 above strip; the square assumption put it at -136).
13039 let nb_bh = (info.size_h * 4) as i32;
13040 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
13041 };
13042
13043 'outer: {
13044 if up_available {
13045 let above = grid.get(mi_row - 1, mi_col);
13046 let superblock_width = above.map_or(1, |c| c.size).max(1);
13047 if bw4 <= superblock_width {
13048 let col_offset = -((mi_col % superblock_width) as isize);
13049 if col_offset < 0 {
13050 do_tl = false;
13051 }
13052 if col_offset + superblock_width as isize > bw4 as isize {
13053 do_tr = false;
13054 }
13055 if let Some(info) = above {
13056 if single_ref_match(info) {
13057 samples.push(rec(info, 0, -1, col_offset as i32, 1));
13058 if samples.len() >= MAX {
13059 break 'outer;
13060 }
13061 }
13062 }
13063 } else {
13064 let mut i = 0usize;
13065 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
13066 while i < limit {
13067 let cell = grid.get(mi_row - 1, mi_col + i);
13068 let sw = cell.map_or(1, |c| c.size).max(1);
13069 if let Some(info) = cell {
13070 if single_ref_match(info) {
13071 samples.push(rec(info, 0, -1, i as i32, 1));
13072 if samples.len() >= MAX {
13073 break 'outer;
13074 }
13075 }
13076 }
13077 i += sw;
13078 }
13079 }
13080 }
13081
13082 if left_available {
13083 let left = grid.get(mi_row, mi_col - 1);
13084 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
13085 if bh4 <= superblock_height {
13086 let row_offset = -((mi_row % superblock_height) as isize);
13087 if row_offset < 0 {
13088 do_tl = false;
13089 }
13090 if let Some(info) = left {
13091 if single_ref_match(info) {
13092 samples.push(rec(info, row_offset as i32, 1, 0, -1));
13093 if samples.len() >= MAX {
13094 break 'outer;
13095 }
13096 }
13097 }
13098 } else {
13099 let mut i = 0usize;
13100 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
13101 while i < limit {
13102 let cell = grid.get(mi_row + i, mi_col - 1);
13103 let sh = cell.map_or(1, |c| c.size_h).max(1);
13104 if let Some(info) = cell {
13105 if single_ref_match(info) {
13106 samples.push(rec(info, i as i32, 1, 0, -1));
13107 if samples.len() >= MAX {
13108 break 'outer;
13109 }
13110 }
13111 }
13112 i += sh;
13113 }
13114 }
13115 }
13116
13117 if do_tl && left_available && up_available {
13118 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
13119 if single_ref_match(info) {
13120 samples.push(rec(info, 0, -1, 0, -1));
13121 if samples.len() >= MAX {
13122 break 'outer;
13123 }
13124 }
13125 }
13126 }
13127
13128 if do_tr && has_top_right(mi_row, mi_col, bw4) {
13129 let tr_col = mi_col + bw4;
13130 if mi_row > 0 && tr_col < mi_cols {
13131 if let Some(info) = grid.get(mi_row - 1, tr_col) {
13132 if single_ref_match(info) {
13133 samples.push(rec(info, 0, -1, bw4 as i32, 1));
13134 }
13135 }
13136 }
13137 }
13138 }
13139 samples
13140}
13141
13142/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
13143/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
13144/// the 2-symbol `obmc_cdf` (spec 5.11.24).
13145#[allow(clippy::too_many_arguments)]
13146fn num_proj_ref(
13147 grid: &MiGrid,
13148 mi_row: usize,
13149 mi_col: usize,
13150 bw4: usize,
13151 bh4: usize,
13152 mi_cols: usize,
13153 mi_rows: usize,
13154 ref_frame: i8,
13155) -> u8 {
13156 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
13157}
13158
13159/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
13160/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
13161/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
13162/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
13163/// to 64 (no neighbour contribution) away from it. Only the lengths this
13164/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
13165/// are transcribed.
13166fn obmc_mask(len: usize) -> &'static [u8] {
13167 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
13168 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
13169 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
13170 // round wired interior 16x16 splits down to real 8x8 leaves, where the
13171 // old `unreachable!()` below fired as a hard panic.
13172 const M1: [u8; 1] = [64];
13173 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
13174 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
13175 // chroma), which only became live once 8x8 inter leaves stopped being
13176 // refused.
13177 const M2: [u8; 2] = [45, 64];
13178 const M4: [u8; 4] = [39, 50, 59, 64];
13179 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
13180 const M16: [u8; 16] = [
13181 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
13182 ];
13183 const M32: [u8; 32] = [
13184 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
13185 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
13186 ];
13187 match len {
13188 1 => &M1,
13189 2 => &M2,
13190 4 => &M4,
13191 8 => &M8,
13192 16 => &M16,
13193 32 => &M32,
13194 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
13195 }
13196}
13197
13198/// A bordering block's own resolved interp filter kernel, `(h, v)` --
13199/// mirrors [`resolve_interp_filter`]'s own return order from its stored
13200/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
13201/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]`
13202/// sentinel: that value is only ever stored for an intra neighbour (already
13203/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter`
13204/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here
13205/// first.
13206fn neighbour_filter(
13207 interp_fixed: Option<mc::InterpFilterKind>,
13208 sym: [u8; 2],
13209) -> (mc::InterpFilterKind, mc::InterpFilterKind) {
13210 if let Some(kind) = interp_fixed {
13211 return (kind, kind);
13212 }
13213 (
13214 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
13215 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
13216 )
13217}
13218
13219/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
13220/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
13221/// under `av1_setup_build_prediction_by_{above,left}_pred`).
13222#[allow(clippy::too_many_arguments)]
13223fn obmc_neighbour_pred(
13224 refplane: &PlaneBuf,
13225 x: usize,
13226 y: usize,
13227 mv: (i32, i32),
13228 w: usize,
13229 h: usize,
13230 luma: bool,
13231 h_kind: mc::InterpFilterKind,
13232 v_kind: mc::InterpFilterKind,
13233 // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own
13234 // reference (derived from luma widths, applied unchanged to chroma whose
13235 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
13236 // the ordinary stride-1 path bit-exact.
13237 x_scale_fp: i64,
13238) -> Vec<u16> {
13239 let mut out = vec![0u16; w * h];
13240 if x_scale_fp == mc::REF_NO_SCALE {
13241 mc::predict_with_filters(
13242 &refplane.data,
13243 refplane.width,
13244 refplane.true_width,
13245 refplane.true_height,
13246 mv_to_q4(x, mv.1, luma),
13247 mv_to_q4(y, mv.0, luma),
13248 w,
13249 h,
13250 h_kind,
13251 v_kind,
13252 &mut out,
13253 );
13254 } else {
13255 mc::predict_scaled(
13256 &refplane.data,
13257 refplane.width,
13258 refplane.true_width,
13259 refplane.true_height,
13260 mv_to_q4(x, mv.1, luma),
13261 mv_to_q4(y, mv.0, luma),
13262 x_scale_fp,
13263 w,
13264 h,
13265 h_kind,
13266 v_kind,
13267 &mut out,
13268 );
13269 }
13270 out
13271}
13272
13273/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
13274/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
13275/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
13276const II_WEIGHTS_1D: [u8; 128] = [
13277 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
13278 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
13279 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
13280 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
13281 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
13282 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
13283 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
13284];
13285
13286/// lane-interintra r1: non-wedge interintra prediction for one plane
13287/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
13288/// `build_smooth_interintra_mask`). Builds the intra predictor for the
13289/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
13290/// own decoded edges at `(x, y)`, then blends it over the inter prediction
13291/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
13292/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
13293/// reduces to `128 / side` for the square plane sizes this decoder reaches.
13294/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
13295/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
13296fn interintra_blend(
13297 plane: &PlaneBuf,
13298 x: usize,
13299 y: usize,
13300 side: usize,
13301 ii_mode: u8,
13302 wedge: Option<(&'static [u8], usize)>,
13303 pred: &mut [u16],
13304) {
13305 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
13306 let intra_mode = match ii_mode {
13307 0 => crate::intra::DC_PRED,
13308 1 => crate::intra::V_PRED,
13309 2 => crate::intra::H_PRED,
13310 _ => crate::intra::SMOOTH_PRED,
13311 };
13312 let (above, left, corner) = plane.edges(
13313 x,
13314 y,
13315 side,
13316 crate::encode::Reach {
13317 above_right: false,
13318 below_left: false,
13319 },
13320 );
13321 let mut intra = vec![0u16; side * side];
13322 // Edge filtering never applies here: V/H at delta 0 are plain edge
13323 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
13324 // angle at all.
13325 predict(
13326 intra_mode,
13327 0,
13328 above.as_deref(),
13329 left.as_deref(),
13330 corner,
13331 side,
13332 side,
13333 false,
13334 false,
13335 &mut intra,
13336 );
13337 let scale = 128 / side;
13338 for i in 0..side {
13339 for j in 0..side {
13340 let m = u32::from(match wedge {
13341 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
13342 // over the wedge codebook, intra as src0, fixed sign 0).
13343 // Luma plane: mask rows are luma-resolution, ms == side.
13344 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
13345 // subw == subh == 1).
13346 Some((mask, ms)) if ms == side => mask[i * side + j],
13347 Some((mask, ms)) => {
13348 let t = 2 * i * ms + 2 * j;
13349 ((u32::from(mask[t])
13350 + u32::from(mask[t + 1])
13351 + u32::from(mask[t + ms])
13352 + u32::from(mask[t + ms + 1])
13353 + 2)
13354 >> 2) as u8
13355 }
13356 None => match ii_mode {
13357 0 => 32,
13358 1 => II_WEIGHTS_1D[i * scale],
13359 2 => II_WEIGHTS_1D[j * scale],
13360 _ => II_WEIGHTS_1D[i.min(j) * scale],
13361 },
13362 });
13363 let idx = i * side + j;
13364 pred[idx] =
13365 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u16;
13366 }
13367 }
13368}
13369
13370fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
13371 let mask = obmc_mask(h);
13372 for row in 0..h {
13373 let m = u32::from(mask[row]);
13374 for col in 0..w {
13375 let d = &mut dst[(oy + row) * stride + ox + col];
13376 let t = u32::from(tmp[row * w + col]);
13377 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
13378 }
13379 }
13380}
13381
13382/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
13383/// left-neighbour pass, `aom_blend_a64_hmask`).
13384fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
13385 let mask = obmc_mask(w);
13386 for row in 0..h {
13387 for col in 0..w {
13388 let m = u32::from(mask[col]);
13389 let d = &mut dst[(oy + row) * stride + ox + col];
13390 let t = u32::from(tmp[row * w + col]);
13391 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
13392 }
13393 }
13394}
13395
13396/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
13397/// the overlap strip against each bordering above/left inter neighbour's own
13398/// mv/ref/filter and blends it into this block's just-built single-reference
13399/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
13400/// left, each reading only the *original* prediction this function was
13401/// handed (never the other pass's own output), matching libaom's own
13402/// independence between the two. `max_neighbor_obmc`'s own cap table
13403/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
13404/// decoder's own square blocks always index the same value both ways) bounds
13405/// how many bordering blocks actually get blended, separate from the
13406/// eligibility scan's own unbounded ("any at all") walk.
13407#[allow(clippy::too_many_arguments)]
13408fn obmc_blend(
13409 grid: &MiGrid,
13410 neighbours: &Neighbours,
13411 mi_row: usize,
13412 mi_col: usize,
13413 bw4: usize,
13414 bh4: usize,
13415 mi_rows: usize,
13416 mi_cols: usize,
13417 side: usize,
13418 write_w: usize,
13419 write_h: usize,
13420 chroma_side: usize,
13421 px: usize,
13422 py: usize,
13423 cpx: usize,
13424 cpy: usize,
13425 ref_y: &PlaneBuf,
13426 ref_u: &PlaneBuf,
13427 ref_v: &PlaneBuf,
13428 other_refs: &RefSlots,
13429 interp_fixed: Option<mc::InterpFilterKind>,
13430 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
13431 // neighbour is re-predicted against ITS OWN reference, which may be
13432 // scaled differently from this block's (spec 7.11.3.3 / libaom
13433 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
13434 // `scale_factors`).
13435 frame_width: usize,
13436 pred_y: &mut [u16],
13437 pred_u: &mut [u16],
13438 pred_v: &mut [u16],
13439) -> Result<()> {
13440 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
13441 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
13442 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
13443 // right only for square blocks.
13444 let max_nb = |n4: usize| match n4 {
13445 1..=4 => 2,
13446 5..=8 => 3,
13447 _ => 4,
13448 };
13449 let overlap_above = write_h / 2;
13450 let overlap_left = write_w / 2;
13451 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
13452 // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided
13453 // obmc") returns `dir == 0` when the chroma plane's own block is
13454 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
13455 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
13456 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
13457
13458 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
13459 {
13460 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
13461 // (this decoder's own outer block-loop granularity), one step
13462 // coarser than the mi(4px) units `overlappable_above` walks in --
13463 // divide back down to that column.
13464 // lane-gmaffine r2: the neighbour's OWN mi-granular filter
13465 // (libaom `av1_setup_build_prediction_by_above_pred` reads
13466 // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot
13467 // stays as the fallback for paths that do not record one yet
13468 // (compound), which is what every earlier round used.
13469 let (h_kind, v_kind) = neighbour_filter(
13470 interp_fixed,
13471 neighbours.above_filter[mi_col + off4],
13472 );
13473 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
13474 let nb_scale = mc::scale_factor(ny.width, frame_width);
13475 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
13476 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
13477 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
13478 if !skip_chroma_above {
13479 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
13480 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13481 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
13482 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13483 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
13484 }
13485 }
13486
13487 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
13488 let (h_kind, v_kind) = neighbour_filter(
13489 interp_fixed,
13490 neighbours.left_filter[mi_row + off4],
13491 );
13492 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
13493 let nb_scale = mc::scale_factor(ny.width, frame_width);
13494 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
13495 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
13496 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
13497 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
13498 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13499 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
13500 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13501 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
13502 }
13503 Ok(())
13504}
13505
13506/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
13507/// the square block sizes this decoder ever decodes (32/16/8, all
13508/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
13509/// always `is_interinter_compound_used`, so the function is always `true`
13510/// for `side` -- kept as a named call (rather than inlined `true`) so a
13511/// future sub-8 block size does not silently misdecode a real stream.
13512fn is_any_masked_compound_used_here(side: usize) -> bool {
13513 side.min(side) >= 8
13514}
13515
13516/// Whether a compound reference pair is unidirectional (both references on
13517/// the same temporal side of the current frame) -- `has_uni_comp_refs`
13518/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
13519/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
13520/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
13521/// is_backward(ref1)`). Used to build a real
13522/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
13523/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
13524fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
13525 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
13526 backward(ref0) == backward(ref1)
13527}
13528
13529/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
13530/// above/left neighbour contributions [`Neighbours::record_inter`]/
13531/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
13532/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
13533/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
13534/// leaves read the same neighbour cell (class context-read-from-one-cell).
13535fn get_comp_group_idx_context(
13536 neighbours: &Neighbours,
13537 at_mi: (usize, usize),
13538 side: usize,
13539) -> usize {
13540 let _ = side;
13541 let (rmi, cmi) = at_mi;
13542 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
13543 .min(5)
13544}
13545
13546/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
13547/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
13548/// block's own two references' distances from the current frame (spec
13549/// 7.11.3.15's `get_relative_dist`, same convention
13550/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
13551#[allow(clippy::too_many_arguments)]
13552fn get_comp_index_context(
13553 neighbours: &Neighbours,
13554 at_mi: (usize, usize),
13555 side: usize,
13556 order_hint_bits: u32,
13557 cur_order_hint: u32,
13558 ref0_order_hint: u32,
13559 ref1_order_hint: u32,
13560) -> usize {
13561 let _ = side;
13562 let (rmi, cmi) = at_mi;
13563 let fwd =
13564 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
13565 .abs();
13566 let bck =
13567 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
13568 .abs();
13569 let offset = usize::from(fwd == bck);
13570 neighbours.above_compound_idx[cmi] as usize
13571 + neighbours.left_compound_idx[rmi] as usize
13572 + 3 * offset
13573}
13574
13575fn read_comp_mode(
13576 dec: &mut SymbolDecoder,
13577 cdfs: &mut Cdfs,
13578 above: Option<NeighbourRef>,
13579 left: Option<NeighbourRef>,
13580) -> bool {
13581 let ctx = reference_mode_ctx(above, left);
13582 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
13583 if compound {
13584 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
13585 }
13586 compound
13587}
13588
13589/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
13590/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
13591/// arm), reached once [`read_comp_mode`] has already returned
13592/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
13593/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
13594/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
13595/// convention [`read_single_ref`] already uses, for every downstream binary
13596/// decision. libaom `pred_common.c`'s own compound context functions
13597/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
13598/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
13599/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
13600/// (same vote-the-neighbours-above-left shape, same forward/backward and
13601/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
13602/// against the C source rather than porting six near-duplicate functions.
13603/// Its caller today only needs the symbols consumed, correctly, to keep the
13604/// arithmetic decoder's own state in sync before refusing the block by name
13605/// -- the returned pair is not yet threaded into any motion-compensation
13606/// path.
13607fn read_compound_ref_frames(
13608 dec: &mut SymbolDecoder,
13609 cdfs: &mut Cdfs,
13610 above: Option<NeighbourRef>,
13611 left: Option<NeighbourRef>,
13612 above_ref: i8,
13613 left_ref: i8,
13614) -> (i8, i8) {
13615 let a = (above_ref > 0).then_some(above_ref);
13616 let l = (left_ref > 0).then_some(left_ref);
13617 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
13618 // neighbour's references, not just its first -- `a1`/`l1` carry that
13619 // second reference through to every vote below (lane-av1blend r6: a
13620 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
13621 // row for a block sitting under a skip_mode-forced compound neighbour).
13622 let a1 = above.and_then(|n| n.ref1);
13623 let l1 = left.and_then(|n| n.ref1);
13624 let type_ctx = comp_reference_type_ctx(above, left);
13625 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
13626 if unidir {
13627 UNI_COMP_HITS.with(|c| c.set(c.get() + 1));
13628 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
13629 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
13630 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
13631 if bit == 1 {
13632 (BWDREF_FRAME, ALTREF_FRAME)
13633 } else {
13634 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
13635 if p1 == 1 {
13636 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
13637 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
13638 if p2 == 1 {
13639 (LAST_FRAME, GOLDEN_FRAME)
13640 } else {
13641 (LAST_FRAME, LAST3_FRAME)
13642 }
13643 } else {
13644 (LAST_FRAME, LAST2_FRAME)
13645 }
13646 }
13647 } else {
13648 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
13649 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
13650 let ref0 = if bit0 == 0 {
13651 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
13652 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
13653 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
13654 } else {
13655 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
13656 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
13657 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
13658 };
13659 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
13660 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
13661 let ref1 = if bit1 == 0 {
13662 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
13663 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
13664 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
13665 } else {
13666 ALTREF_FRAME
13667 };
13668 (ref0, ref1)
13669 }
13670}
13671
13672/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
13673/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
13674/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
13675/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
13676/// libaom's `av1_mode_context_analyzer`'s compound branch --
13677/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
13678/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
13679/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
13680/// is not yet turned into an assigned MV pair or motion-compensated --
13681/// lane-av1comp.
13682fn read_inter_compound_mode(
13683 dec: &mut SymbolDecoder,
13684 cdfs: &mut Cdfs,
13685 new_mv_ctx: usize,
13686 ref_mv_ctx: usize,
13687) -> u8 {
13688 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
13689 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
13690 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
13691}
13692
13693/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
13694/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
13695/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
13696/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
13697/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
13698/// non-`IDENTITY` global motion model before a tile is ever decoded.
13699///
13700/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
13701/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
13702/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
13703/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
13704/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
13705fn assign_compound_mv(
13706 dec: &mut SymbolDecoder,
13707 cdfs: &mut Cdfs,
13708 comp_stack: &crate::mvstack::CompoundMvStack,
13709 mode: u8,
13710 allow_high_precision_mv: bool,
13711 force_integer_mv: bool,
13712 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
13713 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
13714 global_mv: ((i32, i32), (i32, i32)),
13715) -> ((i32, i32), (i32, i32)) {
13716 const NEAREST_NEARESTMV: u8 = 0;
13717 const NEAR_NEARMV: u8 = 1;
13718 const NEAREST_NEWMV: u8 = 2;
13719 const NEW_NEARESTMV: u8 = 3;
13720 const NEAR_NEWMV: u8 = 4;
13721 const NEW_NEARMV: u8 = 5;
13722 const GLOBAL_GLOBALMV: u8 = 6;
13723 const NEW_NEWMV: u8 = 7;
13724
13725 let mut ref_mv_idx = 0usize;
13726 if mode == NEW_NEWMV {
13727 let mut idx = 0usize;
13728 while idx < 2 && comp_stack.entries.len() > idx + 1 {
13729 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
13730 break;
13731 }
13732 idx += 1;
13733 }
13734 ref_mv_idx = idx;
13735 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
13736 let mut idx = 1usize;
13737 while idx < 3 && comp_stack.entries.len() > idx + 1 {
13738 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
13739 break;
13740 }
13741 idx += 1;
13742 }
13743 ref_mv_idx = idx - 1;
13744 }
13745
13746 let near = comp_stack
13747 .entries
13748 .get(ref_mv_idx + 1)
13749 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
13750 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
13751 ref_mv_idx + 1
13752 } else {
13753 ref_mv_idx
13754 };
13755 let new_pred = comp_stack
13756 .entries
13757 .get(new_idx)
13758 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
13759
13760 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
13761 read_mv(
13762 dec,
13763 &mut cdfs.mv_comp,
13764 &mut cdfs.mv_joint,
13765 base,
13766 allow_high_precision_mv,
13767 force_integer_mv,
13768 )
13769 };
13770
13771 match mode {
13772 NEAREST_NEARESTMV => comp_stack.nearest_mv,
13773 NEAR_NEARMV => near,
13774 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
13775 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
13776 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
13777 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
13778 GLOBAL_GLOBALMV => global_mv,
13779 _ => (
13780 read_new(dec, cdfs, new_pred.0),
13781 read_new(dec, cdfs, new_pred.1),
13782 ),
13783 }
13784}
13785
13786/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
13787/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
13788/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
13789/// table is always computed at the *querying* block's position, never a
13790/// donating neighbour's).
13791fn build_gm_mv_table(
13792 global_motion: &[ec_av1_syntax::WarpParams; 7],
13793 mi_row: usize,
13794 mi_col: usize,
13795 bw4: usize,
13796 bh4: usize,
13797 allow_high_precision_mv: bool,
13798 force_integer_mv: bool,
13799) -> crate::mvstack::GmMvTable {
13800 std::array::from_fn(|i| {
13801 let gm = &global_motion[i];
13802 crate::warp::gm_get_motion_vector(
13803 gm.model,
13804 &gm.params,
13805 mi_row,
13806 mi_col,
13807 bw4,
13808 bh4,
13809 allow_high_precision_mv,
13810 force_integer_mv,
13811 )
13812 })
13813}
13814
13815/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
13816/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
13817/// and motion-compensated reconstruction, or the inter frame's own intra
13818/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
13819/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
13820/// private `write_inter_frame_leaf` -- both share this one function here,
13821/// parameterised by `side`/the transform sets/scan tables/size group they
13822/// each use.
13823///
13824/// # Errors
13825/// Returns an error when a symbol names anything this decoder does not
13826/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
13827/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
13828/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
13829/// refuse.
13830#[allow(clippy::too_many_arguments)]
13831fn decode_inter_block(
13832 dec: &mut SymbolDecoder,
13833 cdfs: &mut Cdfs,
13834 neighbours: &mut Neighbours,
13835 grid: &mut MiGrid,
13836 at: (usize, usize),
13837 side: usize,
13838 mi_cols: u32,
13839 mi_rows: u32,
13840 y: &mut PlaneBuf,
13841 u: &mut PlaneBuf,
13842 v: &mut PlaneBuf,
13843 ref_y: &PlaneBuf,
13844 ref_u: &PlaneBuf,
13845 ref_v: &PlaneBuf,
13846 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
13847 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
13848 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
13849 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
13850 // slot's still empty (an error-resilient stream, or too early in the
13851 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
13852 other_refs: &RefSlots,
13853 sign_bias_table: &SignBiasTable,
13854 // lane-gm r2: this frame header's own `global_motion` table (spec
13855 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
13856 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
13857 // assignment and the mv-stack's neighbour substitution.
13858 global_motion: &[ec_av1_syntax::WarpParams; 7],
13859 base_q_idx: u8,
13860 luma_set_intra: TxbSet,
13861 luma_set_inter: TxbSet,
13862 chroma_set: TxbSet,
13863 luma_tx: usize,
13864 chroma_tx: usize,
13865 scan_luma: &[u16],
13866 scan_chroma: &[u16],
13867 size_group: usize,
13868 allow_high_precision_mv: bool,
13869 force_integer_mv: bool,
13870 interp_fixed: Option<mc::InterpFilterKind>,
13871 enable_dual_filter: bool,
13872 tpl_frame: Option<&TplFrameArgs>,
13873 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
13874 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
13875 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
13876 // refuses (rather than silently misdecoding) the ones that pick
13877 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
13878 // wired yet.
13879 reference_select: bool,
13880 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
13881 // compound enable bits, gating `comp_group_idx`/`compound_idx`
13882 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
13883 // compound blend weights need this frame's own order hint regardless
13884 // of `use_ref_frame_mvs`.
13885 enable_masked_compound: bool,
13886 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
13887 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
13888 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
13889 // and before `read_motion_mode` on the single-ref path below, gated by
13890 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
13891 // every mode this single-ref branch can produce is already in
13892 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
13893 // (inter+intra blended prediction unimplemented) rather than a
13894 // mis-decode.
13895 enable_interintra_compound: bool,
13896 enable_jnt_comp: bool,
13897 order_hint_bits: u32,
13898 order_hint: u32,
13899 ref_order_hints: [u32; 7],
13900 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
13901 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
13902 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
13903 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
13904 // when this is `true` (every block this decoder reaches is >= 8x8, so
13905 // `is_comp_ref_allowed` never gates it further); a `true` result forces
13906 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
13907 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
13908 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
13909 skip_mode_present: bool,
13910 skip_mode_frame: [u8; 2],
13911 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
13912 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
13913 switchable_motion_mode: bool,
13914 allow_warped_motion: bool,
13915 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
13916 // as a square 32x32 block, which over-reads a residual unless coded
13917 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
13918 reject_residual: bool,
13919 // lane-partitions r1: the strip's own true width/height in pixels --
13920 // `side` keeps governing every syntax/CDF/prediction-buffer decision
13921 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
13922 // the final pixel write and this block's own neighbour-context stamp
13923 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
13924 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
13925 // for every existing (square) caller.
13926 write_w: usize,
13927 write_h: usize,
13928 // lane-screen r2: this frame header's own `allow_screen_content_tools`
13929 // bit, threaded to the intra-sub-block branch below -- libaom's
13930 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
13931 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
13932 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
13933 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
13934 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
13935 // under the same `av1_allow_palette` gate as the key-frame path.
13936 allow_screen_content_tools: bool,
13937 // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) --
13938 // compared against each reference's stored picture width to decide
13939 // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary
13940 // stride-1 one (`mc::predict_with_filters`) applies per reference, and to
13941 // refuse (rather than mis-decode) the warp/OBMC/interintra/compound
13942 // combinations that don't implement scaled MC yet.
13943 frame_width: usize,
13944) -> Result<()> {
13945 let (r, c) = at;
13946 // lane-inter8 r2: the inter side bands are mi-granular; this block's own
13947 // above/left neighbour is the mi cell at its top-left corner (libaom
13948 // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads
13949 // exactly what it read before.
13950 let (rmi, cmi) = (r * (SUB / MI), c * (SUB / MI));
13951 let (px, py) = (c * SUB, r * SUB);
13952 let (cpx, cpy) = (px / 2, py / 2);
13953 let chroma_side = side / 2;
13954 let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2);
13955
13956 if std::env::var_os("EC_AV1_TELL").is_some() {
13957 eprintln!(
13958 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
13959 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
13960 );
13961 }
13962 let skip_mode_ctx =
13963 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
13964 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
13965 // MSAC tell so it can be diffed against an equivalent hook in libaom's
13966 // own `read_skip_mode`/`av1_get_skip_mode_context`.
13967 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
13968 eprintln!(
13969 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
13970 dec.debug_bitpos()
13971 );
13972 }
13973 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
13974 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
13975 let (seg_mi_r, seg_mi_c) = (r * SUB_MI as usize, c * SUB_MI as usize);
13976 let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
13977 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
13978 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
13979 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
13980 eprintln!(
13981 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
13982 dec.debug_bitpos()
13983 );
13984 }
13985 if skip_mode {
13986 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
13987 }
13988
13989 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
13990 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
13991 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
13992 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
13993 maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
13994 maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
13995 // lane-warp r5: see `reject_residual` -- a square-block decode of a
13996 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
13997 // motion_mode/warp symbol), so gate here before any further read.
13998 if reject_residual && !skip {
13999 return Err(unsupported(
14000 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
14001 ));
14002 }
14003
14004 let (has_above, has_left) = (
14005 r > neighbours.tile_row0_mi / (SUB / MI),
14006 c > neighbours.tile_col0_mi / (SUB / MI),
14007 );
14008 let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]);
14009 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
14010 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
14011 if std::env::var_os("EC_TRACE_MODE").is_some() {
14012 eprintln!(
14013 "EC_MODE mi_row={} mi_col={} rng={}",
14014 r * SUB_MI as usize,
14015 c * SUB_MI as usize,
14016 dec.debug_state().0
14017 );
14018 }
14019 if std::env::var_os("EC_AV1_TELL").is_some() {
14020 eprintln!(
14021 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
14022 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
14023 );
14024 }
14025
14026 let mode_for_tx;
14027 let uv_predict_mode;
14028 let (luma_grid, u_grid, v_grid);
14029 let block_filter;
14030 let ref_frame_for_lf;
14031 let globalmv_for_lf;
14032 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
14033 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
14034 // common `record_inter` call below (which would otherwise stamp the
14035 // single-ref ALTREF-special-case default over it).
14036 let mut compound_ctx: Option<(i8, u8, u8)> = None;
14037 // lane-txselect: `read_block_tx_size`'s leaf transform units (spec
14038 // 5.11.17), `Some` only when this block's var-tx tree resolved to more
14039 // than one luma transform -- read back by the residual loop, the
14040 // coefficient-context write-back and the loop-filter grid fill below.
14041 let mut vartx_leaves: Option<Vec<(usize, usize, usize)>> = None;
14042 let at_mi = (r * (SUB / MI), c * (SUB / MI));
14043 if is_inter {
14044 let above_nbr = has_above.then(|| NeighbourRef {
14045 is_inter: above_inter,
14046 ref0: if above_inter {
14047 neighbours.above_ref[cmi]
14048 } else {
14049 0
14050 },
14051 ref1: neighbours.above_ref1[cmi],
14052 uni: neighbours.above_ref1[cmi]
14053 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[cmi], r1)),
14054 });
14055 let left_nbr = has_left.then(|| NeighbourRef {
14056 is_inter: left_inter,
14057 ref0: if left_inter {
14058 neighbours.left_ref[rmi]
14059 } else {
14060 0
14061 },
14062 ref1: neighbours.left_ref1[rmi],
14063 uni: neighbours.left_ref1[rmi]
14064 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
14065 });
14066 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
14067 eprintln!(
14068 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
14069 dec.debug_bitpos()
14070 );
14071 }
14072 let is_compound =
14073 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
14074 if is_compound {
14075 let (ref0, ref1) = if skip_mode {
14076 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
14077 } else {
14078 read_compound_ref_frames(
14079 dec,
14080 cdfs,
14081 above_nbr,
14082 left_nbr,
14083 neighbours.above_ref[cmi],
14084 neighbours.left_ref[rmi],
14085 )
14086 };
14087 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
14088 // lane-rect r2: true footprint, mirroring the single-ref path below.
14089 let bw4 = write_w / 4;
14090 let bh4 = write_h / 4;
14091 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
14092 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
14093 // below, just one `get_relative_dist` per reference.
14094 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
14095 field: t.field,
14096 cur_offset_0: crate::motion_field::get_relative_dist(
14097 t.order_hint_bits,
14098 t.order_hint,
14099 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
14100 ),
14101 cur_offset_1: crate::motion_field::get_relative_dist(
14102 t.order_hint_bits,
14103 t.order_hint,
14104 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
14105 ),
14106 allow_high_precision_mv,
14107 });
14108 let gm_table = build_gm_mv_table(
14109 global_motion,
14110 mi_row,
14111 mi_col,
14112 bw4,
14113 bh4,
14114 allow_high_precision_mv,
14115 force_integer_mv,
14116 );
14117 let comp_stack = crate::mvstack::find_mv_stack_compound(
14118 grid,
14119 mi_row,
14120 mi_col,
14121 bw4,
14122 bh4,
14123 (ref0, ref1),
14124 mi_cols as usize,
14125 mi_rows as usize,
14126 sign_bias_table,
14127 &gm_table,
14128 comp_tpl,
14129 );
14130 let compound_mode = if skip_mode {
14131 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
14132 } else {
14133 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
14134 };
14135 let (mv0, mv1) = assign_compound_mv(
14136 dec,
14137 cdfs,
14138 &comp_stack,
14139 compound_mode,
14140 allow_high_precision_mv,
14141 force_integer_mv,
14142 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
14143 );
14144 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
14145 // spec `is_nontrans_global_motion`: ALL active refs' models must
14146 // be non-TRANSLATION (IDENTITY counts) for the compound block's
14147 // interp-filter read to be suppressed.
14148 let gm_nontrans = is_globalmv
14149 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
14150 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
14151 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
14152 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
14153 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
14154 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
14155 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
14156 // the write extent below, so recompute the size bound from
14157 // `side` here (the block's own size, what libaom's `bsize`
14158 // is).
14159 let is_global_mv0 = is_globalmv
14160 && side >= 8
14161 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1;
14162 let is_global_mv1 = is_globalmv
14163 && side >= 8
14164 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1;
14165 // libaom `av1_init_warp_params` + `allow_warp`'s
14166 // `global_warp_allowed` branch, run once per reference for a
14167 // compound block exactly as for a single-ref one (reconinter.c
14168 // `build_inter_predictors_8x8_and_bigger` loops over `ref` and
14169 // calls `av1_init_warp_params` inside the loop) -- WARPED_CAUSAL
14170 // never reaches here (spec 5.11.27 / libaom `read_motion_mode`:
14171 // `has_second_ref` returns SIMPLE_TRANSLATION), so the local-warp
14172 // arm of `allow_warp` is dead on this path and only the global
14173 // one applies. `force_integer_mv` short-circuits
14174 // `av1_init_warp_params` before `allow_warp`.
14175 let compound_warp = |ref_frame: i8, eligible: bool| {
14176 if eligible
14177 && !force_integer_mv
14178 && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid
14179 {
14180 crate::warp::global_warp_params(
14181 global_motion[(ref_frame - LAST_FRAME) as usize].params,
14182 )
14183 } else {
14184 None
14185 }
14186 };
14187 let warp0 = compound_warp(ref0, is_global_mv0);
14188 let warp1 = compound_warp(ref1, is_global_mv1);
14189 if warp0.is_some() || warp1.is_some() {
14190 COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1));
14191 }
14192 // spec `get_ref_filter_type`: matches when EITHER of the
14193 // neighbour's two references equals this block's own ref0 --
14194 // `above_ref1`/`left_ref1` is the neighbour's real second
14195 // reference (`record_compound_ctx`) when it was itself a
14196 // compound block; checking `above_ref`/`left_ref` alone drops a
14197 // real filter match down to the "no neighbour" sentinel
14198 // whenever the shared reference sits in the neighbour's SECOND
14199 // slot (lane-av1idx r2).
14200 let above_filter_ctx = if neighbours.above_ref[cmi] == ref0
14201 || neighbours.above_ref1[cmi] == Some(ref0)
14202 {
14203 neighbours.above_filter[cmi]
14204 } else {
14205 [3, 3]
14206 };
14207 let left_filter_ctx = if neighbours.left_ref[rmi] == ref0
14208 || neighbours.left_ref1[rmi] == Some(ref0)
14209 {
14210 neighbours.left_filter[rmi]
14211 } else {
14212 [3, 3]
14213 };
14214 globalmv_for_lf = is_globalmv;
14215 ref_frame_for_lf = ref0;
14216 mode_for_tx = 0;
14217 uv_predict_mode = DC_PRED;
14218 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
14219 // `neighbours`) must be stamped with the block's true footprint
14220 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
14221 // NEXT strip's own rows/cols before it decodes, corrupting
14222 // every later mvstack scan that reads this cell back.
14223 for dr in 0..bh4 {
14224 for dc in 0..bw4 {
14225 grid.set(
14226 mi_row + dr,
14227 mi_col + dc,
14228 MiInfo {
14229 is_inter: true,
14230 ref_frame: ref0,
14231 ref_frame1: Some(ref1),
14232 mv1: Some(mv1),
14233 mv: mv0,
14234 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
14235 size: bw4,
14236 size_h: bh4,
14237 // libaom `is_global_mv_block`: per-ref-slot, mode
14238 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
14239 // own gm model > TRANSLATION (IDENTITY excluded
14240 // too -- the two-predicate trap, distinct from
14241 // `gm_nontrans` above which allows IDENTITY).
14242 is_global_mv0,
14243 is_global_mv1,
14244 },
14245 );
14246 }
14247 }
14248 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
14249 // masked compound / distance-weighted compound are actually
14250 // enabled for this stream -- `is_any_masked_compound_used_here`
14251 // is `true` for every block size this decoder ever reaches
14252 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
14253 // there), so the gate reduces to the sequence header bit; kept
14254 // as an explicit call so a future smaller block size is not
14255 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
14256 let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side);
14257 let comp_group_idx = if !skip_mode
14258 && enable_masked_compound
14259 && is_any_masked_compound_used_here(side)
14260 {
14261 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
14262 } else {
14263 0
14264 };
14265 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
14266 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
14267 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
14268 // when `comp_group_idx == 1`.
14269 let mut diffwtd_mask_type: Option<u8> = None;
14270 let mut wedge_mask: Option<&'static [u8]> = None;
14271 if comp_group_idx == 1 {
14272 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
14273 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
14274 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
14275 // `av1_wedge_params_lookup`) is true for every square bsize
14276 // this leaf reaches (8x8/16x16/32x32 all have
14277 // `wedge_types > 0`), so `compound_type` always reads a real
14278 // symbol here -- no alphabet collapse to worry about at this
14279 // block-size family.
14280 // lane-mcomp64 r1: `av1_is_wedge_used` is false at 64x64
14281 // (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`),
14282 // so libaom's `read_compound_type` (decodemv.c 1634-1656)
14283 // writes NO `compound_type` symbol there and INFERS
14284 // `COMPOUND_DIFFWTD` -- only the 1-bit `mask_type` literal
14285 // follows. `None` here is exactly that inferred arm.
14286 let wedge_bsize = match side {
14287 8 => Some(3),
14288 16 => Some(6),
14289 32 => Some(9),
14290 _ => None,
14291 };
14292 let compound_type = match wedge_bsize {
14293 Some(b) => dec.symbol(&mut cdfs.compound_type[b]),
14294 None => 1,
14295 };
14296 if let Some(wedge_bsize) = wedge_bsize.filter(|_| compound_type == 0) {
14297 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
14298 // verified vs independent C dump (wedge.rs).
14299 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
14300 let wedge_sign = dec.literal(1);
14301 WEDGE_HITS.with(|c| c.set(c.get() + 1));
14302 wedge_mask = Some(
14303 crate::wedge::wedge_masks()
14304 .codebook(side)
14305 .mask(wedge_sign as usize, wedge_index as usize),
14306 );
14307 } else {
14308 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
14309 let mask_type = dec.literal(1);
14310 diffwtd_mask_type = Some(mask_type as u8);
14311 if wedge_bsize.is_none() {
14312 DIFFWTD_INFERRED_HITS.with(|c| c.set(c.get() + 1));
14313 }
14314 }
14315 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
14316 }
14317 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
14318 // called this a `predict_compound_intermediate`/`combine_compound`
14319 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
14320 // unmasking and running the real gates
14321 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
14322 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
14323 // shows the plain-average blend is bit-exact *most of the time*
14324 // -- `combine_compound`'s two-shift-in-one round2 was proven
14325 // algebraically identical to libaom's separate
14326 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
14327 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
14328 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
14329 // the common case a lag-in-frames GOP's hidden altref frames
14330 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
14331 // for several consecutive frames.
14332 //
14333 // The real defect a live gate run isolated (seed 49,
14334 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
14335 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
14336 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
14337 // byte; decode-order frame 2 -- same shape, same zero MV, only
14338 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
14339 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
14340 // Every later frame up through decode-order 9 also mismatches,
14341 // *including* frame 8, whose four blocks are back to
14342 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
14343 // math is wrong" (that block's own math is proven exact) in
14344 // favour of "the picture sitting in some DPB slot is already
14345 // wrong by the time frame 2 reads it, and the corruption
14346 // propagates through refresh_frame_flags into every later
14347 // reference regardless of which named ref a later block picks".
14348 // Frames 10 through 18 (once the GOP's lineage stops tracing
14349 // back through the bad slot) are bit-exact again. This points at
14350 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
14351 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
14352 // indexing feeding `dist_wtd_comp_weight_assign`) around
14353 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
14354 // mc.rs. Not isolated further within lane-av1blend's budget --
14355 // refuse by name rather than ship a blend that is right only
14356 // sometimes. Ceiling: r13/r14's MC plumbing above this line
14357 // stays -- only the plain-average reconstruct is masked off
14358 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
14359 // per decode-order frame (which slot each `Frame` OBU refreshes,
14360 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
14361 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
14362 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
14363 // frame 2.
14364 //
14365 // r2 (fresh fixture, seed 45, same recipe -- the original r1
14366 // fixture is gitignored and could not be regenerated byte-exact):
14367 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
14368 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
14369 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
14370 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
14371 // is forced 0 on every non-key `show_existing_frame`) turned up
14372 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
14373 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
14374 // isolated a *different, smaller* shape than r1's: decode-order
14375 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
14376 // compound block) is the first to diverge from ffmpeg (worst
14377 // delta 1, luma only, clustered at 32-pixel block edges) even
14378 // though BOTH its compound inputs -- the key frame and
14379 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
14380 // itself proven bit-exact: it is later re-shown via
14381 // `show_existing_frame` and matches ffmpeg exactly) -- are
14382 // independently pixel-exact, and the blend arithmetic is the
14383 // same proven-exact formula. That rules out "wrong slot"/"stale
14384 // picture" for this fixture: the inputs are right, so the defect
14385 // is in decode-order frame 3's *own* per-block decode (entropy
14386 // desync from compound-CDF adaptation carried across a slot, or
14387 // the compound mode/MV read itself) -- not in `ref_slots`/
14388 // `refresh_frame_flags`. Not isolated further within budget.
14389 // Upgrade: bisect decode-order frame 3's tile decode against a
14390 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
14391 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
14392 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
14393 // -- the pre-deblock dump frame-index alignment between this
14394 // crate and that aomdec build is NOT 1:1 on this fixture (23
14395 // dumps here vs 24 there), so calibrate that first.
14396 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
14397 // against an instrumented aomdec build (frame-index alignment
14398 // recalibrated via content-hash matching rather than the raw
14399 // dump count -- the keyframe never calls a pre-deblock dump at
14400 // all, since only `decode_inter_frame_tile` does, which is the
14401 // whole "23 vs 24" gap, not a real bug).
14402 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
14403 // seed 45) is still the first divergence: PRE-deblock differs
14404 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
14405 // luma pixels, clustered where its two compound inputs' pixel
14406 // values disagree by more than a couple of levels -- both
14407 // inputs (the keyframe and decode-order frame 2's own picture)
14408 // are independently proven bit-exact (pre- and post-deblock)
14409 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
14410 // matches this decoder's block loop exactly for every block in
14411 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
14412 // every mismatching pixel against `key`/`bwd` (both known-exact)
14413 // picks out `w0=9, w1=7` for the majority (525/846) with zero
14414 // matches for the plain average this decoder actually emits or
14415 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
14416 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
14417 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
14418 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
14419 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
14420 // decoder's own `dist_wtd_comp_weight_assign` was independently
14421 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
14422 // by hand for these distances and gives the same `(9, 7)`).
14423 // `get_comp_index_context` was checked line-for-line against
14424 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
14425 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
14426 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
14427 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
14428 // `default_compound_idx_cdfs` value-for-value; the read is
14429 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
14430 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
14431 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
14432 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
14433 // either -- some blocks in this frame plausibly decode a
14434 // genuinely different (correct, context-dependent) compound_idx
14435 // than block (0,0)'s own -- so this is not simply "always wrong
14436 // the same way": table/context/gate are all individually
14437 // verified correct, yet the decoded VALUE at this specific
14438 // symbol is wrong at least once in this frame. Not isolated
14439 // further within budget. Upgrade: instrument `dec.symbol`'s own
14440 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
14441 // trace fields) immediately before and after the `compound_idx`
14442 // read specifically, not just the surrounding mode/mv/skip
14443 // trace which does match -- the desync (if any) is local to
14444 // this one read, not a wider stream desync.
14445 //
14446 // r5 (this round): the `resolve_interp_filter` call used to sit
14447 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
14448 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
14449 // `read_compound_type`, not before, so that was a genuine
14450 // ordering bug for a Switchable-filter frame (moved below, past
14451 // the `compound_ctx = Some(...)` line). It does NOT explain this
14452 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
14453 // header carries a *fixed* interpolation filter
14454 // (`interp_fixed = Some(Regular)`, confirmed live via a
14455 // one-off dump), so `resolve_interp_filter` never read a symbol
14456 // in either position -- zero bits moved, decoded values
14457 // unchanged before and after the reorder. Kept anyway: it is a
14458 // real spec-order fix for the next Switchable-filter compound
14459 // stream, independently correct regardless of this fixture.
14460 //
14461 // Also ruled out this round: comparing this crate's own
14462 // `SymbolDecoder::debug_bitpos()` against aomdec's
14463 // `aom_reader_tell()` at the block boundary is NOT a valid
14464 // desync probe -- they are different quantities (raw consumed
14465 // input bits vs. an entropy-cost estimate that advances without
14466 // a literal byte fetch), so equal/unequal bitpos proves nothing
14467 // either way. Do not repeat that comparison; instead trace
14468 // `range`/`value` (this crate) against libaom's own internal
14469 // `dif`/`rng` (needs new instrumentation in both) immediately
14470 // after each read *upstream* of this one in the same block:
14471 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
14472 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
14473 // and the DRL loop. All of those independently decoded the SAME
14474 // values this crate and aomdec both show (ref0=1, ref1=5, mode
14475 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
14476 // miscomputation can still decode the identical symbol value off
14477 // a slightly different CDF, narrowing `range` by a different
14478 // amount than aomdec without changing the decoded value itself,
14479 // and only surface as a wrong decode a few reads later exactly
14480 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
14481 // table were independently re-verified again this round and are
14482 // still correct; the four candidates above were not re-audited
14483 // this round. Refusing here (rather than shipping a value-exact-
14484 // most-of-the-time blend) until one of them is found wrong.
14485 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
14486 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
14487 // comp_bwdref* context reads -- kept, real fix). Unmasking on
14488 // that fix alone and running the wide gate sweep (many seeds,
14489 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
14490 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
14491 // cq-level=45) still mismatches roughly half the time, at
14492 // different frames each run for the SAME seed -- aomenc's own
14493 // cpu-used=0 RD search is run-to-run nondeterministic (noted
14494 // above), so this is a second, still-unfound compound_idx defect,
14495 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
14496 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
14497 // either) already flagged more than one bug here. Re-masking:
14498 // do not ship a blend that is right only sometimes.
14499 // lane-av1idx r1: fixed one real bug this round
14500 // (`switchable_interp_ctx` never folded in libaom's
14501 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
14502 // interp_filter context -- kept). Pinned
14503 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
14504 // gate) still mismatches after that fix (decode-order frame 8
14505 // first, small deltas, worst 1-2, propagating through later
14506 // frames via DPB reference) -- a second, still-unfound bug.
14507 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
14508 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
14509 // for the next round's starting point.
14510 // lane-maskcomp r2: `compound_idx` is only read when
14511 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
14512 // (wedge/diffwtd) block never also carries a distance-weighted
14513 // split. This gate was missing before r2 (dead code: the masked
14514 // path always refused earlier, so it never executed with
14515 // `comp_group_idx == 1` in practice).
14516 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
14517 && !skip_mode
14518 && enable_jnt_comp
14519 {
14520 let idx_ctx = get_comp_index_context(
14521 neighbours,
14522 (rmi, cmi),
14523 side,
14524 order_hint_bits,
14525 order_hint,
14526 ref_order_hints[(ref0 - LAST_FRAME) as usize],
14527 ref_order_hints[(ref1 - LAST_FRAME) as usize],
14528 );
14529 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
14530 if idx == 1 {
14531 (8, 8, 1u8)
14532 } else {
14533 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
14534 order_hint_bits,
14535 order_hint,
14536 ref_order_hints[(ref0 - LAST_FRAME) as usize],
14537 ref_order_hints[(ref1 - LAST_FRAME) as usize],
14538 );
14539 (fwd, bck, 0u8)
14540 }
14541 } else {
14542 (8, 8, 1u8)
14543 };
14544 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
14545 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
14546 eprintln!(
14547 "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={}",
14548 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
14549 );
14550 }
14551
14552 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
14553 // comes AFTER `read_compound_type` (the `comp_group_idx`/
14554 // `compound_idx` reads just above), not before -- moved here
14555 // (lane-av1blend r5) from its old position ahead of those reads,
14556 // which stole their bits for a Switchable-filter compound block
14557 // and desynced every symbol read after it in the tile.
14558 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
14559 // filter is derived (Regular), never read -- same
14560 // conditional-read contract as the WARPED_CAUSAL suppression on
14561 // the single-ref path below.
14562 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
14563 dec,
14564 cdfs,
14565 interp_fixed,
14566 enable_dual_filter,
14567 gm_nontrans || skip_mode,
14568 above_filter_ctx,
14569 left_filter_ctx,
14570 true,
14571 );
14572 block_filter = resolved_filter;
14573
14574 // lane-scaledref r1: each compound tap scales INDEPENDENTLY off
14575 // its own stored reference's luma width (spec 7.11.3.3 derives
14576 // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds
14577 // one `scale_factors` per `ref_frame`), so the two taps can carry
14578 // different ratios in the same block. `REF_NO_SCALE` reduces
14579 // `predict_compound_intermediate`'s walk to the ordinary
14580 // stride-1 one, so the unscaled case is unchanged.
14581 let scale0 = mc::scale_factor(py0.width, frame_width);
14582 let scale1 = mc::scale_factor(py1.width, frame_width);
14583 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
14584 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
14585 }
14586 // lane-scaledref r2: the MIXED case -- one tap scaled, the other
14587 // not -- is the one an all-frames-scaled recipe never produces,
14588 // and the one a single shared scale factor would get wrong.
14589 if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) {
14590 MIXED_SCALE_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
14591 }
14592
14593 let mut inter0_y = vec![0i32; side * side];
14594 mc::predict_compound_intermediate(
14595 &py0.data,
14596 py0.width,
14597 py0.true_width,
14598 py0.true_height,
14599 mv_to_q4(px, mv0.1, true),
14600 mv_to_q4(py, mv0.0, true),
14601 scale0,
14602 side,
14603 side,
14604 h_filter,
14605 v_filter,
14606 &mut inter0_y,
14607 );
14608 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
14609 // translational tap (libaom `av1_warp_plane` with
14610 // `conv_params->is_compound`); the blend below is unchanged.
14611 if let Some(wp) = &warp0 {
14612 crate::warp::warp_affine_compound(
14613 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
14614 py0.width as i32, &mut inter0_y, px as i32, py as i32, side as i32,
14615 side as i32, side as i32, 0, 0,
14616 );
14617 }
14618 let mut inter1_y = vec![0i32; side * side];
14619 mc::predict_compound_intermediate(
14620 &py1.data,
14621 py1.width,
14622 py1.true_width,
14623 py1.true_height,
14624 mv_to_q4(px, mv1.1, true),
14625 mv_to_q4(py, mv1.0, true),
14626 scale1,
14627 side,
14628 side,
14629 h_filter,
14630 v_filter,
14631 &mut inter1_y,
14632 );
14633 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
14634 // translational tap (libaom `av1_warp_plane` with
14635 // `conv_params->is_compound`); the blend below is unchanged.
14636 if let Some(wp) = &warp1 {
14637 crate::warp::warp_affine_compound(
14638 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
14639 py1.width as i32, &mut inter1_y, px as i32, py as i32, side as i32,
14640 side as i32, side as i32, 0, 0,
14641 );
14642 }
14643 let mut pred_y = vec![0u16; side * side];
14644 let mut diffwtd_mask_y = Vec::new();
14645 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
14646 // the wedge codebook lookup (comp_group_idx==1's two mutually
14647 // exclusive branches) -- same [`mc::blend_masked_compound`] call
14648 // either way, only the mask source differs.
14649 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
14650 diffwtd_mask_y = vec![0u8; side * side];
14651 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
14652 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
14653 Some(diffwtd_mask_y.as_slice())
14654 } else {
14655 wedge_mask
14656 };
14657 if let Some(mask_y) = mask_y {
14658 mc::blend_masked_compound(
14659 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
14660 );
14661 } else {
14662 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
14663 }
14664
14665 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
14666 mc::predict_compound_intermediate(
14667 &pu0.data,
14668 pu0.width,
14669 pu0.true_width,
14670 pu0.true_height,
14671 mv_to_q4(cpx, mv0.1, false),
14672 mv_to_q4(cpy, mv0.0, false),
14673 scale0,
14674 chroma_side,
14675 chroma_side,
14676 h_filter,
14677 v_filter,
14678 &mut inter0_u,
14679 );
14680 // `av1_init_warp_params` bails when the PLANE's block is
14681 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
14682 // block of an 8x8 luma block stays translational.
14683 if let Some(wp) = &warp0 {
14684 if chroma_side >= 8 {
14685 crate::warp::warp_affine_compound(
14686 wp, &pu0.data, pu0.true_width as i32, pu0.true_height as i32,
14687 pu0.width as i32, &mut inter0_u, cpx as i32, cpy as i32,
14688 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
14689 );
14690 }
14691 }
14692 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
14693 mc::predict_compound_intermediate(
14694 &pu1.data,
14695 pu1.width,
14696 pu1.true_width,
14697 pu1.true_height,
14698 mv_to_q4(cpx, mv1.1, false),
14699 mv_to_q4(cpy, mv1.0, false),
14700 scale1,
14701 chroma_side,
14702 chroma_side,
14703 h_filter,
14704 v_filter,
14705 &mut inter1_u,
14706 );
14707 // `av1_init_warp_params` bails when the PLANE's block is
14708 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
14709 // block of an 8x8 luma block stays translational.
14710 if let Some(wp) = &warp1 {
14711 if chroma_side >= 8 {
14712 crate::warp::warp_affine_compound(
14713 wp, &pu1.data, pu1.true_width as i32, pu1.true_height as i32,
14714 pu1.width as i32, &mut inter1_u, cpx as i32, cpy as i32,
14715 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
14716 );
14717 }
14718 }
14719 let mut pred_u = vec![0u16; chroma_side * chroma_side];
14720 if let Some(mask_y) = mask_y {
14721 mc::blend_masked_compound(
14722 &inter0_u,
14723 &inter1_u,
14724 mask_y,
14725 side,
14726 chroma_side,
14727 chroma_side,
14728 true,
14729 &mut pred_u,
14730 );
14731 } else {
14732 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
14733 }
14734
14735 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
14736 mc::predict_compound_intermediate(
14737 &pv0.data,
14738 pv0.width,
14739 pv0.true_width,
14740 pv0.true_height,
14741 mv_to_q4(cpx, mv0.1, false),
14742 mv_to_q4(cpy, mv0.0, false),
14743 scale0,
14744 chroma_side,
14745 chroma_side,
14746 h_filter,
14747 v_filter,
14748 &mut inter0_v,
14749 );
14750 // `av1_init_warp_params` bails when the PLANE's block is
14751 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
14752 // block of an 8x8 luma block stays translational.
14753 if let Some(wp) = &warp0 {
14754 if chroma_side >= 8 {
14755 crate::warp::warp_affine_compound(
14756 wp, &pv0.data, pv0.true_width as i32, pv0.true_height as i32,
14757 pv0.width as i32, &mut inter0_v, cpx as i32, cpy as i32,
14758 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
14759 );
14760 }
14761 }
14762 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
14763 mc::predict_compound_intermediate(
14764 &pv1.data,
14765 pv1.width,
14766 pv1.true_width,
14767 pv1.true_height,
14768 mv_to_q4(cpx, mv1.1, false),
14769 mv_to_q4(cpy, mv1.0, false),
14770 scale1,
14771 chroma_side,
14772 chroma_side,
14773 h_filter,
14774 v_filter,
14775 &mut inter1_v,
14776 );
14777 // `av1_init_warp_params` bails when the PLANE's block is
14778 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
14779 // block of an 8x8 luma block stays translational.
14780 if let Some(wp) = &warp1 {
14781 if chroma_side >= 8 {
14782 crate::warp::warp_affine_compound(
14783 wp, &pv1.data, pv1.true_width as i32, pv1.true_height as i32,
14784 pv1.width as i32, &mut inter1_v, cpx as i32, cpy as i32,
14785 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
14786 );
14787 }
14788 }
14789 let mut pred_v = vec![0u16; chroma_side * chroma_side];
14790 if let Some(mask_y) = mask_y {
14791 mc::blend_masked_compound(
14792 &inter0_v,
14793 &inter1_v,
14794 mask_y,
14795 side,
14796 chroma_side,
14797 chroma_side,
14798 true,
14799 &mut pred_v,
14800 );
14801 } else {
14802 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
14803 }
14804
14805 vartx_leaves = read_block_tx_size(
14806 dec,
14807 cdfs,
14808 neighbours,
14809 at_mi,
14810 side,
14811 (mi_cols as usize, mi_rows as usize),
14812 true,
14813 skip,
14814 )?
14815 .1;
14816 if skip {
14817 y.reconstruct_mc_rect(
14818 px,
14819 py,
14820 side,
14821 write_w,
14822 write_h,
14823 &pred_y,
14824 &vec![0i32; side * side],
14825 );
14826 u.reconstruct_mc_rect(
14827 cpx,
14828 cpy,
14829 chroma_side,
14830 write_chroma_w,
14831 write_chroma_h,
14832 &pred_u,
14833 &vec![0i32; chroma_side * chroma_side],
14834 );
14835 v.reconstruct_mc_rect(
14836 cpx,
14837 cpy,
14838 chroma_side,
14839 write_chroma_w,
14840 write_chroma_h,
14841 &pred_v,
14842 &vec![0i32; chroma_side * chroma_side],
14843 );
14844 luma_grid = vec![0i32; side * side];
14845 u_grid = vec![0i32; chroma_side * chroma_side];
14846 v_grid = vec![0i32; chroma_side * chroma_side];
14847 } else {
14848 let around = neighbours.around(at, side);
14849 let luma_tx_type;
14850 if let Some(leaves) = vartx_leaves.clone() {
14851 // spec 5.11.17's transform tree, leaf by leaf in the order
14852 // `read_var_tx_size` coded it: each unit reads its own
14853 // coefficients against the neighbour magnitudes the
14854 // earlier units already wrote, and reconstructs over its
14855 // own slice of the block's motion-compensated predictor.
14856 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
14857 let mut first_tx_type = TxType::DctDct;
14858 for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() {
14859 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
14860 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14861 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
14862 for rr in 0..tx_px {
14863 let start = (row * MI + rr) * side + col * MI;
14864 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
14865 }
14866 let scan = default_scan(tx_px);
14867 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
14868 let (tu_grid, tu_tx_type) = read_inter_plane(
14869 dec,
14870 cdfs,
14871 inter_txbset_for(tx_px, reduced),
14872 &scan,
14873 0,
14874 neighbours.around_mi(tu_mi, tx_px)[0],
14875 mode_for_tx,
14876 y,
14877 tu_px,
14878 tu_py,
14879 tx_px,
14880 base_q_idx,
14881 &tu_pred,
14882 None,
14883 Some(tu_skip_ctx),
14884 )?;
14885 if idx == 0 {
14886 first_tx_type = tu_tx_type;
14887 }
14888 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
14889 }
14890 // `av1_get_tx_type`'s chroma lookup scales the chroma
14891 // position back to luma, so an inter block's chroma
14892 // inherits the *first* (top-left) luma unit's coded type.
14893 luma_tx_type = first_tx_type;
14894 luma_grid = vec![0i32; side * side];
14895 } else {
14896 (luma_grid, luma_tx_type) = read_inter_plane(
14897 dec,
14898 cdfs,
14899 luma_set_inter,
14900 scan_luma,
14901 0,
14902 around[0],
14903 mode_for_tx,
14904 y,
14905 px,
14906 py,
14907 side,
14908 base_q_idx,
14909 &pred_y,
14910 None,
14911 None,
14912 )?;
14913 }
14914 u_grid = read_inter_plane(
14915 dec,
14916 cdfs,
14917 chroma_set,
14918 scan_chroma,
14919 1,
14920 around[1],
14921 mode_for_tx,
14922 u,
14923 cpx,
14924 cpy,
14925 chroma_side,
14926 base_q_idx,
14927 &pred_u,
14928 Some(luma_tx_type),
14929 None,
14930 )?
14931 .0;
14932 v_grid = read_inter_plane(
14933 dec,
14934 cdfs,
14935 chroma_set,
14936 scan_chroma,
14937 2,
14938 around[2],
14939 mode_for_tx,
14940 v,
14941 cpx,
14942 cpy,
14943 chroma_side,
14944 base_q_idx,
14945 &pred_v,
14946 Some(luma_tx_type),
14947 None,
14948 )?
14949 .0;
14950 }
14951 } else {
14952 let ref_frame =
14953 read_single_ref(
14954 dec,
14955 cdfs,
14956 neighbours.above_ref[cmi],
14957 neighbours.above_ref1[cmi],
14958 neighbours.left_ref[rmi],
14959 neighbours.left_ref1[rmi],
14960 );
14961 ref_frame_for_lf = ref_frame;
14962 if std::env::var_os("EC_AV1_TELL").is_some() {
14963 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
14964 eprintln!(
14965 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
14966 dec.debug_bitpos(), dec.debug_state().0
14967 );
14968 }
14969 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
14970 // stacked defects (lf_level ref/mode-delta forwarding, the
14971 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
14972 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
14973 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
14974 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
14975 // widens this from GOLDEN alone to every reference `read_single_ref`
14976 // can name.
14977 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
14978 (ref_y, ref_u, ref_v)
14979 } else {
14980 match other_refs[ref_frame as usize] {
14981 Some((ry, ru, rv)) => (ry, ru, rv),
14982 None => {
14983 return Err(unsupported(
14984 "a reference frame selected with no picture at this frame's own \
14985 ref_frame_idx slot for it",
14986 ));
14987 }
14988 }
14989 };
14990
14991 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
14992 // lane-rect r2: the mv stack must be queried with the block's
14993 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
14994 // xd->width/xd->height, not a square guess) -- `write_w`/
14995 // `write_h` already name the true HORZ/VERT/HORZ_B strip
14996 // footprint (r1's plumbing), so derive bw4/bh4 from those
14997 // instead of the old `side`-square (HORZ_B-only) heuristic.
14998 let bw4 = write_w / 4;
14999 let bh4 = write_h / 4;
15000 // spec 7.10.2.8: only reached when the frame header set
15001 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
15002 // otherwise) -- `cur_offset_0` is this query block's own resolved
15003 // `ref_frame`'s distance from the current frame (spec 7.9.3),
15004 // recomputed per block since different blocks pick different refs.
15005 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
15006 field: t.field,
15007 cur_offset_0: crate::motion_field::get_relative_dist(
15008 t.order_hint_bits,
15009 t.order_hint,
15010 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
15011 ),
15012 allow_high_precision_mv,
15013 });
15014 let gm_table = build_gm_mv_table(
15015 global_motion,
15016 mi_row,
15017 mi_col,
15018 bw4,
15019 bh4,
15020 allow_high_precision_mv,
15021 force_integer_mv,
15022 );
15023 let stack = find_mv_stack_with_sign_bias(
15024 grid,
15025 mi_row,
15026 mi_col,
15027 bw4,
15028 bh4,
15029 ref_frame,
15030 mi_cols as usize,
15031 mi_rows as usize,
15032 sign_bias_table,
15033 &gm_table,
15034 tpl,
15035 );
15036 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
15037 let mut is_globalmv = false;
15038 let (mv, is_new_mv) = if !not_new {
15039 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
15040 // read at most two `drl_mode` bits, one per stack entry past the
15041 // first, stopping at the first `0`. The chosen index selects
15042 // which stack entry `read_mv`'s base predictor comes from
15043 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
15044 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
15045 let mut idx = 0usize;
15046 while idx < 2 && stack.entries.len() > idx + 1 {
15047 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
15048 break;
15049 }
15050 idx += 1;
15051 }
15052 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
15053 (
15054 read_mv(
15055 dec,
15056 &mut cdfs.mv_comp,
15057 &mut cdfs.mv_joint,
15058 base_mv,
15059 allow_high_precision_mv,
15060 force_integer_mv,
15061 ),
15062 true,
15063 )
15064 } else {
15065 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
15066 is_globalmv = !not_zero;
15067 let mv = if !not_zero {
15068 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
15069 // computed at this block's own position in `gm_table`.
15070 gm_table[(ref_frame - LAST_FRAME) as usize]
15071 } else {
15072 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
15073 if nearest {
15074 stack.nearest_mv
15075 } else {
15076 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
15077 // at 1): read at most two more `drl_mode` bits, one per stack
15078 // entry past the second, stopping at the first `0`.
15079 // `drl_ctx[idx]` is the context between `entries[idx]` and
15080 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
15081 // exactly the pair this index is choosing between.
15082 let mut idx = 1usize;
15083 while idx < 3 && stack.entries.len() > idx + 1 {
15084 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
15085 break;
15086 }
15087 idx += 1;
15088 }
15089 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
15090 }
15091 };
15092 (mv, false)
15093 };
15094 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
15095 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
15096 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
15097 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
15098 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
15099 // TRANSLATION -- IDENTITY counts here -- gating the interp
15100 // filter suppress below). Do NOT unify these.
15101 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
15102 let min_bw_bh4 = bw4.min(bh4);
15103 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
15104 let gm_nontrans =
15105 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
15106 if std::env::var_os("EC_AV1_TELL").is_some() {
15107 eprintln!(
15108 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
15109 dec.debug_bitpos(), dec.debug_state().0
15110 );
15111 }
15112 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
15113 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
15114 // right after `assign_mv` and before `read_motion_mode` below --
15115 // libaom's own sequential order. `is_interintra_allowed_bsize`
15116 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
15117 // single-ref path: `is_interintra_allowed_ref` always holds here
15118 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
15119 // `is_interintra_allowed_mode` always holds (every mode this
15120 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
15121 // `SINGLE_INTER_MODE_START..END` by construction).
15122 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
15123 let mut interintra_mode: Option<u8> = None;
15124 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
15125 if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) {
15126 let bsize_group = if side == 16 { 2 } else { 3 };
15127 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
15128 if interintra {
15129 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
15130 // then -- gated on block size ALONE, never the
15131 // `enable_interintra_wedge` seq bit -- the wedge flag
15132 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
15133 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
15134 let wedge_bsize = if side == 16 { 6 } else { 9 };
15135 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
15136 if wedge {
15137 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
15138 // ADAPTING CDF symbol over the same `wedge_bsize` row;
15139 // NO sign symbol follows -- libaom fixes
15140 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
15141 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
15142 WII_HITS.with(|c| c.set(c.get() + 1));
15143 wedge_mask = Some((
15144 crate::wedge::wedge_masks()
15145 .codebook(side)
15146 .mask(0, wedge_index as usize),
15147 side,
15148 ));
15149 } else {
15150 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
15151 }
15152 interintra_mode = Some(ii);
15153 }
15154 }
15155 if std::env::var_os("EC_AV1_TELL").is_some() {
15156 eprintln!(
15157 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
15158 dec.debug_bitpos(), dec.debug_state().0
15159 );
15160 }
15161 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
15162 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
15163 // placed right after MV assignment and before the switchable
15164 // interp filter read below (`read_mb_interp_filter`, decodemv.c
15165 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
15166 // (`reconinter.h`) reduces, for every block this single-ref path
15167 // reaches, to "does an inter neighbour border the above row or
15168 // left column": `is_motion_variation_allowed_bsize` always holds
15169 // (`side` is never below 16px on this path), `ref_frame[1] !=
15170 // INTRA_FRAME` always holds (no interintra reader here),
15171 // `is_motion_variation_allowed_compound` always holds (this is
15172 // the single-ref branch), and `is_global_mv_block` never
15173 // triggers (this decoder's global motion is always `IDENTITY`,
15174 // so its warp `type` is never `> TRANSLATION`). A stream with
15175 // `allow_warped_motion=1` is refused right at an eligible block
15176 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
15177 // not ported, so this decoder cannot tell a real
15178 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
15179 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
15180 // the header allows warp -- reading the wrong alphabet desyncs
15181 // the tile.
15182 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
15183 // fails libaom's `is_motion_variation_allowed_compound`: the
15184 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
15185 let motion_mode_eligible = switchable_motion_mode
15186 && !skip_mode
15187 && interintra_mode.is_none()
15188 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
15189 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
15190 .is_empty())
15191 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
15192 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
15193 // mv reads no motion_mode/obmc symbol at all -- implicit
15194 // SIMPLE_TRANSLATION.
15195 && !(is_global_mv_block && !force_integer_mv);
15196 let mut obmc_selected = false;
15197 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
15198 // *and* the local warp estimate is valid (`!wm_params.invalid`,
15199 // `av1_find_projection`) -- an invalid estimate falls back to
15200 // this block's own translational mv, same as any other block
15201 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
15202 // fallback here since this decoder's global motion is always
15203 // IDENTITY).
15204 let mut warp_params: Option<crate::warp::WarpParams> = None;
15205 // Tracks the SYMBOL value, not projection validity: libaom's
15206 // `av1_is_interp_needed` suppresses the interp-filter read for
15207 // `motion_mode == WARPED_CAUSAL` even when the projection later
15208 // falls back to translation. Its third suppressor,
15209 // `is_nontrans_global_motion`, matches our unconditional
15210 // `is_globalmv` only because this decoder codes global motion as
15211 // IDENTITY (non-TRANSLATION) and never reads switchable filters
15212 // below 8x8 -- porting TRANSLATION global motion must add the
15213 // wmtype check here.
15214 let mut warped_selected = false;
15215 if motion_mode_eligible {
15216 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
15217 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
15218 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
15219 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
15220 // strip motion_mode read diverged on the square row.
15221 let bsize_idx = if write_w == write_h {
15222 (write_w.trailing_zeros() - 3) as usize
15223 } else if write_w == 16 {
15224 4
15225 } else {
15226 5
15227 };
15228 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
15229 // instead of the 2-symbol `obmc_cdf` exactly when
15230 // `num_proj_ref >= 1` under `allow_warped_motion`.
15231 // lane-scaledref r2 + lane-fimv r1: libaom
15232 // `motion_mode_allowed` (`blockd.h:1484`) requires BOTH
15233 // `!av1_is_scaled(block_ref_scale_factors[0])` and
15234 // `!xd->cur_frame_force_integer_mv` for WARPED_CAUSAL --
15235 // under a scaled reference (superres) OR on a frame whose
15236 // header set `force_integer_mv` (screen content) the block
15237 // reads the 2-symbol `obmc_cdf`, never the 3-symbol
15238 // `motion_mode_cdf`. Reading the wrong alphabet here narrows
15239 // the arithmetic coder by the wrong amount and predicts the
15240 // rest of the tile off a diverged state: silently wrong
15241 // pixels, not a desync error. `force_integer_mv` is the
15242 // per-frame value (spec 5.9.2: coded per frame only when
15243 // `seq_force_integer_mv == SELECT_INTEGER_MV`, threaded from
15244 // `FrameHeader::force_integer_mv`).
15245 // libaom `av1_is_scaled` is `x_scale_fp != REF_NO_SCALE ||
15246 // y_scale_fp != REF_NO_SCALE`; the y half is unreachable here
15247 // because a reference whose height differs from this frame's
15248 // true size is refused before any tile decodes ("a reference
15249 // picture whose height does not match this frame's own true
15250 // size", ~14681). Whoever lifts that refusal adds the y term.
15251 let ref_is_scaled =
15252 mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE;
15253 let proj_ok = num_proj_ref(
15254 grid,
15255 mi_row,
15256 mi_col,
15257 bw4,
15258 bh4,
15259 mi_cols as usize,
15260 mi_rows as usize,
15261 ref_frame,
15262 ) >= 1;
15263 let warp_eligible =
15264 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
15265 if allow_warped_motion && proj_ok && ref_is_scaled {
15266 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1));
15267 }
15268 if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv {
15269 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
15270 }
15271 if warp_eligible {
15272 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
15273 match mode {
15274 0 => {}
15275 1 => {
15276 obmc_selected = true;
15277 OBMC_HITS.with(|c| c.set(c.get() + 1));
15278 }
15279 _ => {
15280 warped_selected = true;
15281 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
15282 let mut samples = find_samples(
15283 grid,
15284 mi_row,
15285 mi_col,
15286 bw4,
15287 bh4,
15288 mi_cols as usize,
15289 mi_rows as usize,
15290 ref_frame,
15291 );
15292 if std::env::var_os("EC_WARP_DEBUG").is_some() {
15293 eprintln!(
15294 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
15295 samples.len()
15296 );
15297 for (i, s) in samples.iter().enumerate() {
15298 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
15299 }
15300 }
15301 if samples.len() > 1 {
15302 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
15303 }
15304 warp_params = crate::warp::find_projection(
15305 &samples,
15306 // lane-rect r2: the block's TRUE dims -- a
15307 // 32x16 strip's model center is not a
15308 // 32x32's (aom av1_find_projection bw/bh).
15309 write_w as i32,
15310 write_h as i32,
15311 mv.1,
15312 mv.0,
15313 mi_row as i32,
15314 mi_col as i32,
15315 );
15316 if std::env::var_os("EC_WARP_DEBUG").is_some() {
15317 eprintln!(
15318 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
15319 samples.len(), mv.0, mv.1, warp_params
15320 );
15321 for (i, s) in samples.iter().enumerate() {
15322 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
15323 }
15324 }
15325 }
15326 }
15327 } else {
15328 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
15329 if obmc_selected {
15330 OBMC_HITS.with(|c| c.set(c.get() + 1));
15331 }
15332 }
15333 }
15334 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
15335 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
15336 // libaom's `av1_init_warp_params` runs for every inter
15337 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
15338 // reachable when `warp_params` is still `None` here: a block
15339 // that read (and got) local `WARPED_CAUSAL` above already has
15340 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
15341 // checks FIRST and short-circuits on -- the global branch is an
15342 // `else if`, never layered on top. `is_global_mv_block` already
15343 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
15344 // >=8px both dims, matching `av1_init_warp_params`'s
15345 // `block_height < 8 || block_width < 8` early return) and, via
15346 // `motion_mode_eligible`'s own suppression above, the
15347 // `force_integer_mv` case never reads a motion_mode symbol at
15348 // all -- checked again here directly since this branch fires
15349 // independent of `motion_mode_eligible`.
15350 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
15351 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
15352 warp_params = crate::warp::global_warp_params(gm_ref.params);
15353 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
15354 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
15355 }
15356 }
15357 if std::env::var_os("EC_AV1_TELL").is_some() {
15358 eprintln!(
15359 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
15360 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
15361 );
15362 }
15363 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
15364 // this block's switchable_interp context when that neighbour coded
15365 // the SAME reference frame this block is about to read -- a
15366 // different-ref neighbour reads as "no neighbour" ([3, 3], the
15367 // sentinel `Neighbours::new` already seeds unset slots with),
15368 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
15369 // block next to a LAST_FRAME one inherits that neighbour's filter
15370 // choice into its own context, corrupting the symbol it reads.
15371 // lane-av1idx r2: also match on the neighbour's SECOND reference
15372 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
15373 // see the 16x16 leaf's own comment above for the spec citation.
15374 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
15375 || neighbours.above_ref1[cmi] == Some(ref_frame)
15376 {
15377 neighbours.above_filter[cmi]
15378 } else {
15379 [3, 3]
15380 };
15381 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
15382 || neighbours.left_ref1[rmi] == Some(ref_frame)
15383 {
15384 neighbours.left_filter[rmi]
15385 } else {
15386 [3, 3]
15387 };
15388 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
15389 dec,
15390 cdfs,
15391 interp_fixed,
15392 enable_dual_filter,
15393 gm_nontrans || warped_selected,
15394 above_filter_ctx,
15395 left_filter_ctx,
15396 false,
15397 );
15398 block_filter = resolved_filter;
15399 globalmv_for_lf = is_globalmv;
15400 if std::env::var_os("EC_AV1_TELL").is_some() {
15401 eprintln!(
15402 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
15403 dec.debug_bitpos(), dec.debug_state().0
15404 );
15405 }
15406 if std::env::var_os("EC_AV1_TRACE").is_some() {
15407 eprintln!(
15408 "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={}",
15409 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()
15410 );
15411 }
15412 // lane-rect r2: see the compound path's matching comment above --
15413 // `grid` must be stamped with the block's true bh4/bw4 span, not
15414 // a square `bw4`x`bw4` guess.
15415 for dr in 0..bh4 {
15416 for dc in 0..bw4 {
15417 grid.set(
15418 mi_row + dr,
15419 mi_col + dc,
15420 MiInfo {
15421 is_inter: true,
15422 ref_frame,
15423 // An interintra block records ref_frame[1] ==
15424 // INTRA_FRAME (0): warp-sample gathering
15425 // (libaom av1_findSamples, mvref_common.c:1155)
15426 // requires ref_frame[1] == NONE_FRAME, so such a
15427 // neighbour must not donate samples or count in
15428 // num_proj_ref.
15429 ref_frame1: interintra_mode.map(|_| 0),
15430 mv1: None,
15431 mv,
15432 is_new_mv,
15433 size: bw4,
15434 size_h: bh4,
15435 is_global_mv0: is_global_mv_block,
15436 is_global_mv1: false,
15437 },
15438 );
15439 }
15440 }
15441 mode_for_tx = 0;
15442 uv_predict_mode = DC_PRED;
15443
15444 // lane-superres r9: spec 7.11.3.3's x_scale_fp comes from LUMA
15445 // widths only (r8's derivation) and applies unchanged to the
15446 // chroma calls below (their x_q4 is already in the chroma
15447 // plane's own pixel units). `mc::predict_scaled` has no warp/OBMC
15448 // /interintra counterpart -- those three combinations are refused
15449 // by name instead of silently sampling a scaled reference wrong
15450 // (warp_params/obmc_selected/interintra_mode are all resolved by
15451 // this point, every symbol for this block already read).
15452 let luma_scale = mc::scale_factor(py_ref.width, frame_width);
15453 if luma_scale != mc::REF_NO_SCALE {
15454 // lane-scaledref r1: libaom `allow_warp`
15455 // (av1/common/reconinter.c:41) suppresses BOTH local and
15456 // global warp under a scaled reference and predicts
15457 // translationally instead -- that fallback is implemented
15458 // below, but the one real aomenc stream this round found
15459 // that reaches it (`--enable-warped-motion=1`,
15460 // `--superres-denominator=16`, seed 47) still mismatches
15461 // ffmpeg at frame 2 luma, so the case stays refused by name
15462 // until it has a green gate rather than shipping wrong
15463 // pixels behind a lifted refusal.
15464 if warp_params.is_some() {
15465 SCALED_WARP_FALLBACK_HITS.with(|c| c.set(c.get() + 1));
15466 return Err(unsupported(
15467 "warp prediction with a scaled reference (superres, unimplemented)",
15468 ));
15469 }
15470 if obmc_selected {
15471 SCALED_OBMC_HITS.with(|c| c.set(c.get() + 1));
15472 }
15473 if interintra_mode.is_some() {
15474 SCALED_INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
15475 }
15476 }
15477
15478 let mut pred_y = vec![0u16; side * side];
15479 let mut pred_u = vec![0u16; chroma_side * chroma_side];
15480 let mut pred_v = vec![0u16; chroma_side * chroma_side];
15481 if luma_scale == mc::REF_NO_SCALE {
15482 mc::predict_with_filters(
15483 &py_ref.data,
15484 py_ref.width,
15485 py_ref.true_width,
15486 py_ref.true_height,
15487 mv_to_q4(px, mv.1, true),
15488 mv_to_q4(py, mv.0, true),
15489 side,
15490 side,
15491 h_filter,
15492 v_filter,
15493 &mut pred_y,
15494 );
15495 mc::predict_with_filters(
15496 &pu_ref.data,
15497 pu_ref.width,
15498 pu_ref.true_width,
15499 pu_ref.true_height,
15500 mv_to_q4(cpx, mv.1, false),
15501 mv_to_q4(cpy, mv.0, false),
15502 chroma_side,
15503 chroma_side,
15504 h_filter,
15505 v_filter,
15506 &mut pred_u,
15507 );
15508 mc::predict_with_filters(
15509 &pv_ref.data,
15510 pv_ref.width,
15511 pv_ref.true_width,
15512 pv_ref.true_height,
15513 mv_to_q4(cpx, mv.1, false),
15514 mv_to_q4(cpy, mv.0, false),
15515 chroma_side,
15516 chroma_side,
15517 h_filter,
15518 v_filter,
15519 &mut pred_v,
15520 );
15521 } else {
15522 mc::predict_scaled(
15523 &py_ref.data,
15524 py_ref.width,
15525 py_ref.true_width,
15526 py_ref.true_height,
15527 mv_to_q4(px, mv.1, true),
15528 mv_to_q4(py, mv.0, true),
15529 luma_scale,
15530 side,
15531 side,
15532 h_filter,
15533 v_filter,
15534 &mut pred_y,
15535 );
15536 mc::predict_scaled(
15537 &pu_ref.data,
15538 pu_ref.width,
15539 pu_ref.true_width,
15540 pu_ref.true_height,
15541 mv_to_q4(cpx, mv.1, false),
15542 mv_to_q4(cpy, mv.0, false),
15543 luma_scale,
15544 chroma_side,
15545 chroma_side,
15546 h_filter,
15547 v_filter,
15548 &mut pred_u,
15549 );
15550 mc::predict_scaled(
15551 &pv_ref.data,
15552 pv_ref.width,
15553 pv_ref.true_width,
15554 pv_ref.true_height,
15555 mv_to_q4(cpx, mv.1, false),
15556 mv_to_q4(cpy, mv.0, false),
15557 luma_scale,
15558 chroma_side,
15559 chroma_side,
15560 h_filter,
15561 v_filter,
15562 &mut pred_v,
15563 );
15564 }
15565
15566 // lane-scaledref r1: libaom `allow_warp` (av1/common/reconinter.c:41)
15567 // opens with `if (av1_is_scaled(sf)) return 0;` -- BOTH local
15568 // (`wm_params`) and global warp fall back to the translational
15569 // prediction above when the reference is scaled, even though the
15570 // motion_mode symbol was still read and warp_params still
15571 // resolved. Suppress the warp, keep every symbol read.
15572 if let Some(params) = warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE) {
15573 crate::warp::warp_affine(
15574 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
15575 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
15576 side as i32, side as i32, 0, 0,
15577 );
15578 // libaom `av1_init_warp_params` (reconinter.c): warp is
15579 // per PLANE and bails out at `block_width < 8 ||
15580 // block_height < 8`, so a plane whose own block is under
15581 // 8x8 keeps the translational prediction built above --
15582 // in 420 that is every chroma plane of a luma block below
15583 // 16x16 (lane-gmaffine r4: chroma-only mismatch of a few
15584 // levels on both 8x8-leaf motion gates).
15585 if chroma_side >= 8 {
15586 crate::warp::warp_affine(
15587 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
15588 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
15589 chroma_side as i32, chroma_side as i32, 1, 1,
15590 );
15591 crate::warp::warp_affine(
15592 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
15593 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
15594 chroma_side as i32, chroma_side as i32, 1, 1,
15595 );
15596 }
15597 }
15598
15599 if obmc_selected {
15600 obmc_blend(
15601 grid,
15602 neighbours,
15603 mi_row,
15604 mi_col,
15605 bw4,
15606 bh4,
15607 mi_rows as usize,
15608 mi_cols as usize,
15609 side,
15610 write_w,
15611 write_h,
15612 chroma_side,
15613 px,
15614 py,
15615 cpx,
15616 cpy,
15617 ref_y,
15618 ref_u,
15619 ref_v,
15620 other_refs,
15621 interp_fixed,
15622 frame_width,
15623 &mut pred_y,
15624 &mut pred_u,
15625 &mut pred_v,
15626 )?;
15627 }
15628
15629 // Mutually exclusive with warp/OBMC (motion_mode is not read for
15630 // an interintra block): blend the intra predictor over the MC
15631 // result, all planes (reconinter.c av1_build_interintra_predictor
15632 // plane loop).
15633 if let Some(ii) = interintra_mode {
15634 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
15635 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
15636 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
15637 }
15638
15639 vartx_leaves = read_block_tx_size(
15640 dec,
15641 cdfs,
15642 neighbours,
15643 at_mi,
15644 side,
15645 (mi_cols as usize, mi_rows as usize),
15646 true,
15647 skip,
15648 )?
15649 .1;
15650 if skip {
15651 y.reconstruct_mc_rect(
15652 px,
15653 py,
15654 side,
15655 write_w,
15656 write_h,
15657 &pred_y,
15658 &vec![0i32; side * side],
15659 );
15660 u.reconstruct_mc_rect(
15661 cpx,
15662 cpy,
15663 chroma_side,
15664 write_chroma_w,
15665 write_chroma_h,
15666 &pred_u,
15667 &vec![0i32; chroma_side * chroma_side],
15668 );
15669 v.reconstruct_mc_rect(
15670 cpx,
15671 cpy,
15672 chroma_side,
15673 write_chroma_w,
15674 write_chroma_h,
15675 &pred_v,
15676 &vec![0i32; chroma_side * chroma_side],
15677 );
15678 luma_grid = vec![0i32; side * side];
15679 u_grid = vec![0i32; chroma_side * chroma_side];
15680 v_grid = vec![0i32; chroma_side * chroma_side];
15681 } else {
15682 let around = neighbours.around(at, side);
15683 let luma_tx_type;
15684 if let Some(leaves) = vartx_leaves.clone() {
15685 // spec 5.11.17's transform tree, leaf by leaf in the order
15686 // `read_var_tx_size` coded it: each unit reads its own
15687 // coefficients against the neighbour magnitudes the
15688 // earlier units already wrote, and reconstructs over its
15689 // own slice of the block's motion-compensated predictor.
15690 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
15691 let mut first_tx_type = TxType::DctDct;
15692 for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() {
15693 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
15694 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
15695 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
15696 for rr in 0..tx_px {
15697 let start = (row * MI + rr) * side + col * MI;
15698 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
15699 }
15700 let scan = default_scan(tx_px);
15701 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
15702 let (tu_grid, tu_tx_type) = read_inter_plane(
15703 dec,
15704 cdfs,
15705 inter_txbset_for(tx_px, reduced),
15706 &scan,
15707 0,
15708 neighbours.around_mi(tu_mi, tx_px)[0],
15709 mode_for_tx,
15710 y,
15711 tu_px,
15712 tu_py,
15713 tx_px,
15714 base_q_idx,
15715 &tu_pred,
15716 None,
15717 Some(tu_skip_ctx),
15718 )?;
15719 if idx == 0 {
15720 first_tx_type = tu_tx_type;
15721 }
15722 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
15723 }
15724 // `av1_get_tx_type`'s chroma lookup scales the chroma
15725 // position back to luma, so an inter block's chroma
15726 // inherits the *first* (top-left) luma unit's coded type.
15727 luma_tx_type = first_tx_type;
15728 luma_grid = vec![0i32; side * side];
15729 } else {
15730 (luma_grid, luma_tx_type) = read_inter_plane(
15731 dec,
15732 cdfs,
15733 luma_set_inter,
15734 scan_luma,
15735 0,
15736 around[0],
15737 mode_for_tx,
15738 y,
15739 px,
15740 py,
15741 side,
15742 base_q_idx,
15743 &pred_y,
15744 None,
15745 None,
15746 )?;
15747 }
15748 u_grid = read_inter_plane(
15749 dec,
15750 cdfs,
15751 chroma_set,
15752 scan_chroma,
15753 1,
15754 around[1],
15755 mode_for_tx,
15756 u,
15757 cpx,
15758 cpy,
15759 chroma_side,
15760 base_q_idx,
15761 &pred_u,
15762 Some(luma_tx_type),
15763 None,
15764 )?
15765 .0;
15766 v_grid = read_inter_plane(
15767 dec,
15768 cdfs,
15769 chroma_set,
15770 scan_chroma,
15771 2,
15772 around[2],
15773 mode_for_tx,
15774 v,
15775 cpx,
15776 cpy,
15777 chroma_side,
15778 base_q_idx,
15779 &pred_v,
15780 Some(luma_tx_type),
15781 None,
15782 )?
15783 .0;
15784 }
15785 }
15786 } else {
15787 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
15788 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
15789 // its own true-width/height edge/predict math, unlike the inter
15790 // skip path above (which only needed a clipped write of an
15791 // already-square-predicted buffer). Named refusal instead of a
15792 // silently wrong square-shaped intra prediction.
15793 if write_w != side || write_h != side {
15794 return Err(unsupported(
15795 "an intra-coded HORZ/VERT strip needs rectangular intra prediction \
15796 this decoder does not code yet",
15797 ));
15798 }
15799 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
15800 if mode >= 13 {
15801 return Err(unsupported(
15802 "an intra mode this decoder does not code (round 2)",
15803 ));
15804 }
15805 if (V_PRED..=D67_PRED).contains(&mode) {
15806 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
15807 if angle != ANGLE_DELTA_ZERO {
15808 return Err(unsupported(
15809 "a nonzero angle delta (this encoder never writes one)",
15810 ));
15811 }
15812 }
15813 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
15814 if (9..=12).contains(&uv_mode) {
15815 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
15816 }
15817 let alpha = if uv_mode == DC_PRED {
15818 None
15819 } else if uv_mode == UV_CFL_PRED {
15820 Some(read_cfl_alphas(dec, cdfs))
15821 } else {
15822 None
15823 };
15824 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
15825 // the angle-delta question, same as [`read_intra_mode`]'s own copy
15826 // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
15827 // `else` branch below is exact for it either way.
15828 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
15829 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
15830 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
15831 } else {
15832 0
15833 };
15834 if angle_delta_uv != 0 {
15835 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
15836 }
15837 uv_predict_mode = if uv_mode == UV_CFL_PRED {
15838 DC_PRED
15839 } else {
15840 uv_mode
15841 };
15842 // lane-chroma r4: same chroma edge-filter-strength neighbour check
15843 // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
15844 // neighbour's own `uv_mode`, not the luma one.
15845 let smooth_neighbor_uv =
15846 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
15847 // `read_palette_mode_info` (decodemv.c:567, called from
15848 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
15849 // gating and same corner-cut as `read_intra_mode`'s own copy above
15850 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
15851 // safe since a nonzero neighbour `palette_size` would already have
15852 // refused the decode that produced it.
15853 if allow_screen_content_tools
15854 && let Some(bsize_ctx) = palette_bsize_ctx(side)
15855 {
15856 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
15857 return Err(unsupported(
15858 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
15859 ));
15860 }
15861 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
15862 return Err(unsupported(
15863 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
15864 ));
15865 }
15866 }
15867 mode_for_tx = mode;
15868 block_filter = [3, 3];
15869 ref_frame_for_lf = 0;
15870 globalmv_for_lf = false;
15871 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
15872 for dr in 0..side / 4 {
15873 for dc in 0..side / 4 {
15874 grid.set(
15875 mi_row + dr,
15876 mi_col + dc,
15877 MiInfo {
15878 is_inter: false,
15879 ref_frame: -1,
15880 ref_frame1: None,
15881 mv1: None,
15882 mv: (0, 0),
15883 is_new_mv: false,
15884 size: side / 4,
15885 size_h: side / 4,
15886 is_global_mv0: false,
15887 is_global_mv1: false,
15888 },
15889 );
15890 }
15891 }
15892
15893 read_block_tx_size(
15894 dec,
15895 cdfs,
15896 neighbours,
15897 at_mi,
15898 side,
15899 (mi_cols as usize, mi_rows as usize),
15900 false,
15901 skip,
15902 )?;
15903 let reach = Reach::of(side, px, py, y.width, y.height);
15904 if skip {
15905 y.reconstruct(
15906 px,
15907 py,
15908 side,
15909 mode,
15910 0,
15911 reach,
15912 &vec![0i32; side * side],
15913 None,
15914 None,
15915 false,
15916 );
15917 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
15918 u.reconstruct(
15919 cpx,
15920 cpy,
15921 chroma_side,
15922 uv_predict_mode,
15923 angle_delta_uv,
15924 reach,
15925 &vec![0i32; chroma_side * chroma_side],
15926 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
15927 None,
15928 smooth_neighbor_uv,
15929 );
15930 v.reconstruct(
15931 cpx,
15932 cpy,
15933 chroma_side,
15934 uv_predict_mode,
15935 angle_delta_uv,
15936 reach,
15937 &vec![0i32; chroma_side * chroma_side],
15938 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
15939 None,
15940 smooth_neighbor_uv,
15941 );
15942 luma_grid = vec![0i32; side * side];
15943 u_grid = vec![0i32; chroma_side * chroma_side];
15944 v_grid = vec![0i32; chroma_side * chroma_side];
15945 } else {
15946 let around = neighbours.around(at, side);
15947 luma_grid = read_plane(
15948 dec,
15949 cdfs,
15950 luma_set_intra,
15951 scan_luma,
15952 0,
15953 around[0],
15954 mode,
15955 mode,
15956 0,
15957 reach,
15958 y,
15959 px,
15960 py,
15961 side,
15962 luma_tx,
15963 base_q_idx,
15964 None,
15965 None,
15966 None,
15967 false,
15968 )?;
15969 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
15970 u_grid = read_plane(
15971 dec,
15972 cdfs,
15973 chroma_set,
15974 scan_chroma,
15975 1,
15976 around[1],
15977 mode,
15978 uv_predict_mode,
15979 angle_delta_uv,
15980 reach,
15981 u,
15982 cpx,
15983 cpy,
15984 chroma_side,
15985 chroma_tx,
15986 base_q_idx,
15987 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
15988 None,
15989 None,
15990 smooth_neighbor_uv,
15991 )?;
15992 v_grid = read_plane(
15993 dec,
15994 cdfs,
15995 chroma_set,
15996 scan_chroma,
15997 2,
15998 around[2],
15999 mode,
16000 uv_predict_mode,
16001 angle_delta_uv,
16002 reach,
16003 v,
16004 cpx,
16005 cpy,
16006 chroma_side,
16007 chroma_tx,
16008 base_q_idx,
16009 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
16010 None,
16011 None,
16012 smooth_neighbor_uv,
16013 )?;
16014 }
16015 }
16016 // lane-comppin r9: end-of-block checkpoint -- everything between
16017 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
16018 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
16019 // equivalent post-content point (added at the matching call site)
16020 // narrows the ladder to this block's own tail instead of the next
16021 // block's partition read.
16022 if std::env::var_os("EC_AV1_TELL").is_some() {
16023 eprintln!(
16024 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
16025 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
16026 );
16027 }
16028 if vartx_leaves.is_some() {
16029 // Plane 0 is already correct per transform unit
16030 // ([`Neighbours::record_mi_luma`] above); this writes everything else
16031 // [`Neighbours::record_rect`] would (a var-tx block is always square,
16032 // so `write_w == write_h == side`).
16033 neighbours.record_split_luma(at, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]);
16034 } else {
16035 neighbours.record_rect(
16036 at,
16037 write_w,
16038 write_h,
16039 mode_for_tx,
16040 uv_predict_mode,
16041 &[luma_grid, u_grid, v_grid],
16042 );
16043 }
16044 neighbours.record_inter_rect(
16045 at,
16046 write_w,
16047 write_h,
16048 skip,
16049 is_inter,
16050 ref_frame_for_lf,
16051 block_filter,
16052 skip_mode,
16053 );
16054 if let Some((ref1, group_idx, idx)) = compound_ctx {
16055 neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx);
16056 }
16057 neighbours.fill_skip_grid_rect(
16058 (r * (SUB / MI), c * (SUB / MI)),
16059 write_w / MI,
16060 write_h / MI,
16061 skip,
16062 );
16063 neighbours.fill_lf_grid_rect(
16064 (r * (SUB / MI), c * (SUB / MI)),
16065 write_w / MI,
16066 write_h / MI,
16067 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
16068 // single-scalar corner-cut deblocked the strip seam with the wrong
16069 // edge length (1-px chroma drift on rect-flake-1 f17+).
16070 write_w as u8,
16071 write_h as u8,
16072 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
16073 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
16074 if globalmv_for_lf {
16075 -ref_frame_for_lf
16076 } else {
16077 ref_frame_for_lf
16078 },
16079 );
16080 // lane-txselect: a var-tx block's deblock edges follow its own transform
16081 // units, not the block. Chroma still reads `tx_h_grid / 2` (the block's
16082 // uv transform is not split) -- a known corner-cut of this round.
16083 if let Some(leaves) = &vartx_leaves {
16084 for &(row, col, tx_px) in leaves {
16085 neighbours.fill_lf_grid_rect(
16086 (at_mi.0 + row, at_mi.1 + col),
16087 tx_px / MI,
16088 tx_px / MI,
16089 tx_px as u8,
16090 tx_px as u8,
16091 if globalmv_for_lf {
16092 -ref_frame_for_lf
16093 } else {
16094 ref_frame_for_lf
16095 },
16096 );
16097 }
16098 }
16099 Ok(())
16100}
16101
16102/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
16103/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
16104/// exact symbol order: its own skip flag, intra/inter choice and (when
16105/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
16106/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
16107/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
16108/// same as [`decode_leaf8`]'s coefficient layer but with
16109/// motion-compensated prediction instead of intra prediction when inter.
16110/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
16111/// skip/intra-inter context, overridden by `prev_leaf` exactly as
16112/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
16113/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
16114/// and intra/inter choice, for the next leaf or the caller's final
16115/// write-back.
16116#[allow(clippy::too_many_arguments)]
16117fn decode_inter_block8(
16118 dec: &mut SymbolDecoder,
16119 cdfs: &mut Cdfs,
16120 neighbours: &mut Neighbours,
16121 grid: &mut MiGrid,
16122 mi_cols: u32,
16123 mi_rows: u32,
16124 outer_at: (usize, usize),
16125 leaf_mi: (usize, usize),
16126 y: &mut PlaneBuf,
16127 u: &mut PlaneBuf,
16128 v: &mut PlaneBuf,
16129 ref_y: &PlaneBuf,
16130 ref_u: &PlaneBuf,
16131 ref_v: &PlaneBuf,
16132 other_refs: &RefSlots,
16133 base_q_idx: u8,
16134 scan8: &[u16],
16135 scan4: &[u16],
16136 allow_high_precision_mv: bool,
16137 force_integer_mv: bool,
16138 // lane-gmaffine r1: this frame header's own `global_motion` table (spec
16139 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` -- same table
16140 // [`decode_inter_block`] takes, threaded here so the 8x8 leaf can code
16141 // `GLOBALMV` (`gm_get_motion_vector`), fill its mv stack's missing
16142 // candidates with the gm mv (gm r6's root cause) and build a global
16143 // warp prediction.
16144 global_motion: &[ec_av1_syntax::WarpParams; 7],
16145 // lane-gmaffine r1: this sequence header's own `enable_dual_filter` bit,
16146 // for the leaf's own `read_mb_interp_filter` below.
16147 enable_dual_filter: bool,
16148 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
16149 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
16150 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
16151 // context uses that same approximation.
16152 reference_select: bool,
16153 enable_masked_compound: bool,
16154 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
16155 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
16156 // drops the `side` check entirely.
16157 enable_interintra_compound: bool,
16158 enable_jnt_comp: bool,
16159 order_hint_bits: u32,
16160 order_hint: u32,
16161 ref_order_hints: [u32; 7],
16162 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
16163 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
16164 // so its `skip_mode` context reuses the same [`SUB`]-grid
16165 // `above_skip_mode[cmi]`/`left_skip_mode[rmi]` the enclosing 16x16 slot
16166 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
16167 // just above).
16168 skip_mode_present: bool,
16169 skip_mode_frame: [u8; 2],
16170 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
16171 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
16172 reduced_tx_set: bool,
16173 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
16174 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
16175 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
16176 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
16177 // prediction is always `Regular` (documented corner-cut, `mc::predict`
16178 // has no filter param), but an OBMC neighbour can be a real 16x16+
16179 // block that DID resolve a switchable filter.
16180 interp_fixed: Option<mc::InterpFilterKind>,
16181 switchable_motion_mode: bool,
16182 allow_warped_motion: bool,
16183 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
16184 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
16185 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
16186 // `compound_ctx` local, just handed back instead of applied here (this
16187 // fn's `neighbours` recording happens once for the whole straddling
16188 // 16x16 block, after every leaf).
16189 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
16190 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
16191 // eligible (`bsize >= BLOCK_8X8`).
16192 allow_screen_content_tools: bool,
16193 // lane-inter8 r1: the leaf's mv stacks used to be built without the
16194 // frame's sign-bias table (`NO_SIGN_BIAS`), while [`decode_inter_block`]
16195 // one level up passed it -- it changes the candidate list and with it
16196 // `new_mv_ctx`/`ref_mv_ctx`, `drl_ctx` and the number of symbols read.
16197 // Measured: an 8x8 compound NEAR_NEWMV leaf desynced against aomdec's
16198 // EC_MODE ladder at exactly this block (mi 4,14 of the mandelbrot
16199 // 8x8-split gate).
16200 sign_bias_table: &SignBiasTable,
16201 // lane-inter8 r2: the frame's temporal mv field (spec 7.10.2.8), which
16202 // [`decode_inter_block`] one level up has always passed and this leaf
16203 // passed `None` for -- a `use_ref_frame_mvs` frame's stack then holds
16204 // fewer candidates here than in the reference decoder, which changes the
16205 // mode contexts AND the number of `drl_mode` bits read (class parsed
16206 // then discarded).
16207 tpl_frame: Option<&TplFrameArgs>,
16208 // lane-scaledref r1: this frame's own coded luma width (spec 7.11.3.3),
16209 // for the scaled-reference MC this leaf's own single-ref/compound/OBMC
16210 // predictions take when a stored reference was coded at another width
16211 // (`use_superres`) -- mirrors [`decode_inter_block`]'s own param.
16212 frame_width: usize,
16213) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>, [u8; 2], (i8, Option<i8>))> {
16214 const LAST_FRAME: i8 = 1;
16215 // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back
16216 // so the caller stamps them into `Neighbours` instead of the `[3, 3]`
16217 // placeholder. `[3, 3]` is the "intra neighbour, no filter" sentinel: an
16218 // OBMC blend that picks such a neighbour up feeds it to
16219 // `neighbour_filter`, which PANICS on it (`from_switchable_symbol`) --
16220 // that was the warp gate's crash, not an entropy desync. Stays `[3, 3]`
16221 // on the intra and compound paths.
16222 let mut leaf_filter_syms = [3u8; 2];
16223 // lane-gmaffine r1: this leaf's GLOBALMV vector AND the mv stack's
16224 // missing-candidate fallback both come from the frame's global motion
16225 // evaluated at THIS block's centre (gm r6's root cause).
16226 let gm_table = build_gm_mv_table(
16227 global_motion,
16228 leaf_mi.0,
16229 leaf_mi.1,
16230 2,
16231 2,
16232 allow_high_precision_mv,
16233 force_integer_mv,
16234 );
16235 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
16236 const SIZE_GROUP_8: usize = 1;
16237
16238 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
16239 let (cpx, cpy) = (px / 2, py / 2);
16240 // lane-txselect: whether this leaf's `TxMode::Select` var-tx tree took
16241 // the one split a `BLOCK_8X8` can take (`read_block_tx_size` below) --
16242 // read back by the luma residual read and the tail's neighbour/loop-filter
16243 // bookkeeping. Always `false` outside a `TxMode::Select` inter frame.
16244 let mut split8 = false;
16245 const SIDE: usize = 8;
16246 const CHROMA_SIDE: usize = 4;
16247
16248 let (r, c) = outer_at;
16249 let _ = (r, c);
16250 // lane-inter8 r2: this leaf's OWN mi cell, not the enclosing 16x16's --
16251 // leaf (mi_r, mi_c + 2)'s left neighbour is leaf (mi_r, mi_c), and the
16252 // left column of a 16x16's second leaf ROW is the previous 16x16 block's
16253 // bottom leaf, neither of which a SUB-grid slot can name.
16254 let (rmi, cmi) = leaf_mi;
16255 // lane-inter8 r2: no sibling-leaf override any more -- each leaf stamps
16256 // its own 2x2-mi span into the bands right after it decodes (the caller's
16257 // `record_inter_rect_mi`), so a plain mi read already names the correct
16258 // neighbour, including one belonging to the previous 16x16 block.
16259 let above_skip = neighbours.above_skip[cmi];
16260 let left_skip = neighbours.left_skip[rmi];
16261 let above_inter = neighbours.above_inter[cmi];
16262 let left_inter = neighbours.left_inter[rmi];
16263 let above_ref0 = neighbours.above_ref[cmi];
16264 let above_ref1 = neighbours.above_ref1[cmi];
16265 let left_ref0 = neighbours.left_ref[rmi];
16266 let left_ref1 = neighbours.left_ref1[rmi];
16267 let skip_mode_ctx =
16268 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
16269 // Same two `inter_segment_id` positions as [`decode_inter_block`]; this
16270 // leaf is always `BLOCK_8X8`, i.e. 2x2 mi.
16271 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true);
16272 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
16273 if skip_mode {
16274 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
16275 }
16276
16277 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
16278 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
16279 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false);
16280 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
16281 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
16282 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
16283 maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
16284
16285 let (has_above, has_left) = (
16286 leaf_mi.0 > neighbours.tile_row0_mi,
16287 leaf_mi.1 > neighbours.tile_col0_mi,
16288 );
16289 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
16290 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
16291 // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4,
16292 // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder
16293 // diffs line for line against a real aomdec.
16294 if std::env::var_os("EC_TRACE_MODE").is_some() {
16295 eprintln!(
16296 "EC_MODE mi_row={} mi_col={} rng={}",
16297 leaf_mi.0,
16298 leaf_mi.1,
16299 dec.debug_state().0
16300 );
16301 }
16302
16303 let mode_for_tx;
16304 let (luma_grid, u_grid, v_grid);
16305 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
16306 // lane-inter8 r1: this leaf's own resolved references, handed back so the
16307 // NEXT leaf of the same 16x16 can use them as its real above/left
16308 // neighbour (`Neighbours`' arrays only move once per 16x16 block).
16309 // `(0, None)` is intra.
16310 let mut leaf_refs: (i8, Option<i8>) = (0, None);
16311 if is_inter {
16312 if reference_select || skip_mode {
16313 // lane-inter8 r1: the REAL neighbour references, not a
16314 // `LAST_FRAME`-or-intra stand-in. `av1_get_reference_mode_context`
16315 // and `read_compound_ref_frames`' own contexts both ask whether a
16316 // neighbour is COMPOUND, so pretending every inter neighbour is
16317 // single-ref LAST picked the wrong `comp_mode` CDF row -- measured
16318 // as an 8x8 leaf reading single-ref where aomdec read compound
16319 // NEAR_NEWMV (mi 4,14).
16320 let above_nbr = has_above.then(|| NeighbourRef {
16321 is_inter: above_inter,
16322 ref0: if above_inter { above_ref0 } else { 0 },
16323 ref1: above_ref1,
16324 uni: above_ref1.is_some_and(|r1| is_uni_comp_ref(above_ref0, r1)),
16325 });
16326 let left_nbr = has_left.then(|| NeighbourRef {
16327 is_inter: left_inter,
16328 ref0: if left_inter { left_ref0 } else { 0 },
16329 ref1: left_ref1,
16330 uni: left_ref1.is_some_and(|r1| is_uni_comp_ref(left_ref0, r1)),
16331 });
16332 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
16333 let (ref0, ref1) = if skip_mode {
16334 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
16335 } else {
16336 read_compound_ref_frames(
16337 dec,
16338 cdfs,
16339 above_nbr,
16340 left_nbr,
16341 if has_above && above_inter {
16342 LAST_FRAME
16343 } else {
16344 -1
16345 },
16346 if has_left && left_inter {
16347 LAST_FRAME
16348 } else {
16349 -1
16350 },
16351 )
16352 };
16353 leaf_refs = (ref0, Some(ref1));
16354 let (mi_row, mi_col) = leaf_mi;
16355 // spec 7.10.2.8, mirroring [`decode_inter_block`]'s own
16356 // `comp_tpl` build (`use_ref_frame_mvs` frames only).
16357 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
16358 field: t.field,
16359 cur_offset_0: crate::motion_field::get_relative_dist(
16360 t.order_hint_bits,
16361 t.order_hint,
16362 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
16363 ),
16364 cur_offset_1: crate::motion_field::get_relative_dist(
16365 t.order_hint_bits,
16366 t.order_hint,
16367 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
16368 ),
16369 allow_high_precision_mv,
16370 });
16371 // lane-av1comp: this leaf path has neither a real sign-bias
16372 // table nor `tpl_frame` (see this function's own doc on the
16373 // coarse `LAST_FRAME`-or-intra neighbour approximation
16374 // already in force above), matching the plain `find_mv_stack`
16375 // (no bias, no tpl) the leaf's single-ref arm below already
16376 // uses.
16377 let comp_stack = crate::mvstack::find_mv_stack_compound(
16378 grid,
16379 mi_row,
16380 mi_col,
16381 2,
16382 2,
16383 (ref0, ref1),
16384 mi_cols as usize,
16385 mi_rows as usize,
16386 sign_bias_table,
16387 &gm_table,
16388 comp_tpl,
16389 );
16390 let compound_mode = if skip_mode {
16391 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
16392 } else {
16393 read_inter_compound_mode(
16394 dec,
16395 cdfs,
16396 comp_stack.new_mv_ctx,
16397 comp_stack.ref_mv_ctx,
16398 )
16399 };
16400 if std::env::var_os("EC_TRACE_MODE").is_some() {
16401 eprintln!(
16402 "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}",
16403 leaf_mi.0,
16404 leaf_mi.1,
16405 compound_mode + 17,
16406 comp_stack.entries.len(),
16407 comp_stack.new_mv_ctx,
16408 comp_stack.ref_mv_ctx,
16409 dec.debug_state().0
16410 );
16411 }
16412 let (mv0, mv1) = assign_compound_mv(
16413 dec,
16414 cdfs,
16415 &comp_stack,
16416 compound_mode,
16417 allow_high_precision_mv,
16418 force_integer_mv,
16419 // lane-inter8 r1: the real per-ref gm mvs, same as
16420 // [`decode_inter_block`]'s own compound arm.
16421 (
16422 gm_table[(ref0 - LAST_FRAME) as usize],
16423 gm_table[(ref1 - LAST_FRAME) as usize],
16424 ),
16425 );
16426 // lane-inter8 r3: byte-format-identical to the oracle's
16427 // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder
16428 // diffs line for line against a real aomdec.
16429 if std::env::var_os("EC_TRACE_MODE").is_some() {
16430 eprintln!(
16431 "EC_MODE_VAL mi_row={} mi_col={} mode={} ref0={} ref1={} mv0=({},{}) rng={}",
16432 leaf_mi.0,
16433 leaf_mi.1,
16434 compound_mode + 17,
16435 ref0,
16436 ref1,
16437 mv0.0,
16438 mv0.1,
16439 dec.debug_state().0
16440 );
16441 }
16442
16443 // spec 5.11.25: same gating [`decode_inter_block`]'s own
16444 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
16445 // slot -- the only granularity `Neighbours`' comp_group_idx/
16446 // compound_idx arrays track.
16447 let group_ctx = get_comp_group_idx_context(neighbours, leaf_mi, SIDE);
16448 let comp_group_idx = if !skip_mode
16449 && enable_masked_compound
16450 && is_any_masked_compound_used_here(SIDE)
16451 {
16452 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
16453 } else {
16454 0
16455 };
16456 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
16457 // leaf's own comment.
16458 let mut diffwtd_mask_type: Option<u8> = None;
16459 let mut wedge_mask: Option<&'static [u8]> = None;
16460 if comp_group_idx == 1 {
16461 // lane-maskcomp r1: see the 16x16 leaf's own comment
16462 // above -- SIDE==8 here, `wedge_bsize` index 3
16463 // (BLOCK_8X8, `wedge_types > 0`).
16464 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
16465 if compound_type == 0 {
16466 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
16467 // leaf's own comment.
16468 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
16469 let wedge_sign = dec.literal(1);
16470 WEDGE_HITS.with(|c| c.set(c.get() + 1));
16471 wedge_mask = Some(
16472 crate::wedge::wedge_masks()
16473 .codebook(SIDE)
16474 .mask(wedge_sign as usize, wedge_index as usize),
16475 );
16476 } else {
16477 let mask_type = dec.literal(1);
16478 diffwtd_mask_type = Some(mask_type as u8);
16479 }
16480 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
16481 }
16482 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
16483 // reference-slot defect as the 16x16 leaf's own mask above
16484 // (r1: falsified as an MC/blend math bug, isolated to a DPB
16485 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
16486 // that comment.
16487 // r3: same defect as the 16x16 leaf's own mask above -- see
16488 // that comment (compound_idx's decoded value, not the blend
16489 // math or reference-slot bookkeeping). r6/r7: same re-mask
16490 // as the 16x16 leaf above -- one real bug found and fixed
16491 // (mvstack.rs ref_ctx family), a second, still-unfound
16492 // compound_idx defect surfaces on the wide gate sweep.
16493 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
16494 // see that comment.
16495 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
16496 && !skip_mode
16497 && enable_jnt_comp
16498 {
16499 let idx_ctx = get_comp_index_context(
16500 neighbours,
16501 leaf_mi,
16502 SIDE,
16503 order_hint_bits,
16504 order_hint,
16505 ref_order_hints[(ref0 - LAST_FRAME) as usize],
16506 ref_order_hints[(ref1 - LAST_FRAME) as usize],
16507 );
16508 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
16509 if idx == 1 {
16510 (8, 8, 1u8)
16511 } else {
16512 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
16513 order_hint_bits,
16514 order_hint,
16515 ref_order_hints[(ref0 - LAST_FRAME) as usize],
16516 ref_order_hints[(ref1 - LAST_FRAME) as usize],
16517 );
16518 (fwd, bck, 0u8)
16519 }
16520 } else {
16521 (8, 8, 1u8)
16522 };
16523 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
16524 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
16525 eprintln!(
16526 "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={}",
16527 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
16528 );
16529 }
16530
16531 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
16532 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
16533 let scale0 = mc::scale_factor(py0.width, frame_width);
16534 let scale1 = mc::scale_factor(py1.width, frame_width);
16535 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
16536 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
16537 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
16538 }
16539
16540 for dr in 0..2 {
16541 for dc in 0..2 {
16542 grid.set(
16543 mi_row + dr,
16544 mi_col + dc,
16545 MiInfo {
16546 is_inter: true,
16547 ref_frame: ref0,
16548 ref_frame1: Some(ref1),
16549 mv1: Some(mv1),
16550 mv: mv0,
16551 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
16552 size: 2,
16553 size_h: 2,
16554 is_global_mv0: false,
16555 is_global_mv1: false,
16556 },
16557 );
16558 }
16559 }
16560 mode_for_tx = 0;
16561
16562 // lane-av1comp corner-cut, matching this leaf's single-ref
16563 // arm below (`mc::predict`'s own fixed-Regular default):
16564 // `decode_inter_block8` never resolves a switchable filter,
16565 // so both compound taps use `Regular` too.
16566 use mc::InterpFilterKind::Regular;
16567 let mut inter0_y = vec![0i32; SIDE * SIDE];
16568 mc::predict_compound_intermediate(
16569 &py0.data,
16570 py0.width,
16571 py0.true_width,
16572 py0.true_height,
16573 mv_to_q4(px, mv0.1, true),
16574 mv_to_q4(py, mv0.0, true),
16575 scale0,
16576 SIDE,
16577 SIDE,
16578 Regular,
16579 Regular,
16580 &mut inter0_y,
16581 );
16582 let mut inter1_y = vec![0i32; SIDE * SIDE];
16583 mc::predict_compound_intermediate(
16584 &py1.data,
16585 py1.width,
16586 py1.true_width,
16587 py1.true_height,
16588 mv_to_q4(px, mv1.1, true),
16589 mv_to_q4(py, mv1.0, true),
16590 scale1,
16591 SIDE,
16592 SIDE,
16593 Regular,
16594 Regular,
16595 &mut inter1_y,
16596 );
16597 let mut pred_y = vec![0u16; SIDE * SIDE];
16598 let mut diffwtd_mask_y = Vec::new();
16599 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
16600 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
16601 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
16602 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
16603 Some(diffwtd_mask_y.as_slice())
16604 } else {
16605 wedge_mask
16606 };
16607 if let Some(mask_y) = mask_y {
16608 mc::blend_masked_compound(
16609 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
16610 );
16611 } else {
16612 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
16613 }
16614
16615 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16616 mc::predict_compound_intermediate(
16617 &pu0.data,
16618 pu0.width,
16619 pu0.true_width,
16620 pu0.true_height,
16621 mv_to_q4(cpx, mv0.1, false),
16622 mv_to_q4(cpy, mv0.0, false),
16623 scale0,
16624 CHROMA_SIDE,
16625 CHROMA_SIDE,
16626 Regular,
16627 Regular,
16628 &mut inter0_u,
16629 );
16630 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16631 mc::predict_compound_intermediate(
16632 &pu1.data,
16633 pu1.width,
16634 pu1.true_width,
16635 pu1.true_height,
16636 mv_to_q4(cpx, mv1.1, false),
16637 mv_to_q4(cpy, mv1.0, false),
16638 scale1,
16639 CHROMA_SIDE,
16640 CHROMA_SIDE,
16641 Regular,
16642 Regular,
16643 &mut inter1_u,
16644 );
16645 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
16646 if let Some(mask_y) = mask_y {
16647 mc::blend_masked_compound(
16648 &inter0_u,
16649 &inter1_u,
16650 mask_y,
16651 SIDE,
16652 CHROMA_SIDE,
16653 CHROMA_SIDE,
16654 true,
16655 &mut pred_u,
16656 );
16657 } else {
16658 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
16659 }
16660
16661 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16662 mc::predict_compound_intermediate(
16663 &pv0.data,
16664 pv0.width,
16665 pv0.true_width,
16666 pv0.true_height,
16667 mv_to_q4(cpx, mv0.1, false),
16668 mv_to_q4(cpy, mv0.0, false),
16669 scale0,
16670 CHROMA_SIDE,
16671 CHROMA_SIDE,
16672 Regular,
16673 Regular,
16674 &mut inter0_v,
16675 );
16676 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16677 mc::predict_compound_intermediate(
16678 &pv1.data,
16679 pv1.width,
16680 pv1.true_width,
16681 pv1.true_height,
16682 mv_to_q4(cpx, mv1.1, false),
16683 mv_to_q4(cpy, mv1.0, false),
16684 scale1,
16685 CHROMA_SIDE,
16686 CHROMA_SIDE,
16687 Regular,
16688 Regular,
16689 &mut inter1_v,
16690 );
16691 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
16692 if let Some(mask_y) = mask_y {
16693 mc::blend_masked_compound(
16694 &inter0_v,
16695 &inter1_v,
16696 mask_y,
16697 SIDE,
16698 CHROMA_SIDE,
16699 CHROMA_SIDE,
16700 true,
16701 &mut pred_v,
16702 );
16703 } else {
16704 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
16705 }
16706
16707 split8 = read_block_tx_size(
16708 dec,
16709 cdfs,
16710 neighbours,
16711 leaf_mi,
16712 SIDE,
16713 (mi_cols as usize, mi_rows as usize),
16714 true,
16715 skip,
16716 )?
16717 .1
16718 .is_some();
16719 if skip {
16720 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
16721 u.reconstruct_mc(
16722 cpx,
16723 cpy,
16724 CHROMA_SIDE,
16725 &pred_u,
16726 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
16727 );
16728 v.reconstruct_mc(
16729 cpx,
16730 cpy,
16731 CHROMA_SIDE,
16732 &pred_v,
16733 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
16734 );
16735 luma_grid = vec![0i32; SIDE * SIDE];
16736 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16737 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16738 } else {
16739 let around = neighbours.around_mi(leaf_mi, 8);
16740 let (grid8, luma_tx_type) = read_inter_luma8(
16741 dec,
16742 cdfs,
16743 neighbours,
16744 leaf_mi,
16745 y,
16746 px,
16747 py,
16748 &pred_y,
16749 mode_for_tx,
16750 base_q_idx,
16751 scan8,
16752 scan4,
16753 reduced_tx_set,
16754 split8,
16755 )?;
16756 luma_grid = grid8;
16757 u_grid = read_inter_plane(
16758 dec,
16759 cdfs,
16760 TxbSet::Chroma4,
16761 scan4,
16762 1,
16763 around[1],
16764 mode_for_tx,
16765 u,
16766 cpx,
16767 cpy,
16768 CHROMA_SIDE,
16769 base_q_idx,
16770 &pred_u,
16771 Some(luma_tx_type),
16772 None,
16773 )?
16774 .0;
16775 v_grid = read_inter_plane(
16776 dec,
16777 cdfs,
16778 TxbSet::Chroma4,
16779 scan4,
16780 2,
16781 around[2],
16782 mode_for_tx,
16783 v,
16784 cpx,
16785 cpy,
16786 CHROMA_SIDE,
16787 base_q_idx,
16788 &pred_v,
16789 Some(luma_tx_type),
16790 None,
16791 )?
16792 .0;
16793 }
16794 // lane-inter8 r2: the COMPOUND leaf used to return here
16795 // WITHOUT the end-of-function `record_mi`/`fill_lf_grid` the
16796 // single-ref path falls through to -- so a compound 8x8 leaf
16797 // left `above_side_mi`/`left_side_mi` (the next block's
16798 // partition context), the per-plane coefficient level state
16799 // and the loop-filter grid describing whatever block was
16800 // there before. Every leaf of the gate's stream is compound,
16801 // so the 16x16 below a split block read partition ctx 0
16802 // instead of 1 and mis-read PARTITION_SPLIT as NONE.
16803 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
16804 neighbours.fill_lf_grid(
16805 leaf_mi,
16806 2,
16807 8,
16808 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
16809 );
16810 return Ok((
16811 skip,
16812 is_inter,
16813 skip_mode,
16814 compound_ctx8,
16815 leaf_filter_syms,
16816 leaf_refs,
16817 ));
16818 }
16819 }
16820 // lane-gmaffine r1: the leaf reads the FULL `single_ref` tree
16821 // ([`read_single_ref`], the same one the 16x16+ leaf uses, with the
16822 // real per-neighbour p1..p6 contexts) instead of the old three-symbol
16823 // LAST-only probe plus a refusal -- aomenc picks GOLDEN/ALTREF for
16824 // 8x8 leaves constantly, so that refusal was what every 8x8 gate
16825 // actually stopped at.
16826 let ref_frame = read_single_ref(
16827 dec,
16828 cdfs,
16829 neighbours.above_ref[cmi],
16830 neighbours.above_ref1[cmi],
16831 neighbours.left_ref[rmi],
16832 neighbours.left_ref1[rmi],
16833 );
16834 leaf_refs = (ref_frame, None);
16835 let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
16836
16837 let (mi_row, mi_col) = leaf_mi;
16838 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS
16839 // leaf's own reference (lane-gmaffine r1 taught it non-LAST refs).
16840 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
16841 field: t.field,
16842 cur_offset_0: crate::motion_field::get_relative_dist(
16843 t.order_hint_bits,
16844 t.order_hint,
16845 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
16846 ),
16847 allow_high_precision_mv,
16848 });
16849 let stack = crate::mvstack::find_mv_stack_with_sign_bias(
16850 grid,
16851 mi_row,
16852 mi_col,
16853 2,
16854 2,
16855 ref_frame,
16856 mi_cols as usize,
16857 mi_rows as usize,
16858 sign_bias_table,
16859 &gm_table,
16860 tpl,
16861 );
16862
16863 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
16864 let mut is_globalmv = false;
16865 let (mv, is_new_mv) = if !not_new {
16866 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
16867 // read at most two `drl_mode` bits, one per stack entry past the
16868 // first, stopping at the first `0`. The chosen index selects
16869 // which stack entry `read_mv`'s base predictor comes from
16870 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
16871 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
16872 let mut idx = 0usize;
16873 while idx < 2 && stack.entries.len() > idx + 1 {
16874 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
16875 break;
16876 }
16877 idx += 1;
16878 }
16879 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
16880 (
16881 read_mv(
16882 dec,
16883 &mut cdfs.mv_comp,
16884 &mut cdfs.mv_joint,
16885 base_mv,
16886 allow_high_precision_mv,
16887 force_integer_mv,
16888 ),
16889 true,
16890 )
16891 } else {
16892 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
16893 is_globalmv = !not_zero;
16894 let mv = if !not_zero {
16895 // lane-gmaffine r1: GLOBALMV (spec 7.10.2.1) -- the same
16896 // `gm_get_motion_vector` value the 16x16+ leaf reads out of
16897 // its own `gm_table`, computed at this block's centre.
16898 GLOBALMV_HITS_8.with(|c| c.set(c.get() + 1));
16899 gm_table[(ref_frame - LAST_FRAME) as usize]
16900 } else {
16901 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
16902 if nearest {
16903 stack.nearest_mv
16904 } else {
16905 let mut idx = 1usize;
16906 while idx < 3 && stack.entries.len() > idx + 1 {
16907 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
16908 break;
16909 }
16910 idx += 1;
16911 }
16912 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
16913 }
16914 };
16915 (mv, false)
16916 };
16917 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
16918 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
16919 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
16920 // (compound already returned above), GLOBALMV already refused
16921 // (round 3), so the only real gate left is the header enable bit.
16922 let mut interintra_mode: Option<u8> = None;
16923 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
16924 if enable_interintra_compound && !skip_mode {
16925 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
16926 if interintra {
16927 // lane-interintra r1: same read pair as the 16/32 site;
16928 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
16929 // alone, never the `enable_interintra_wedge` seq bit.
16930 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
16931 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
16932 if wedge {
16933 // lane-wii r2: same adapting `wedge_index` symbol as the
16934 // 16/32 leaf, fixed sign 0 -- see that site's comment.
16935 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
16936 WII_HITS.with(|c| c.set(c.get() + 1));
16937 wedge_mask = Some((
16938 crate::wedge::wedge_masks()
16939 .codebook(SIDE)
16940 .mask(0, wedge_index as usize),
16941 SIDE,
16942 ));
16943 } else {
16944 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
16945 }
16946 interintra_mode = Some(ii);
16947 }
16948 }
16949 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
16950 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
16951 // is the spec's own minimum eligible size, single-ref-only branch,
16952 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
16953 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
16954 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
16955 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
16956 // lane-gmaffine r1: the two libaom predicates, exactly as the
16957 // 16x16+ leaf resolves them (see [`decode_inter_block`]'s own doc):
16958 // `is_global_mv_block` (mode GLOBAL*, model > TRANSLATION, block
16959 // >= 8x8 -- BLOCK_8X8 IS the 8px minimum, so the size predicate is
16960 // always true here) suppresses the motion_mode read entirely and
16961 // turns on the global warp below.
16962 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
16963 let is_global_mv_block = is_globalmv && gm_ref.model as u8 > 1;
16964 let motion_mode_eligible = switchable_motion_mode
16965 && !skip_mode
16966 && interintra_mode.is_none()
16967 && !(is_global_mv_block && !force_integer_mv)
16968 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
16969 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
16970 let mut warp_params: Option<crate::warp::WarpParams> = None;
16971 let mut warped_selected = false;
16972 let mut obmc_selected = false;
16973 if motion_mode_eligible {
16974 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
16975 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
16976 // (grid.set below hardcodes it).
16977 // lane-scaledref r2 sibling of the 16x16+ leaf's fix: libaom
16978 // drops WARPED_CAUSAL eligibility (so this reads `obmc_cdf`)
16979 // when the reference is scaled. Not gated here because an 8x8
16980 // leaf under a scaled reference is refused before this function
16981 // runs (see the block8 refusal below, ~12500) -- whoever lifts
16982 // that refusal must add `&& !ref_is_scaled` here too.
16983 // lane-fimv r1: libaom `motion_mode_allowed` also requires
16984 // `!xd->cur_frame_force_integer_mv`, so a screen-content frame
16985 // that set `force_integer_mv` reads the 2-symbol `obmc_cdf` here
16986 // (class wrong-alphabet-same-value).
16987 let proj_ok =
16988 num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
16989 let warp_eligible = allow_warped_motion && !force_integer_mv && proj_ok;
16990 if allow_warped_motion && proj_ok && force_integer_mv {
16991 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
16992 }
16993 if warp_eligible {
16994 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
16995 match mode {
16996 0 => {}
16997 1 => {
16998 obmc_selected = true;
16999 OBMC_HITS.with(|c| c.set(c.get() + 1));
17000 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
17001 }
17002 _ => {
17003 // lane-gmaffine r1: WARPED_CAUSAL at the 8x8 leaf --
17004 // the same findSamples -> select_samples ->
17005 // av1_find_projection chain the 16x16+ leaf runs,
17006 // with BLOCK_8X8's own 8x8 model centre; an
17007 // unusable projection falls back to the block's
17008 // translational mv (libaom `av1_find_projection`
17009 // returning 1 leaves `wm_params` invalid and
17010 // `build_inter_predictors` skips the warp).
17011 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
17012 let mut samples = find_samples(
17013 grid,
17014 mi_row,
17015 mi_col,
17016 2,
17017 2,
17018 mi_cols as usize,
17019 mi_rows as usize,
17020 ref_frame,
17021 );
17022 if samples.len() > 1 {
17023 crate::warp::select_samples(mv, &mut samples, SIDE as i32, SIDE as i32);
17024 }
17025 warp_params = crate::warp::find_projection(
17026 &samples,
17027 SIDE as i32,
17028 SIDE as i32,
17029 mv.1,
17030 mv.0,
17031 mi_row as i32,
17032 mi_col as i32,
17033 );
17034 warped_selected = true;
17035 if warp_params.is_some() {
17036 WARP_HITS_8.with(|c| c.set(c.get() + 1));
17037 }
17038 }
17039 }
17040 } else {
17041 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
17042 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
17043 if obmc_selected {
17044 OBMC_HITS.with(|c| c.set(c.get() + 1));
17045 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
17046 }
17047 }
17048 }
17049 // lane-gmaffine r1: `read_mb_interp_filter` (spec 5.11.26) at the 8x8
17050 // leaf, in libaom's own order (interintra, motion_mode, THEN the
17051 // filter). Until this round the leaf read no filter symbol at all and
17052 // predicted Regular unconditionally -- correct only for a frame with a
17053 // fixed `interp_filter`, and a silent entropy DESYNC for every
17054 // SWITCHABLE-filter stream that reaches an 8x8 leaf (which is what
17055 // made the interior-split wiring above unusable at first).
17056 // corner-cut: the neighbour filter context is the enclosing 16x16
17057 // block's own coarse `above_filter`/`left_filter` entry (this leaf
17058 // path keeps no per-leaf neighbour array), so all four siblings read
17059 // the same context row. Ceiling: a stream whose 8x8 siblings pick
17060 // DIFFERENT filters decodes the second..fourth leaf's symbol from the
17061 // wrong CDF row. Upgrade: give `Neighbours` a real 8x8-granular
17062 // filter array, same shape as the `[3, 3]` approximation the caller
17063 // records after the leaf loop.
17064 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
17065 || neighbours.above_ref1[cmi] == Some(ref_frame)
17066 {
17067 neighbours.above_filter[cmi]
17068 } else {
17069 [3, 3]
17070 };
17071 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
17072 || neighbours.left_ref1[rmi] == Some(ref_frame)
17073 {
17074 neighbours.left_filter[rmi]
17075 } else {
17076 [3, 3]
17077 };
17078 let gm_nontrans =
17079 is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation;
17080 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
17081 dec,
17082 cdfs,
17083 interp_fixed,
17084 enable_dual_filter,
17085 gm_nontrans || warped_selected || skip_mode,
17086 above_filter_ctx,
17087 left_filter_ctx,
17088 false,
17089 );
17090 leaf_filter_syms = resolved_filter;
17091 if std::env::var_os("EC_TRACE_MODE").is_some() {
17092 eprintln!(
17093 "EC_MODE_VAL8 mi_row={} mi_col={} newmv={is_new_mv} globalmv={is_globalmv} ref0={ref_frame} mv0=({},{}) stack={} rng={}",
17094 leaf_mi.0,
17095 leaf_mi.1,
17096 mv.0,
17097 mv.1,
17098 stack.entries.len(),
17099 dec.debug_state().0
17100 );
17101 }
17102 // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch
17103 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
17104 // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model
17105 // wins (`is_none()` guard); BLOCK_8X8 already satisfies the >=8px
17106 // size predicate baked into `is_global_mv_block`.
17107 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
17108 warp_params = crate::warp::global_warp_params(gm_ref.params);
17109 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
17110 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
17111 }
17112 }
17113 if std::env::var_os("EC_TRACE_MODE").is_some() {
17114 eprintln!(
17115 "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}",
17116 leaf_mi.0,
17117 leaf_mi.1,
17118 warp_params.is_some(),
17119 );
17120 }
17121 for dr in 0..2 {
17122 for dc in 0..2 {
17123 grid.set(
17124 mi_row + dr,
17125 mi_col + dc,
17126 MiInfo {
17127 is_inter: true,
17128 ref_frame,
17129 // INTRA_FRAME marker for interintra blocks -- keeps
17130 // them out of warp-sample gathering (see 16/32 site).
17131 ref_frame1: interintra_mode.map(|_| 0),
17132 mv1: None,
17133 mv,
17134 is_new_mv,
17135 size: 2,
17136 size_h: 2,
17137 is_global_mv0: is_global_mv_block,
17138 is_global_mv1: false,
17139 },
17140 );
17141 }
17142 }
17143 mode_for_tx = 0;
17144
17145 // lane-scaledref r1: this leaf's own prediction is always `Regular`
17146 // (documented corner-cut above); under a scaled reference the same
17147 // fixed kernel runs through spec 7.11.3.3's scaled walk instead.
17148 let luma_scale = mc::scale_factor(sref_y.width, frame_width);
17149 if luma_scale != mc::REF_NO_SCALE {
17150 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
17151 }
17152 let mut pred_y = vec![0u16; SIDE * SIDE];
17153 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
17154 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
17155 // Merge of lane-gmaffine (this leaf's own switchable filters) with
17156 // lane-scaledref (spec 7.11.3.3's scaled walk): same kernels either
17157 // way, only the sample walk differs.
17158 for (plane, x, y, dim, dst) in [
17159 (sref_y, px, py, SIDE, &mut pred_y),
17160 (sref_u, cpx, cpy, CHROMA_SIDE, &mut pred_u),
17161 (sref_v, cpx, cpy, CHROMA_SIDE, &mut pred_v),
17162 ] {
17163 let luma = std::ptr::eq(plane, sref_y);
17164 if luma_scale == mc::REF_NO_SCALE {
17165 mc::predict_with_filters(
17166 &plane.data,
17167 plane.width,
17168 plane.true_width,
17169 plane.true_height,
17170 mv_to_q4(x, mv.1, luma),
17171 mv_to_q4(y, mv.0, luma),
17172 dim,
17173 dim,
17174 h_filter,
17175 v_filter,
17176 dst,
17177 );
17178 } else {
17179 mc::predict_scaled(
17180 &plane.data,
17181 plane.width,
17182 plane.true_width,
17183 plane.true_height,
17184 mv_to_q4(x, mv.1, luma),
17185 mv_to_q4(y, mv.0, luma),
17186 luma_scale,
17187 dim,
17188 dim,
17189 h_filter,
17190 v_filter,
17191 dst,
17192 );
17193 }
17194 }
17195
17196 // lane-gmaffine r1: the warp filter REPLACES the translational
17197 // prediction just built (libaom builds one or the other), same as
17198 // the 16x16+ leaf's own call trio.
17199 if let Some(params) = &warp_params {
17200 crate::warp::warp_affine(
17201 params, &sref_y.data, sref_y.true_width as i32, sref_y.true_height as i32,
17202 sref_y.width as i32, &mut pred_y, px as i32, py as i32, SIDE as i32,
17203 SIDE as i32, SIDE as i32, 0, 0,
17204 );
17205 // `av1_init_warp_params`'s per-plane `block_width/height < 8`
17206 // bail-out: an 8x8 leaf's chroma plane is 4x4 in 420, so it is
17207 // predicted translationally even when the luma warps.
17208 #[allow(clippy::absurd_extreme_comparisons)]
17209 if CHROMA_SIDE >= 8 {
17210 crate::warp::warp_affine(
17211 params, &sref_u.data, sref_u.true_width as i32, sref_u.true_height as i32,
17212 sref_u.width as i32, &mut pred_u, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
17213 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
17214 );
17215 crate::warp::warp_affine(
17216 params, &sref_v.data, sref_v.true_width as i32, sref_v.true_height as i32,
17217 sref_v.width as i32, &mut pred_v, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
17218 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
17219 );
17220 }
17221 }
17222
17223 if obmc_selected {
17224 obmc_blend(
17225 grid,
17226 neighbours,
17227 mi_row,
17228 mi_col,
17229 2,
17230 2,
17231 mi_rows as usize,
17232 mi_cols as usize,
17233 SIDE,
17234 SIDE,
17235 SIDE,
17236 CHROMA_SIDE,
17237 px,
17238 py,
17239 cpx,
17240 cpy,
17241 ref_y,
17242 ref_u,
17243 ref_v,
17244 other_refs,
17245 interp_fixed,
17246 frame_width,
17247 &mut pred_y,
17248 &mut pred_u,
17249 &mut pred_v,
17250 )?;
17251 }
17252
17253 // Non-wedge interintra blend, mutually exclusive with OBMC (the
17254 // motion_mode symbol is not read for an interintra block).
17255 if let Some(ii) = interintra_mode {
17256 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
17257 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
17258 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
17259 }
17260
17261 split8 = read_block_tx_size(
17262 dec,
17263 cdfs,
17264 neighbours,
17265 leaf_mi,
17266 SIDE,
17267 (mi_cols as usize, mi_rows as usize),
17268 true,
17269 skip,
17270 )?
17271 .1
17272 .is_some();
17273 if skip {
17274 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
17275 u.reconstruct_mc(
17276 cpx,
17277 cpy,
17278 CHROMA_SIDE,
17279 &pred_u,
17280 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17281 );
17282 v.reconstruct_mc(
17283 cpx,
17284 cpy,
17285 CHROMA_SIDE,
17286 &pred_v,
17287 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17288 );
17289 luma_grid = vec![0i32; SIDE * SIDE];
17290 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17291 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17292 } else {
17293 let around = neighbours.around_mi(leaf_mi, 8);
17294 let (grid8, luma_tx_type) = read_inter_luma8(
17295 dec,
17296 cdfs,
17297 neighbours,
17298 leaf_mi,
17299 y,
17300 px,
17301 py,
17302 &pred_y,
17303 mode_for_tx,
17304 base_q_idx,
17305 scan8,
17306 scan4,
17307 reduced_tx_set,
17308 split8,
17309 )?;
17310 luma_grid = grid8;
17311 u_grid = read_inter_plane(
17312 dec,
17313 cdfs,
17314 TxbSet::Chroma4,
17315 scan4,
17316 1,
17317 around[1],
17318 mode_for_tx,
17319 u,
17320 cpx,
17321 cpy,
17322 CHROMA_SIDE,
17323 base_q_idx,
17324 &pred_u,
17325 Some(luma_tx_type),
17326 None,
17327 )?
17328 .0;
17329 v_grid = read_inter_plane(
17330 dec,
17331 cdfs,
17332 TxbSet::Chroma4,
17333 scan4,
17334 2,
17335 around[2],
17336 mode_for_tx,
17337 v,
17338 cpx,
17339 cpy,
17340 CHROMA_SIDE,
17341 base_q_idx,
17342 &pred_v,
17343 Some(luma_tx_type),
17344 None,
17345 )?
17346 .0;
17347 }
17348 } else {
17349 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
17350 if mode >= 13 {
17351 return Err(unsupported(
17352 "an intra mode this decoder does not code (round 2)",
17353 ));
17354 }
17355 if (V_PRED..=D67_PRED).contains(&mode) {
17356 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
17357 if angle != ANGLE_DELTA_ZERO {
17358 return Err(unsupported(
17359 "a nonzero angle delta (this encoder never writes one)",
17360 ));
17361 }
17362 }
17363 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
17364 if uv_mode != DC_PRED {
17365 return Err(unsupported(
17366 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
17367 ));
17368 }
17369 // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/
17370 // `uv_mode` are both effectively `DC_PRED`-gated already on this
17371 // leaf (a nonzero `mode` still passes, but `uv_mode` is forced
17372 // `DC_PRED` by the refusal just above), same order as libaom's
17373 // `read_palette_mode_info` call right after `xd->cfl.store_y`.
17374 if allow_screen_content_tools {
17375 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[0][0]) != 0 {
17376 return Err(unsupported(
17377 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
17378 ));
17379 }
17380 if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
17381 return Err(unsupported(
17382 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
17383 ));
17384 }
17385 }
17386 mode_for_tx = mode;
17387 let (mi_row, mi_col) = leaf_mi;
17388 for dr in 0..2 {
17389 for dc in 0..2 {
17390 grid.set(
17391 mi_row + dr,
17392 mi_col + dc,
17393 MiInfo {
17394 is_inter: false,
17395 ref_frame: -1,
17396 ref_frame1: None,
17397 mv1: None,
17398 mv: (0, 0),
17399 is_new_mv: false,
17400 size: 2,
17401 size_h: 2,
17402 is_global_mv0: false,
17403 is_global_mv1: false,
17404 },
17405 );
17406 }
17407 }
17408
17409 read_block_tx_size(
17410 dec,
17411 cdfs,
17412 neighbours,
17413 leaf_mi,
17414 SIDE,
17415 (mi_cols as usize, mi_rows as usize),
17416 false,
17417 skip,
17418 )?;
17419 let reach = Reach::of(SIDE, px, py, y.width, y.height);
17420 if skip {
17421 y.reconstruct(
17422 px,
17423 py,
17424 SIDE,
17425 mode,
17426 0,
17427 reach,
17428 &vec![0i32; SIDE * SIDE],
17429 None,
17430 None,
17431 false,
17432 );
17433 u.reconstruct(
17434 cpx,
17435 cpy,
17436 CHROMA_SIDE,
17437 DC_PRED,
17438 0,
17439 reach,
17440 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17441 None,
17442 None,
17443 false,
17444 );
17445 v.reconstruct(
17446 cpx,
17447 cpy,
17448 CHROMA_SIDE,
17449 DC_PRED,
17450 0,
17451 reach,
17452 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17453 None,
17454 None,
17455 false,
17456 );
17457 luma_grid = vec![0i32; SIDE * SIDE];
17458 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17459 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17460 } else {
17461 let around = neighbours.around_mi(leaf_mi, 8);
17462 luma_grid = read_plane(
17463 dec,
17464 cdfs,
17465 TxbSet::Luma8,
17466 scan8,
17467 0,
17468 around[0],
17469 mode,
17470 mode,
17471 0,
17472 reach,
17473 y,
17474 px,
17475 py,
17476 SIDE,
17477 TX8,
17478 base_q_idx,
17479 None,
17480 None,
17481 None,
17482 false,
17483 )?;
17484 u_grid = read_plane(
17485 dec,
17486 cdfs,
17487 TxbSet::Chroma4,
17488 scan4,
17489 1,
17490 around[1],
17491 mode,
17492 DC_PRED,
17493 0,
17494 reach,
17495 u,
17496 cpx,
17497 cpy,
17498 CHROMA_SIDE,
17499 TX4,
17500 base_q_idx,
17501 None,
17502 None,
17503 None,
17504 false,
17505 )?;
17506 v_grid = read_plane(
17507 dec,
17508 cdfs,
17509 TxbSet::Chroma4,
17510 scan4,
17511 2,
17512 around[2],
17513 mode,
17514 DC_PRED,
17515 0,
17516 reach,
17517 v,
17518 cpx,
17519 cpy,
17520 CHROMA_SIDE,
17521 TX4,
17522 base_q_idx,
17523 None,
17524 None,
17525 None,
17526 false,
17527 )?;
17528 }
17529 }
17530 // lane-txselect: a split leaf's plane-0 neighbour context is per 4x4
17531 // transform unit (written by `record_mi_luma` inside `read_inter_luma8`),
17532 // but `record_mi` rewrites all three planes of these cells at once -- so
17533 // save plane 0 across it, exactly as `record_split_luma` leaves plane 0
17534 // alone at the bigger block sizes.
17535 let saved_luma_ctx = split8.then(|| {
17536 (
17537 [
17538 neighbours.left[leaf_mi.0][0],
17539 neighbours.left[leaf_mi.0 + 1][0],
17540 ],
17541 [
17542 neighbours.above[leaf_mi.1][0],
17543 neighbours.above[leaf_mi.1 + 1][0],
17544 ],
17545 )
17546 });
17547 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
17548 if let Some((left, above)) = saved_luma_ctx {
17549 for (cell, state) in left.into_iter().enumerate() {
17550 neighbours.left[leaf_mi.0 + cell][0] = state;
17551 }
17552 for (cell, state) in above.into_iter().enumerate() {
17553 neighbours.above[leaf_mi.1 + cell][0] = state;
17554 }
17555 }
17556 // lane-gmaffine r2: the deblock grid's ref id is the leaf's OWN reference
17557 // (r1 taught this leaf non-LAST refs; the hardcoded LAST_FRAME made every
17558 // GOLDEN/ALTREF leaf read as LAST at the loop-filter's ref/mv edge test).
17559 neighbours.fill_lf_grid(
17560 leaf_mi,
17561 2,
17562 if split8 { 4 } else { 8 },
17563 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
17564 );
17565 Ok((
17566 skip,
17567 is_inter,
17568 skip_mode,
17569 compound_ctx8,
17570 leaf_filter_syms,
17571 leaf_refs,
17572 ))
17573}
17574
17575/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
17576/// against `reference` (the previous frame's own decoded picture, at this
17577/// frame's true size -- a decoder's single-slot DPB, matching what this
17578/// crate's encoder always predicts from), returning the picture it
17579/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
17580/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
17581/// `frame_width`/`frame_height` its true render size).
17582///
17583/// # Errors
17584/// Returns an error under the same conditions [`decode_inter_block`] does,
17585/// or when `reference` is not this frame's own true size, or when the tile
17586/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
17587/// refusal [`crate::tile`]'s writer gives its encoder).
17588pub fn decode_inter_frame_tile(
17589 data: &[u8],
17590 mi_cols: u32,
17591 mi_rows: u32,
17592 base_q_idx: u8,
17593 frame_width: u32,
17594 frame_height: u32,
17595 reference: &Picture,
17596 other_refs: [Option<&Picture>; 8],
17597 cdef: &CdefParams,
17598 loop_filter: &LoopFilterParams,
17599 allow_high_precision_mv: bool,
17600 force_integer_mv: bool,
17601 interp_fixed: Option<mc::InterpFilterKind>,
17602 enable_dual_filter: bool,
17603 reference_select: bool,
17604) -> Result<Picture> {
17605 let single_tile = TileInfo {
17606 mi_col_starts: vec![0, mi_cols],
17607 mi_row_starts: vec![0, mi_rows],
17608 ..TileInfo::default()
17609 };
17610 decode_inter_frame_tile_with_cdfs(
17611 &[data],
17612 &single_tile,
17613 mi_cols,
17614 mi_rows,
17615 base_q_idx,
17616 crate::quant::QuantDeltas::default(),
17617 frame_width,
17618 frame_height,
17619 reference,
17620 other_refs,
17621 cdef,
17622 loop_filter,
17623 &LoopRestorationParams::default(),
17624 None,
17625 allow_high_precision_mv,
17626 force_integer_mv,
17627 NO_SIGN_BIAS,
17628 [ec_av1_syntax::WarpParams::default(); 7],
17629 interp_fixed,
17630 enable_dual_filter,
17631 0,
17632 0,
17633 [0; 7],
17634 None,
17635 reference_select,
17636 false,
17637 false,
17638 false,
17639 false,
17640 [0; 2],
17641 true,
17642 // `tx_select`: this raw entry point decodes this crate's own encoder's
17643 // streams, which always write `TxMode::Largest`.
17644 false,
17645 false,
17646 false,
17647 false,
17648 DeltaParams::default(),
17649 )
17650 .map(|(picture, _, _)| picture)
17651}
17652
17653/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
17654/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
17655/// end-of-tile table. An inter frame's own header can name
17656/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
17657/// so `None` is a real case here, not only a convenience default.
17658pub(crate) fn decode_inter_frame_tile_with_cdfs(
17659 tiles: &[&[u8]],
17660 tile_info: &TileInfo,
17661 mi_cols: u32,
17662 mi_rows: u32,
17663 base_q_idx: u8,
17664 // lane-sbpart r11: see [`decode_key_frame_tile_with_cdfs`]'s own `deltas`.
17665 deltas: crate::quant::QuantDeltas,
17666 frame_width: u32,
17667 frame_height: u32,
17668 reference: &Picture,
17669 other_refs: [Option<&Picture>; 8],
17670 cdef: &CdefParams,
17671 loop_filter: &LoopFilterParams,
17672 lr: &LoopRestorationParams,
17673 initial_cdfs: Option<Cdfs>,
17674 allow_high_precision_mv: bool,
17675 force_integer_mv: bool,
17676 sign_bias_table: SignBiasTable,
17677 // lane-gm r2: this frame header's own `global_motion` table (spec
17678 // 5.9.24), threaded to every `decode_inter_block` call below.
17679 global_motion: [ec_av1_syntax::WarpParams; 7],
17680 interp_fixed: Option<mc::InterpFilterKind>,
17681 enable_dual_filter: bool,
17682 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
17683 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
17684 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
17685 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
17686 // and the caller ([`crate::stream::decode_stream`]) projected one.
17687 order_hint_bits: u32,
17688 order_hint: u32,
17689 ref_order_hints: [u32; 7],
17690 tpl_field: Option<&crate::motion_field::TplField>,
17691 // lane-av1comp: this frame header's own `reference_select` bit, threaded
17692 // to every `decode_inter_block`/`decode_inter_block8` call below.
17693 reference_select: bool,
17694 // lane-av1comp: `seq_params`' own compound-blend enable bits.
17695 enable_masked_compound: bool,
17696 enable_jnt_comp: bool,
17697 // lane-sb128 r3: this sequence header's own `enable_interintra_compound`
17698 // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call
17699 // below (spec 5.11.24's `interintra` read).
17700 enable_interintra_compound: bool,
17701 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
17702 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
17703 // `decode_inter_block8` call below.
17704 skip_mode_present: bool,
17705 skip_mode_frame: [u8; 2],
17706 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to
17707 // every inter `tx_type` read below (`false` needs the 12-/16-symbol
17708 // `Set1` coefficient tables at 16x16/8x8 rather than the reduced
17709 // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]).
17710 reduced_tx_set: bool,
17711 // lane-txselect: this frame header's own `tx_mode == TxMode::Select`
17712 // bit (spec 5.9.14). Together with `reduced_tx_set` it is stashed in a
17713 // thread-local by [`set_inter_tx_mode`] rather than threaded through
17714 // `decode_inter_block`'s forty parameters -- both are frame-constant, and
17715 // only [`read_block_tx_size`]/the var-tx residual loop read them.
17716 tx_select: bool,
17717 // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/
17718 // `allow_warped_motion` bits, threaded to every `decode_inter_block`/
17719 // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`).
17720 switchable_motion_mode: bool,
17721 allow_warped_motion: bool,
17722 // lane-screen r2: this frame header's own `allow_screen_content_tools`
17723 // bit, threaded to every `decode_inter_block`/`decode_inter_block8`
17724 // call below -- consumes (never reconstructs) the intra-sub-block
17725 // palette syntax libaom's `read_intra_block_mode_info` reads under the
17726 // same `av1_allow_palette` gate as the key-frame path.
17727 allow_screen_content_tools: bool,
17728 // lane-realworld r5: this frame header's own `delta` (spec 5.9.17/5.9.18),
17729 // same contract as [`decode_key_frame_tile_with_cdfs`]'s own `delta`
17730 // param -- only `q_present`/`q_res` are read.
17731 delta: DeltaParams,
17732) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
17733 set_inter_tx_mode(tx_select, reduced_tx_set);
17734 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
17735 field,
17736 order_hint_bits,
17737 order_hint,
17738 ref_order_hints,
17739 });
17740 if mi_cols == 0 || mi_rows == 0 {
17741 return Err(unsupported("a frame with no mode-info grid"));
17742 }
17743 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
17744 // lane-superres r10: a width mismatch alone is no longer refused here --
17745 // `mc::predict_scaled` (spec 7.11.3.3, threaded through
17746 // `decode_inter_block`'s single-ref branch) exists precisely for a
17747 // `use_superres` reference at a different width than this frame's own
17748 // true size. Height must still match: AV1 superres never scales height
17749 // (r8's derivation, `mc.rs`'s own doc), and nothing in this decode path
17750 // has a vertical scaling pass.
17751 if reference.height != true_height {
17752 return Err(unsupported(
17753 "a reference picture whose height does not match this frame's own true size",
17754 ));
17755 }
17756 let (cols, rows) = block_grid(mi_cols, mi_rows);
17757 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
17758 CDEF_BITS.with(|c| c.set(cdef.bits));
17759 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
17760 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
17761 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
17762
17763 let ref_y = PlaneBuf {
17764 data: reference.y.iter().map(|&s| s as u16).collect(),
17765 width: reference.width,
17766 height: reference.height,
17767 true_width: reference.width,
17768 true_height: reference.height,
17769 tile_x0: 0,
17770 tile_y0: 0,
17771 tile_x1: reference.width,
17772 tile_y1: reference.height,
17773 };
17774 let ref_u = PlaneBuf {
17775 data: reference.u.iter().map(|&s| s as u16).collect(),
17776 width: reference.width / 2,
17777 height: reference.height / 2,
17778 true_width: reference.width / 2,
17779 true_height: reference.height / 2,
17780 tile_x0: 0,
17781 tile_y0: 0,
17782 tile_x1: reference.width / 2,
17783 tile_y1: reference.height / 2,
17784 };
17785 let ref_v = PlaneBuf {
17786 data: reference.v.iter().map(|&s| s as u16).collect(),
17787 width: reference.width / 2,
17788 height: reference.height / 2,
17789 true_width: reference.width / 2,
17790 true_height: reference.height / 2,
17791 tile_x0: 0,
17792 tile_y0: 0,
17793 tile_x1: reference.width / 2,
17794 tile_y1: reference.height / 2,
17795 };
17796 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
17797 // names a live DPB slot for (lane-av1refs: generalised from the old
17798 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
17799 // now per-reference). `decode_inter_block` refuses by name when the
17800 // block it is decoding selects an index that is still `None` here
17801 // (spec 7.9 requires every *active* reference be a compatible size;
17802 // an inactive one this frame never selects is simply left `None`).
17803 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
17804 other_refs[i]
17805 .filter(|g| g.width == reference.width && g.height == reference.height)
17806 .map(|g| {
17807 (
17808 PlaneBuf {
17809 data: g.y.iter().map(|&s| s as u16).collect(),
17810 width: g.width,
17811 height: g.height,
17812 true_width: g.width,
17813 true_height: g.height,
17814 tile_x0: 0,
17815 tile_y0: 0,
17816 tile_x1: g.width,
17817 tile_y1: g.height,
17818 },
17819 PlaneBuf {
17820 data: g.u.iter().map(|&s| s as u16).collect(),
17821 width: g.width / 2,
17822 height: g.height / 2,
17823 true_width: g.width / 2,
17824 true_height: g.height / 2,
17825 tile_x0: 0,
17826 tile_y0: 0,
17827 tile_x1: g.width / 2,
17828 tile_y1: g.height / 2,
17829 },
17830 PlaneBuf {
17831 data: g.v.iter().map(|&s| s as u16).collect(),
17832 width: g.width / 2,
17833 height: g.height / 2,
17834 true_width: g.width / 2,
17835 true_height: g.height / 2,
17836 tile_x0: 0,
17837 tile_y0: 0,
17838 tile_x1: g.width / 2,
17839 tile_y1: g.height / 2,
17840 },
17841 )
17842 })
17843 });
17844 let ref_slots: RefSlots =
17845 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
17846
17847 let mut y = PlaneBuf {
17848 data: vec![0u16; width * height],
17849 width,
17850 height,
17851 true_width,
17852 true_height,
17853 tile_x0: 0,
17854 tile_y0: 0,
17855 tile_x1: width,
17856 tile_y1: height,
17857 };
17858 let mut u = PlaneBuf {
17859 data: vec![0u16; width * height / 4],
17860 width: width / 2,
17861 height: height / 2,
17862 true_width: true_width / 2,
17863 true_height: true_height / 2,
17864 tile_x0: 0,
17865 tile_y0: 0,
17866 tile_x1: width / 2,
17867 tile_y1: height / 2,
17868 };
17869 let mut v = PlaneBuf {
17870 data: vec![0u16; width * height / 4],
17871 width: width / 2,
17872 height: height / 2,
17873 true_width: true_width / 2,
17874 true_height: true_height / 2,
17875 tile_x0: 0,
17876 tile_y0: 0,
17877 tile_x1: width / 2,
17878 tile_y1: height / 2,
17879 };
17880
17881 let scan32 = default_scan(TX32);
17882 let scan16 = default_scan(TX16);
17883 let scan8 = default_scan(TX8);
17884 let scan4 = default_scan(TX4);
17885
17886 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
17887 let mut result_cdfs = base_cdfs.clone();
17888 // spec `decode_tile`: `CurrentQIndex`/`DeltaLF` reset to the frame's own
17889 // `base_q_idx`/zero at the top of every tile, not once per frame (mirrors
17890 // `decode_key_frame_tile_with_cdfs`'s per-tile reset below); the
17891 // delta_q/delta_lf presence/resolution flags themselves are frame-level
17892 // and set once here.
17893 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
17894 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
17895 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
17896 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
17897 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
17898 let mut neighbours = Neighbours::new(
17899 cols as usize * 2,
17900 rows as usize * 2,
17901 mi_cols as usize,
17902 mi_rows as usize,
17903 );
17904 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
17905 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
17906 let mut lr_reference = [(
17907 crate::restoration::WienerInfo::default(),
17908 crate::restoration::SgrprojInfo::default(),
17909 ); 3];
17910
17911 // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile
17912 // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets
17913 // its own fresh SymbolDecoder over its own byte range and its own fresh
17914 // copy of the frame's initial CDFs; only context_update_tile_id's own
17915 // end-of-tile adapted table becomes the frame's own output.
17916 for (tile_idx, &data) in tiles.iter().enumerate() {
17917 let tile_num = tile_idx as u32;
17918 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
17919 let mi_row0 = tile_info.mi_row_starts[trow as usize];
17920 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
17921 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
17922 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
17923 let (sb_r0, sb_r1) = (
17924 (mi_row0 / SB_MI).min(sb_rows),
17925 mi_row1.div_ceil(SB_MI).min(sb_rows),
17926 );
17927 let (sb_c0, sb_c1) = (
17928 (mi_col0 / SB_MI).min(sb_cols),
17929 mi_col1.div_ceil(SB_MI).min(sb_cols),
17930 );
17931 let mut cdfs = base_cdfs.clone();
17932 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
17933 QUANT_DELTAS.with(|c| c.set(deltas));
17934 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
17935 let mut dec = SymbolDecoder::new(data);
17936 // lane-comppin r9: tile-entry range, the earliest point comparable
17937 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
17938 // first ladder rung before any symbol (partition or otherwise) is read.
17939 if std::env::var_os("EC_AV1_TELL").is_some() {
17940 eprintln!(
17941 "TELL label=tile_init tell={} range={}",
17942 dec.debug_bitpos(),
17943 dec.debug_state().0
17944 );
17945 }
17946 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
17947 y.set_tile_origin(
17948 mi_col0 as usize * 4,
17949 mi_row0 as usize * 4,
17950 (mi_col1 as usize * 4).min(y.width),
17951 (mi_row1 as usize * 4).min(y.height),
17952 );
17953 u.set_tile_origin(
17954 mi_col0 as usize * 2,
17955 mi_row0 as usize * 2,
17956 (mi_col1 as usize * 2).min(u.width),
17957 (mi_row1 as usize * 2).min(u.height),
17958 );
17959 v.set_tile_origin(
17960 mi_col0 as usize * 2,
17961 mi_row0 as usize * 2,
17962 (mi_col1 as usize * 2).min(v.width),
17963 (mi_row1 as usize * 2).min(v.height),
17964 );
17965 // lane-tiles r6: an MV candidate scan (mvstack.rs's grid.get) must
17966 // not reach across a tile boundary any more than intra prediction's
17967 // PlaneBuf reach does -- bounding the shared grid's own read window
17968 // per tile is equivalent to threading tile bounds through every
17969 // find_mv_stack* call site (all four read through this one grid).
17970 grid.set_tile_bounds(
17971 mi_row0 as usize,
17972 mi_col0 as usize,
17973 mi_row1 as usize,
17974 mi_col1 as usize,
17975 );
17976 TILE_HITS.with(|c| c.set(c.get() + 1));
17977
17978 for sb_r in sb_r0..sb_r1 {
17979 neighbours.start_row();
17980 for sb_c in sb_c0..sb_c1 {
17981 crate::restoration::read_lr(
17982 &mut dec,
17983 &mut cdfs,
17984 lr,
17985 &mut lr_grid,
17986 &mut lr_reference,
17987 sb_r * SB_MI,
17988 sb_c * SB_MI,
17989 SB_MI,
17990 );
17991 CDEF_TRANSMITTED.with(|c| c.set(false));
17992 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
17993 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
17994 let (has_cols, has_rows) = (
17995 sb_c * SB_MI + SB_MI / 2 < mi_cols,
17996 sb_r * SB_MI + SB_MI / 2 < mi_rows,
17997 );
17998 // The straddle cases (one or both halves outside the true
17999 // frame) never carry a real alphabet symbol -- spec forces
18000 // SPLIT there (mirrors the intra key-frame tile's own
18001 // three-way write above). Only the (true, true) case can name
18002 // a non-SPLIT value, and this loop below only ever recurses as
18003 // SPLIT -- so a real non-SPLIT part64 here must refuse by name
18004 // instead of silently decoding as SPLIT and desyncing.
18005 let part64 = match (has_cols, has_rows) {
18006 (true, true) => {
18007 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
18008 if std::env::var_os("EC_AV1_TRACE").is_some() {
18009 eprintln!(
18010 "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}",
18011 sb_r * SB_MI,
18012 sb_c * SB_MI
18013 );
18014 }
18015 p
18016 }
18017 (true, false) => {
18018 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
18019 PARTITION_SPLIT
18020 }
18021 (false, true) => {
18022 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
18023 PARTITION_SPLIT
18024 }
18025 (false, false) => PARTITION_SPLIT,
18026 };
18027 if part64 == PARTITION_NONE {
18028 // lane-inter8 r1: the whole superblock as one 64x64 inter
18029 // block. `SB`-sized syntax throughout (size_group 3, same as
18030 // 32x32 -- `size_group_lookup[BLOCK_64X64] == 3`), luma
18031 // coefficients through `TxbSet::Luma64` with the 32-point
18032 // scan (TX_64X64 codes only its top-left corner, spec
18033 // 5.11.40 -- `read_inter_plane` widens the corner back to
18034 // 64x64 before the inverse transform), chroma as a plain
18035 // 32x32 `TxbSet::Chroma32`. TX_64X64 carries no `tx_type`
18036 // symbol at all, so the intra/inter luma sets coincide.
18037 INTER_SB_NONE_HITS.with(|c| c.set(c.get() + 1));
18038 decode_inter_block(
18039 &mut dec,
18040 &mut cdfs,
18041 &mut neighbours,
18042 &mut grid,
18043 sb_at,
18044 SB,
18045 mi_cols,
18046 mi_rows,
18047 &mut y,
18048 &mut u,
18049 &mut v,
18050 &ref_y,
18051 &ref_u,
18052 &ref_v,
18053 &ref_slots,
18054 &sign_bias_table,
18055 &global_motion,
18056 base_q_idx,
18057 TxbSet::Luma64,
18058 TxbSet::Luma64,
18059 TxbSet::Chroma32,
18060 TX32,
18061 TX32,
18062 &scan32,
18063 &scan32,
18064 3,
18065 allow_high_precision_mv,
18066 force_integer_mv,
18067 interp_fixed,
18068 enable_dual_filter,
18069 tpl_frame.as_ref(),
18070 reference_select,
18071 enable_masked_compound,
18072 enable_interintra_compound,
18073 enable_jnt_comp,
18074 order_hint_bits,
18075 order_hint,
18076 ref_order_hints,
18077 skip_mode_present,
18078 skip_mode_frame,
18079 switchable_motion_mode,
18080 allow_warped_motion,
18081 false,
18082 SB,
18083 SB,
18084 allow_screen_content_tools,
18085 frame_width as usize,
18086 )?;
18087 continue;
18088 }
18089 if part64 != PARTITION_SPLIT {
18090 return Err(unsupported(
18091 "an inter SB-level partition type other than NONE or SPLIT (this decoder's \
18092 inter tile path recurses a superblock only as SPLIT)",
18093 ));
18094 }
18095
18096 for quadrant in 0..4 {
18097 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
18098 if r32 >= rows || c32 >= cols {
18099 continue;
18100 }
18101 let at = (r32 as usize * 2, c32 as usize * 2);
18102 let ctx32 = neighbours.partition_ctx(at, BLOCK);
18103 let (has_cols32, has_rows32) = (
18104 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
18105 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
18106 );
18107 let part32 = if has_cols32 && has_rows32 {
18108 if std::env::var_os("EC_AV1_TRACE").is_some() {
18109 eprintln!(
18110 "TRACE part32_pre mi=({},{}) rng={}",
18111 r32 * BLOCK_MI,
18112 c32 * BLOCK_MI,
18113 dec.debug_state().0
18114 );
18115 }
18116 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
18117 if std::env::var_os("EC_AV1_TRACE").is_some() {
18118 eprintln!(
18119 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
18120 r32 * BLOCK_MI,
18121 c32 * BLOCK_MI
18122 );
18123 }
18124 p
18125 } else {
18126 match (has_cols32, has_rows32) {
18127 (true, false) => {
18128 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
18129 }
18130 (false, true) => {
18131 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
18132 }
18133 _ => {}
18134 }
18135 PARTITION_SPLIT
18136 };
18137 match part32 {
18138 PARTITION_NONE => {
18139 decode_inter_block(
18140 &mut dec,
18141 &mut cdfs,
18142 &mut neighbours,
18143 &mut grid,
18144 at,
18145 BLOCK,
18146 mi_cols,
18147 mi_rows,
18148 &mut y,
18149 &mut u,
18150 &mut v,
18151 &ref_y,
18152 &ref_u,
18153 &ref_v,
18154 &ref_slots,
18155 &sign_bias_table,
18156 &global_motion,
18157 base_q_idx,
18158 TxbSet::Luma32,
18159 TxbSet::Luma32Inter,
18160 TxbSet::Chroma16,
18161 TX32,
18162 TX16,
18163 &scan32,
18164 &scan16,
18165 3,
18166 allow_high_precision_mv,
18167 force_integer_mv,
18168 interp_fixed,
18169 enable_dual_filter,
18170 tpl_frame.as_ref(),
18171 reference_select,
18172 enable_masked_compound,
18173 enable_interintra_compound,
18174 enable_jnt_comp,
18175 order_hint_bits,
18176 order_hint,
18177 ref_order_hints,
18178 skip_mode_present,
18179 skip_mode_frame,
18180 switchable_motion_mode,
18181 allow_warped_motion,
18182 false,
18183 BLOCK,
18184 BLOCK,
18185 allow_screen_content_tools,
18186 frame_width as usize,
18187 )?;
18188 }
18189 PARTITION_SPLIT => {
18190 for sub in 0..4 {
18191 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
18192 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
18193 continue;
18194 }
18195 let (has_cols16, has_rows16) = (
18196 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
18197 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
18198 );
18199 if !has_cols16 && !has_rows16 {
18200 return Err(unsupported(
18201 "a 16x16 inter block whose true edge cuts through both \
18202 axes needs a rectangular transform this decoder does \
18203 not code yet",
18204 ));
18205 }
18206 let at16 = (sr, sc);
18207 let ctx16 = neighbours.partition_ctx(at16, SUB);
18208 // lane-inter8 r1: a straddling 16x16 cannot name a
18209 // value (spec forces SPLIT, one gathered bit); an
18210 // interior one reads the real alphabet, and
18211 // `PARTITION_SPLIT` now recurses into four 8x8
18212 // inter leaves through the very same loop the
18213 // straddling case has always used.
18214 let part16 = if has_cols16 && has_rows16 {
18215 let p = dec.symbol(&mut cdfs.partition_w16[ctx16]);
18216 if std::env::var_os("EC_AV1_TRACE").is_some() {
18217 let (rng, _) = dec.debug_state();
18218 eprintln!(
18219 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={p} rng={rng}",
18220 sr as u32 * SUB_MI,
18221 sc as u32 * SUB_MI
18222 );
18223 }
18224 p
18225 } else {
18226 if has_cols16 {
18227 dec.symbol_fixed(&gather(
18228 &cdfs.partition_w16[ctx16],
18229 VERT_ALIKE,
18230 ));
18231 } else {
18232 dec.symbol_fixed(&gather(
18233 &cdfs.partition_w16[ctx16],
18234 HORZ_ALIKE,
18235 ));
18236 }
18237 PARTITION_SPLIT
18238 };
18239 if part16 == PARTITION_NONE {
18240 decode_inter_block(
18241 &mut dec,
18242 &mut cdfs,
18243 &mut neighbours,
18244 &mut grid,
18245 at16,
18246 SUB,
18247 mi_cols,
18248 mi_rows,
18249 &mut y,
18250 &mut u,
18251 &mut v,
18252 &ref_y,
18253 &ref_u,
18254 &ref_v,
18255 &ref_slots,
18256 &sign_bias_table,
18257 &global_motion,
18258 base_q_idx,
18259 TxbSet::Luma16,
18260 if reduced_tx_set {
18261 TxbSet::Luma16Inter
18262 } else {
18263 TxbSet::Luma16InterSet1
18264 },
18265 TxbSet::Chroma8,
18266 TX16,
18267 TX8,
18268 &scan16,
18269 &scan8,
18270 2,
18271 allow_high_precision_mv,
18272 force_integer_mv,
18273 interp_fixed,
18274 enable_dual_filter,
18275 tpl_frame.as_ref(),
18276 reference_select,
18277 enable_masked_compound,
18278 enable_interintra_compound,
18279 enable_jnt_comp,
18280 order_hint_bits,
18281 order_hint,
18282 ref_order_hints,
18283 skip_mode_present,
18284 skip_mode_frame,
18285 switchable_motion_mode,
18286 allow_warped_motion,
18287 false,
18288 SUB,
18289 SUB,
18290 allow_screen_content_tools,
18291 frame_width as usize,
18292 )?;
18293 } else if part16 != PARTITION_SPLIT {
18294 return Err(unsupported(
18295 "an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet)",
18296 ));
18297 } else {
18298 if has_cols16 && has_rows16 {
18299 INTER_SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
18300 }
18301 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
18302 let leaf_positions: Vec<(u32, u32)> = (0..4)
18303 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
18304 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
18305 .collect();
18306 // lane-scaledref r1: `decode_inter_block8` IS
18307 // threaded for a scaled reference now (its
18308 // single-ref, compound and OBMC MC all take
18309 // spec 7.11.3.3's scaled walk), but the one
18310 // recipe that reaches this path at all -- a
18311 // 64x72 superres fixture whose bottom 16-row
18312 // band straddles the true edge, so the
18313 // gathered split bit lands on 8x8 leaves --
18314 // DESYNCS inside the leaf itself
18315 // (`from_switchable_symbol` handed a 4th
18316 // symbol, mc.rs:200), the same
18317 // below-8x8 desync lane-sub8 r2 left open and
18318 // unrelated to scaling. So the scaled MC here
18319 // is unproven: refuse by name rather than
18320 // ship a capability claim no gate exercises.
18321 // Deleting these six lines is the whole lift
18322 // once the leaf8 desync is fixed.
18323 if ref_y.width != frame_width as usize
18324 || ref_slots.iter().flatten().any(|(py, _, _)| {
18325 py.width != frame_width as usize
18326 })
18327 {
18328 return Err(unsupported(
18329 "an 8x8 partition leaf under a scaled reference (superres, unimplemented)",
18330 ));
18331 }
18332 let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option<i8>)> = Vec::new();
18333 for (mr, mc) in leaf_positions {
18334 let leaf_mi = (mr as usize, mc as usize);
18335 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
18336 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
18337 if part8 != PARTITION_NONE {
18338 return Err(unsupported(
18339 "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)",
18340 ));
18341 }
18342 let (
18343 skip,
18344 is_inter,
18345 skip_mode_leaf,
18346 compound_ctx8,
18347 leaf_filter,
18348 leaf_refs,
18349 ) = decode_inter_block8(
18350 &mut dec,
18351 &mut cdfs,
18352 &mut neighbours,
18353 &mut grid,
18354 mi_cols,
18355 mi_rows,
18356 at16,
18357 leaf_mi,
18358 &mut y,
18359 &mut u,
18360 &mut v,
18361 &ref_y,
18362 &ref_u,
18363 &ref_v,
18364 &ref_slots,
18365 base_q_idx,
18366 &scan8,
18367 &scan4,
18368 allow_high_precision_mv,
18369 force_integer_mv,
18370 &global_motion,
18371 enable_dual_filter,
18372 reference_select,
18373 enable_masked_compound,
18374 enable_interintra_compound,
18375 enable_jnt_comp,
18376 order_hint_bits,
18377 order_hint,
18378 ref_order_hints,
18379 skip_mode_present,
18380 skip_mode_frame,
18381 reduced_tx_set,
18382 interp_fixed,
18383 switchable_motion_mode,
18384 allow_warped_motion,
18385 allow_screen_content_tools,
18386 &sign_bias_table,
18387 tpl_frame.as_ref(),
18388 frame_width as usize,
18389 )?;
18390 prev_leaves.push((leaf_mi, skip, is_inter, leaf_refs.0, leaf_refs.1));
18391 // lane-inter8 r2: stamp THIS leaf's own
18392 // 2x2-mi span before the next leaf reads
18393 // it as a neighbour -- the whole-16x16
18394 // stamp below only ever described the
18395 // last leaf, so three quarters of the
18396 // block carried the wrong skip/ref/inter
18397 // state into the next block's contexts
18398 // (class context-read-from-one-cell).
18399 // lane-gmaffine r3: with the mi-granular
18400 // band, the leaf's OWN switchable-filter
18401 // symbols go in here -- the `[3, 3]`
18402 // ("intra, no filter") sentinel this used
18403 // to stamp made `obmc_blend`'s
18404 // `neighbour_filter` PANIC as soon as a
18405 // sibling leaf blended one of these.
18406 neighbours.record_inter_rect_mi(
18407 leaf_mi,
18408 2,
18409 2,
18410 skip,
18411 is_inter,
18412 leaf_refs.0,
18413 leaf_filter,
18414 skip_mode_leaf,
18415 );
18416 if let Some(ref1) = leaf_refs.1
18417 && let Some((_, _, group_idx, idx)) = compound_ctx8
18418 {
18419 neighbours.record_compound_ctx_rect_mi(
18420 leaf_mi, 2, 2, ref1, group_idx, idx,
18421 );
18422 }
18423 }
18424 // lane-inter8 r2: the four per-leaf
18425 // `record_inter_rect_mi` stamps above replace
18426 // the single whole-16x16 one that used to run
18427 // here with the LAST leaf's state.
18428 }
18429 }
18430 }
18431 PARTITION_HORZ_B => {
18432 // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip +
18433 // 16x16 bottom-left + 16x16 bottom-right. aomenc
18434 // carves static regions into it; the strip is
18435 // decoded as a square 32x32 block: for a `skip`
18436 // block the symbol stream is identical to the true
18437 // 32x16 coding (no residual, no motion_mode/warp
18438 // symbol), and the square stamps it leaves over the
18439 // bottom half (neighbour arrays, skip/lf grids) are
18440 // re-stamped by the C/D leaves right after. The
18441 // mi-granular `left_side_mi` rows of a last-block-in-
18442 // tile strip leak 32-vs-16 only until the per-tile
18443 // `Neighbours::new` reset.
18444 EXTENDED_PARTITION_HITS.with(|c| c.set(c.get() + 1));
18445 let at32 = at;
18446 decode_inter_block(
18447 &mut dec,
18448 &mut cdfs,
18449 &mut neighbours,
18450 &mut grid,
18451 at32,
18452 BLOCK,
18453 mi_cols,
18454 mi_rows,
18455 &mut y,
18456 &mut u,
18457 &mut v,
18458 &ref_y,
18459 &ref_u,
18460 &ref_v,
18461 &ref_slots,
18462 &sign_bias_table,
18463 &global_motion,
18464 base_q_idx,
18465 TxbSet::Luma32,
18466 TxbSet::Luma32Inter,
18467 TxbSet::Chroma16,
18468 TX32,
18469 TX16,
18470 &scan32,
18471 &scan16,
18472 3,
18473 allow_high_precision_mv,
18474 force_integer_mv,
18475 interp_fixed,
18476 enable_dual_filter,
18477 tpl_frame.as_ref(),
18478 reference_select,
18479 enable_masked_compound,
18480 enable_interintra_compound,
18481 enable_jnt_comp,
18482 order_hint_bits,
18483 order_hint,
18484 ref_order_hints,
18485 skip_mode_present,
18486 skip_mode_frame,
18487 switchable_motion_mode,
18488 allow_warped_motion,
18489 true,
18490 // lane-rect r2: the top strip's TRUE 32x16
18491 // footprint (was BLOCK,BLOCK -- the same square
18492 // corner-cut rect-flake-1 exposed on HORZ).
18493 BLOCK,
18494 SUB,
18495 allow_screen_content_tools,
18496 frame_width as usize,
18497 )?;
18498 if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows {
18499 decode_inter_block(
18500 &mut dec,
18501 &mut cdfs,
18502 &mut neighbours,
18503 &mut grid,
18504 (r32 as usize * 2 + 1, c32 as usize * 2),
18505 SUB,
18506 mi_cols,
18507 mi_rows,
18508 &mut y,
18509 &mut u,
18510 &mut v,
18511 &ref_y,
18512 &ref_u,
18513 &ref_v,
18514 &ref_slots,
18515 &sign_bias_table,
18516 &global_motion,
18517 base_q_idx,
18518 TxbSet::Luma16,
18519 if reduced_tx_set {
18520 TxbSet::Luma16Inter
18521 } else {
18522 TxbSet::Luma16InterSet1
18523 },
18524 TxbSet::Chroma8,
18525 TX16,
18526 TX8,
18527 &scan16,
18528 &scan8,
18529 2,
18530 allow_high_precision_mv,
18531 force_integer_mv,
18532 interp_fixed,
18533 enable_dual_filter,
18534 tpl_frame.as_ref(),
18535 reference_select,
18536 enable_masked_compound,
18537 enable_interintra_compound,
18538 enable_jnt_comp,
18539 order_hint_bits,
18540 order_hint,
18541 ref_order_hints,
18542 skip_mode_present,
18543 skip_mode_frame,
18544 switchable_motion_mode,
18545 allow_warped_motion,
18546 false,
18547 SUB,
18548 SUB,
18549 allow_screen_content_tools,
18550 frame_width as usize,
18551 )?;
18552 if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols {
18553 decode_inter_block(
18554 &mut dec,
18555 &mut cdfs,
18556 &mut neighbours,
18557 &mut grid,
18558 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
18559 SUB,
18560 mi_cols,
18561 mi_rows,
18562 &mut y,
18563 &mut u,
18564 &mut v,
18565 &ref_y,
18566 &ref_u,
18567 &ref_v,
18568 &ref_slots,
18569 &sign_bias_table,
18570 &global_motion,
18571 base_q_idx,
18572 TxbSet::Luma16,
18573 if reduced_tx_set {
18574 TxbSet::Luma16Inter
18575 } else {
18576 TxbSet::Luma16InterSet1
18577 },
18578 TxbSet::Chroma8,
18579 TX16,
18580 TX8,
18581 &scan16,
18582 &scan8,
18583 2,
18584 allow_high_precision_mv,
18585 force_integer_mv,
18586 interp_fixed,
18587 enable_dual_filter,
18588 tpl_frame.as_ref(),
18589 reference_select,
18590 enable_masked_compound,
18591 enable_interintra_compound,
18592 enable_jnt_comp,
18593 order_hint_bits,
18594 order_hint,
18595 ref_order_hints,
18596 skip_mode_present,
18597 skip_mode_frame,
18598 switchable_motion_mode,
18599 allow_warped_motion,
18600 false,
18601 SUB,
18602 SUB,
18603 allow_screen_content_tools,
18604 frame_width as usize,
18605 )?;
18606 }
18607 }
18608 }
18609 PARTITION_HORZ => {
18610 // lane-rect r2: two true 32x16 strips. Both read at
18611 // `side=BLOCK` (CDF/size-class selection stays square,
18612 // matching HORZ_B's accepted corner-cut) but bw4/bh4
18613 // (mvstack.rs, `motion_mode_eligible`) now derive from
18614 // `write_w`/`write_h`'s true 32x16 footprint -- the
18615 // pin's fix (r1's finding).
18616 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
18617 decode_inter_block(
18618 &mut dec,
18619 &mut cdfs,
18620 &mut neighbours,
18621 &mut grid,
18622 at,
18623 BLOCK,
18624 mi_cols,
18625 mi_rows,
18626 &mut y,
18627 &mut u,
18628 &mut v,
18629 &ref_y,
18630 &ref_u,
18631 &ref_v,
18632 &ref_slots,
18633 &sign_bias_table,
18634 &global_motion,
18635 base_q_idx,
18636 TxbSet::Luma32,
18637 TxbSet::Luma32Inter,
18638 TxbSet::Chroma16,
18639 TX32,
18640 TX16,
18641 &scan32,
18642 &scan16,
18643 3,
18644 allow_high_precision_mv,
18645 force_integer_mv,
18646 interp_fixed,
18647 enable_dual_filter,
18648 tpl_frame.as_ref(),
18649 reference_select,
18650 enable_masked_compound,
18651 enable_interintra_compound,
18652 enable_jnt_comp,
18653 order_hint_bits,
18654 order_hint,
18655 ref_order_hints,
18656 skip_mode_present,
18657 skip_mode_frame,
18658 switchable_motion_mode,
18659 allow_warped_motion,
18660 true,
18661 BLOCK,
18662 SUB,
18663 allow_screen_content_tools,
18664 frame_width as usize,
18665 )?;
18666 decode_inter_block(
18667 &mut dec,
18668 &mut cdfs,
18669 &mut neighbours,
18670 &mut grid,
18671 (r32 as usize * 2 + 1, c32 as usize * 2),
18672 BLOCK,
18673 mi_cols,
18674 mi_rows,
18675 &mut y,
18676 &mut u,
18677 &mut v,
18678 &ref_y,
18679 &ref_u,
18680 &ref_v,
18681 &ref_slots,
18682 &sign_bias_table,
18683 &global_motion,
18684 base_q_idx,
18685 TxbSet::Luma32,
18686 TxbSet::Luma32Inter,
18687 TxbSet::Chroma16,
18688 TX32,
18689 TX16,
18690 &scan32,
18691 &scan16,
18692 3,
18693 allow_high_precision_mv,
18694 force_integer_mv,
18695 interp_fixed,
18696 enable_dual_filter,
18697 tpl_frame.as_ref(),
18698 reference_select,
18699 enable_masked_compound,
18700 enable_interintra_compound,
18701 enable_jnt_comp,
18702 order_hint_bits,
18703 order_hint,
18704 ref_order_hints,
18705 skip_mode_present,
18706 skip_mode_frame,
18707 switchable_motion_mode,
18708 allow_warped_motion,
18709 true,
18710 BLOCK,
18711 SUB,
18712 allow_screen_content_tools,
18713 frame_width as usize,
18714 )?;
18715 }
18716 PARTITION_VERT => {
18717 // lane-rect r2: mirror of PARTITION_HORZ above with
18718 // width/height swapped.
18719 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
18720 decode_inter_block(
18721 &mut dec,
18722 &mut cdfs,
18723 &mut neighbours,
18724 &mut grid,
18725 at,
18726 BLOCK,
18727 mi_cols,
18728 mi_rows,
18729 &mut y,
18730 &mut u,
18731 &mut v,
18732 &ref_y,
18733 &ref_u,
18734 &ref_v,
18735 &ref_slots,
18736 &sign_bias_table,
18737 &global_motion,
18738 base_q_idx,
18739 TxbSet::Luma32,
18740 TxbSet::Luma32Inter,
18741 TxbSet::Chroma16,
18742 TX32,
18743 TX16,
18744 &scan32,
18745 &scan16,
18746 3,
18747 allow_high_precision_mv,
18748 force_integer_mv,
18749 interp_fixed,
18750 enable_dual_filter,
18751 tpl_frame.as_ref(),
18752 reference_select,
18753 enable_masked_compound,
18754 enable_interintra_compound,
18755 enable_jnt_comp,
18756 order_hint_bits,
18757 order_hint,
18758 ref_order_hints,
18759 skip_mode_present,
18760 skip_mode_frame,
18761 switchable_motion_mode,
18762 allow_warped_motion,
18763 true,
18764 SUB,
18765 BLOCK,
18766 allow_screen_content_tools,
18767 frame_width as usize,
18768 )?;
18769 decode_inter_block(
18770 &mut dec,
18771 &mut cdfs,
18772 &mut neighbours,
18773 &mut grid,
18774 (r32 as usize * 2, c32 as usize * 2 + 1),
18775 BLOCK,
18776 mi_cols,
18777 mi_rows,
18778 &mut y,
18779 &mut u,
18780 &mut v,
18781 &ref_y,
18782 &ref_u,
18783 &ref_v,
18784 &ref_slots,
18785 &sign_bias_table,
18786 &global_motion,
18787 base_q_idx,
18788 TxbSet::Luma32,
18789 TxbSet::Luma32Inter,
18790 TxbSet::Chroma16,
18791 TX32,
18792 TX16,
18793 &scan32,
18794 &scan16,
18795 3,
18796 allow_high_precision_mv,
18797 force_integer_mv,
18798 interp_fixed,
18799 enable_dual_filter,
18800 tpl_frame.as_ref(),
18801 reference_select,
18802 enable_masked_compound,
18803 enable_interintra_compound,
18804 enable_jnt_comp,
18805 order_hint_bits,
18806 order_hint,
18807 ref_order_hints,
18808 skip_mode_present,
18809 skip_mode_frame,
18810 switchable_motion_mode,
18811 allow_warped_motion,
18812 true,
18813 SUB,
18814 BLOCK,
18815 allow_screen_content_tools,
18816 frame_width as usize,
18817 )?;
18818 }
18819 PARTITION_HORZ_A => {
18820 // lane-partab r1: two 16x16 squares on top + a true
18821 // 32x16 strip below (libaom decode_partition
18822 // PARTITION_HORZ_A: TL, TR, bottom strip).
18823 PARTAB_HITS.with(|c| c.set(c.get() + 1));
18824 decode_inter_block(
18825 &mut dec,
18826 &mut cdfs,
18827 &mut neighbours,
18828 &mut grid,
18829 at,
18830 SUB,
18831 mi_cols,
18832 mi_rows,
18833 &mut y,
18834 &mut u,
18835 &mut v,
18836 &ref_y,
18837 &ref_u,
18838 &ref_v,
18839 &ref_slots,
18840 &sign_bias_table,
18841 &global_motion,
18842 base_q_idx,
18843 TxbSet::Luma16,
18844 if reduced_tx_set {
18845 TxbSet::Luma16Inter
18846 } else {
18847 TxbSet::Luma16InterSet1
18848 },
18849 TxbSet::Chroma8,
18850 TX16,
18851 TX8,
18852 &scan16,
18853 &scan8,
18854 2,
18855 allow_high_precision_mv,
18856 force_integer_mv,
18857 interp_fixed,
18858 enable_dual_filter,
18859 tpl_frame.as_ref(),
18860 reference_select,
18861 enable_masked_compound,
18862 enable_interintra_compound,
18863 enable_jnt_comp,
18864 order_hint_bits,
18865 order_hint,
18866 ref_order_hints,
18867 skip_mode_present,
18868 skip_mode_frame,
18869 switchable_motion_mode,
18870 allow_warped_motion,
18871 false,
18872 SUB,
18873 SUB,
18874 allow_screen_content_tools,
18875 frame_width as usize,
18876 )?;
18877 decode_inter_block(
18878 &mut dec,
18879 &mut cdfs,
18880 &mut neighbours,
18881 &mut grid,
18882 (r32 as usize * 2, c32 as usize * 2 + 1),
18883 SUB,
18884 mi_cols,
18885 mi_rows,
18886 &mut y,
18887 &mut u,
18888 &mut v,
18889 &ref_y,
18890 &ref_u,
18891 &ref_v,
18892 &ref_slots,
18893 &sign_bias_table,
18894 &global_motion,
18895 base_q_idx,
18896 TxbSet::Luma16,
18897 if reduced_tx_set {
18898 TxbSet::Luma16Inter
18899 } else {
18900 TxbSet::Luma16InterSet1
18901 },
18902 TxbSet::Chroma8,
18903 TX16,
18904 TX8,
18905 &scan16,
18906 &scan8,
18907 2,
18908 allow_high_precision_mv,
18909 force_integer_mv,
18910 interp_fixed,
18911 enable_dual_filter,
18912 tpl_frame.as_ref(),
18913 reference_select,
18914 enable_masked_compound,
18915 enable_interintra_compound,
18916 enable_jnt_comp,
18917 order_hint_bits,
18918 order_hint,
18919 ref_order_hints,
18920 skip_mode_present,
18921 skip_mode_frame,
18922 switchable_motion_mode,
18923 allow_warped_motion,
18924 false,
18925 SUB,
18926 SUB,
18927 allow_screen_content_tools,
18928 frame_width as usize,
18929 )?;
18930 decode_inter_block(
18931 &mut dec,
18932 &mut cdfs,
18933 &mut neighbours,
18934 &mut grid,
18935 (r32 as usize * 2 + 1, c32 as usize * 2),
18936 BLOCK,
18937 mi_cols,
18938 mi_rows,
18939 &mut y,
18940 &mut u,
18941 &mut v,
18942 &ref_y,
18943 &ref_u,
18944 &ref_v,
18945 &ref_slots,
18946 &sign_bias_table,
18947 &global_motion,
18948 base_q_idx,
18949 TxbSet::Luma32,
18950 TxbSet::Luma32Inter,
18951 TxbSet::Chroma16,
18952 TX32,
18953 TX16,
18954 &scan32,
18955 &scan16,
18956 3,
18957 allow_high_precision_mv,
18958 force_integer_mv,
18959 interp_fixed,
18960 enable_dual_filter,
18961 tpl_frame.as_ref(),
18962 reference_select,
18963 enable_masked_compound,
18964 enable_interintra_compound,
18965 enable_jnt_comp,
18966 order_hint_bits,
18967 order_hint,
18968 ref_order_hints,
18969 skip_mode_present,
18970 skip_mode_frame,
18971 switchable_motion_mode,
18972 allow_warped_motion,
18973 true,
18974 BLOCK,
18975 SUB,
18976 allow_screen_content_tools,
18977 frame_width as usize,
18978 )?;
18979 }
18980 PARTITION_VERT_A => {
18981 // lane-partab r1: mirror of PARTITION_HORZ_A with
18982 // width/height swapped (TL, BL, right 16x32 strip).
18983 PARTAB_HITS.with(|c| c.set(c.get() + 1));
18984 let _vert_ab = crate::encode::Reach::vert_ab_partition();
18985 decode_inter_block(
18986 &mut dec,
18987 &mut cdfs,
18988 &mut neighbours,
18989 &mut grid,
18990 at,
18991 SUB,
18992 mi_cols,
18993 mi_rows,
18994 &mut y,
18995 &mut u,
18996 &mut v,
18997 &ref_y,
18998 &ref_u,
18999 &ref_v,
19000 &ref_slots,
19001 &sign_bias_table,
19002 &global_motion,
19003 base_q_idx,
19004 TxbSet::Luma16,
19005 if reduced_tx_set {
19006 TxbSet::Luma16Inter
19007 } else {
19008 TxbSet::Luma16InterSet1
19009 },
19010 TxbSet::Chroma8,
19011 TX16,
19012 TX8,
19013 &scan16,
19014 &scan8,
19015 2,
19016 allow_high_precision_mv,
19017 force_integer_mv,
19018 interp_fixed,
19019 enable_dual_filter,
19020 tpl_frame.as_ref(),
19021 reference_select,
19022 enable_masked_compound,
19023 enable_interintra_compound,
19024 enable_jnt_comp,
19025 order_hint_bits,
19026 order_hint,
19027 ref_order_hints,
19028 skip_mode_present,
19029 skip_mode_frame,
19030 switchable_motion_mode,
19031 allow_warped_motion,
19032 false,
19033 SUB,
19034 SUB,
19035 allow_screen_content_tools,
19036 frame_width as usize,
19037 )?;
19038 decode_inter_block(
19039 &mut dec,
19040 &mut cdfs,
19041 &mut neighbours,
19042 &mut grid,
19043 (r32 as usize * 2 + 1, c32 as usize * 2),
19044 SUB,
19045 mi_cols,
19046 mi_rows,
19047 &mut y,
19048 &mut u,
19049 &mut v,
19050 &ref_y,
19051 &ref_u,
19052 &ref_v,
19053 &ref_slots,
19054 &sign_bias_table,
19055 &global_motion,
19056 base_q_idx,
19057 TxbSet::Luma16,
19058 if reduced_tx_set {
19059 TxbSet::Luma16Inter
19060 } else {
19061 TxbSet::Luma16InterSet1
19062 },
19063 TxbSet::Chroma8,
19064 TX16,
19065 TX8,
19066 &scan16,
19067 &scan8,
19068 2,
19069 allow_high_precision_mv,
19070 force_integer_mv,
19071 interp_fixed,
19072 enable_dual_filter,
19073 tpl_frame.as_ref(),
19074 reference_select,
19075 enable_masked_compound,
19076 enable_interintra_compound,
19077 enable_jnt_comp,
19078 order_hint_bits,
19079 order_hint,
19080 ref_order_hints,
19081 skip_mode_present,
19082 skip_mode_frame,
19083 switchable_motion_mode,
19084 allow_warped_motion,
19085 false,
19086 SUB,
19087 SUB,
19088 allow_screen_content_tools,
19089 frame_width as usize,
19090 )?;
19091 decode_inter_block(
19092 &mut dec,
19093 &mut cdfs,
19094 &mut neighbours,
19095 &mut grid,
19096 (r32 as usize * 2, c32 as usize * 2 + 1),
19097 BLOCK,
19098 mi_cols,
19099 mi_rows,
19100 &mut y,
19101 &mut u,
19102 &mut v,
19103 &ref_y,
19104 &ref_u,
19105 &ref_v,
19106 &ref_slots,
19107 &sign_bias_table,
19108 &global_motion,
19109 base_q_idx,
19110 TxbSet::Luma32,
19111 TxbSet::Luma32Inter,
19112 TxbSet::Chroma16,
19113 TX32,
19114 TX16,
19115 &scan32,
19116 &scan16,
19117 3,
19118 allow_high_precision_mv,
19119 force_integer_mv,
19120 interp_fixed,
19121 enable_dual_filter,
19122 tpl_frame.as_ref(),
19123 reference_select,
19124 enable_masked_compound,
19125 enable_interintra_compound,
19126 enable_jnt_comp,
19127 order_hint_bits,
19128 order_hint,
19129 ref_order_hints,
19130 skip_mode_present,
19131 skip_mode_frame,
19132 switchable_motion_mode,
19133 allow_warped_motion,
19134 true,
19135 SUB,
19136 BLOCK,
19137 allow_screen_content_tools,
19138 frame_width as usize,
19139 )?;
19140 }
19141 PARTITION_VERT_B => {
19142 // lane-partab r1: true 16x32 strip on the left + two
19143 // 16x16 squares on the right (libaom decode_partition
19144 // PARTITION_VERT_B: left strip, TR, BR).
19145 PARTAB_HITS.with(|c| c.set(c.get() + 1));
19146 let _vert_ab = crate::encode::Reach::vert_ab_partition();
19147 decode_inter_block(
19148 &mut dec,
19149 &mut cdfs,
19150 &mut neighbours,
19151 &mut grid,
19152 at,
19153 BLOCK,
19154 mi_cols,
19155 mi_rows,
19156 &mut y,
19157 &mut u,
19158 &mut v,
19159 &ref_y,
19160 &ref_u,
19161 &ref_v,
19162 &ref_slots,
19163 &sign_bias_table,
19164 &global_motion,
19165 base_q_idx,
19166 TxbSet::Luma32,
19167 TxbSet::Luma32Inter,
19168 TxbSet::Chroma16,
19169 TX32,
19170 TX16,
19171 &scan32,
19172 &scan16,
19173 3,
19174 allow_high_precision_mv,
19175 force_integer_mv,
19176 interp_fixed,
19177 enable_dual_filter,
19178 tpl_frame.as_ref(),
19179 reference_select,
19180 enable_masked_compound,
19181 enable_interintra_compound,
19182 enable_jnt_comp,
19183 order_hint_bits,
19184 order_hint,
19185 ref_order_hints,
19186 skip_mode_present,
19187 skip_mode_frame,
19188 switchable_motion_mode,
19189 allow_warped_motion,
19190 true,
19191 SUB,
19192 BLOCK,
19193 allow_screen_content_tools,
19194 frame_width as usize,
19195 )?;
19196 decode_inter_block(
19197 &mut dec,
19198 &mut cdfs,
19199 &mut neighbours,
19200 &mut grid,
19201 (r32 as usize * 2, c32 as usize * 2 + 1),
19202 SUB,
19203 mi_cols,
19204 mi_rows,
19205 &mut y,
19206 &mut u,
19207 &mut v,
19208 &ref_y,
19209 &ref_u,
19210 &ref_v,
19211 &ref_slots,
19212 &sign_bias_table,
19213 &global_motion,
19214 base_q_idx,
19215 TxbSet::Luma16,
19216 if reduced_tx_set {
19217 TxbSet::Luma16Inter
19218 } else {
19219 TxbSet::Luma16InterSet1
19220 },
19221 TxbSet::Chroma8,
19222 TX16,
19223 TX8,
19224 &scan16,
19225 &scan8,
19226 2,
19227 allow_high_precision_mv,
19228 force_integer_mv,
19229 interp_fixed,
19230 enable_dual_filter,
19231 tpl_frame.as_ref(),
19232 reference_select,
19233 enable_masked_compound,
19234 enable_interintra_compound,
19235 enable_jnt_comp,
19236 order_hint_bits,
19237 order_hint,
19238 ref_order_hints,
19239 skip_mode_present,
19240 skip_mode_frame,
19241 switchable_motion_mode,
19242 allow_warped_motion,
19243 false,
19244 SUB,
19245 SUB,
19246 allow_screen_content_tools,
19247 frame_width as usize,
19248 )?;
19249 decode_inter_block(
19250 &mut dec,
19251 &mut cdfs,
19252 &mut neighbours,
19253 &mut grid,
19254 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
19255 SUB,
19256 mi_cols,
19257 mi_rows,
19258 &mut y,
19259 &mut u,
19260 &mut v,
19261 &ref_y,
19262 &ref_u,
19263 &ref_v,
19264 &ref_slots,
19265 &sign_bias_table,
19266 &global_motion,
19267 base_q_idx,
19268 TxbSet::Luma16,
19269 if reduced_tx_set {
19270 TxbSet::Luma16Inter
19271 } else {
19272 TxbSet::Luma16InterSet1
19273 },
19274 TxbSet::Chroma8,
19275 TX16,
19276 TX8,
19277 &scan16,
19278 &scan8,
19279 2,
19280 allow_high_precision_mv,
19281 force_integer_mv,
19282 interp_fixed,
19283 enable_dual_filter,
19284 tpl_frame.as_ref(),
19285 reference_select,
19286 enable_masked_compound,
19287 enable_interintra_compound,
19288 enable_jnt_comp,
19289 order_hint_bits,
19290 order_hint,
19291 ref_order_hints,
19292 skip_mode_present,
19293 skip_mode_frame,
19294 switchable_motion_mode,
19295 allow_warped_motion,
19296 false,
19297 SUB,
19298 SUB,
19299 allow_screen_content_tools,
19300 frame_width as usize,
19301 )?;
19302 }
19303 _ => {
19304 return Err(unsupported(format!(
19305 "an INTER 32x32 partition type this decoder does not code (value={part32})"
19306 )));
19307 }
19308 }
19309 }
19310 }
19311 }
19312
19313 if tile_num == tile_info.context_update_tile_id {
19314 result_cdfs = cdfs;
19315 }
19316 }
19317
19318 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
19319 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
19320 // that isolate whether a decode-order frame's mismatch already exists
19321 // in reconstruction (this dump) vs is introduced by the loop filter
19322 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
19323 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
19324 use std::io::Write;
19325 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
19326 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
19327 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
19328 let _ = f.write_all(&narrow(&y));
19329 let _ = f.write_all(&narrow(&u));
19330 let _ = f.write_all(&narrow(&v));
19331 }
19332 } else {
19333 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
19334 }
19335 apply_deblock(
19336 &mut y,
19337 &mut u,
19338 &mut v,
19339 loop_filter,
19340 &neighbours,
19341 frame_width as usize,
19342 frame_height as usize,
19343 );
19344 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
19345 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
19346 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
19347 // dump above these bisect WHICH filter stage introduced a mismatch.
19348 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
19349 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
19350 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
19351 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
19352
19353 let motion_field = build_motion_field(
19354 &grid,
19355 mi_cols as usize,
19356 mi_rows as usize,
19357 order_hint,
19358 ref_order_hints,
19359 );
19360
19361 let (fw, fh) = (frame_width as usize, frame_height as usize);
19362 if fw == width && fh == height {
19363 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
19364 return Ok((
19365 Picture {
19366 width,
19367 height,
19368 y: y.data,
19369 u: u.data,
19370 v: v.data,
19371 },
19372 result_cdfs,
19373 motion_field,
19374 ));
19375 }
19376 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
19377 let mut out = Vec::with_capacity(w * h);
19378 for row in 0..h {
19379 out.extend(plane.data[row * plane.width..][..w].iter().copied());
19380 }
19381 out
19382 };
19383 // lane-superres r10 (fixed r9): same real-margin stash as
19384 // `decode_key_frame_tile_with_cdfs` (see that function's comment) -- the
19385 // real reconstructed extent is the mi-aligned `true_width`/`true_height`
19386 // (`mi_cols`/`mi_rows` * 4), NOT the superblock-padded `width`/`height`
19387 // this branch was reading before: columns `[true_width, width)` were
19388 // never actually coded (the last partial superblock stops at
19389 // `true_width`), so stashing out to `width` handed the chroma upscale's
19390 // right-edge replicate a slice of uninitialized/stale buffer one column
19391 // early -- the same shorten-vs-replicate shape as `av1-truesize`. The
19392 // key-frame branch above already used `true_width`/`true_height`; this
19393 // just matches it.
19394 LAST_FRAME_WIDE_MARGIN.with(|m| {
19395 *m.borrow_mut() = if true_width > fw || true_height > fh {
19396 Some(Picture {
19397 width: true_width,
19398 height: true_height,
19399 y: crop(&y, true_width, true_height),
19400 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
19401 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
19402 })
19403 } else {
19404 None
19405 }
19406 });
19407 Ok((
19408 Picture {
19409 width: fw,
19410 height: fh,
19411 y: crop(&y, fw, fh),
19412 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
19413 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
19414 },
19415 result_cdfs,
19416 motion_field,
19417 ))
19418}
19419
19420#[cfg(test)]
19421mod tests {
19422
19423 /// lane-fistrip r1 (class `enumerate-the-table-domain`): every block
19424 /// shape this decoder can hand [`filter_intra_size_class_rect`], against
19425 /// `av1_filter_intra_allowed_bsize` (`block_size_wide <= 32 &&
19426 /// block_size_high <= 32`) and `default_filter_intra_cdfs`
19427 /// (entropymode.c) row by row. A class that exists must carry ITS OWN
19428 /// bsize's default probability -- a wrong row is a silently different
19429 /// symbol, not a decode error. The shapes with no class are listed here
19430 /// with their reason so the residue is pinned rather than implied.
19431 #[test]
19432 fn filter_intra_classes_carry_their_own_libaom_default_row() {
19433 // `default_filter_intra_cdfs[bsize]`, BLOCK_SIZES_ALL order, as
19434 // (width, height, default, refused_by) for the shapes <= 32 on both
19435 // axes. The first three fields are GENERATED from the oracle by
19436 // `scripts/extract-filter-intra-cdfs.py` (it reads BLOCK_SIZES_ALL's
19437 // order from enums.h and the table from entropymode.c, so no hand
19438 // transcription can drift -- lane-fistrip r1 listed the four 1:4
19439 // shapes as 16384 out of exactly that kind of guess; their real rows
19440 // are 12770/10368/20229/18101). `refused_by` is `None` for a shape
19441 // this decoder's partition tree reaches today -- it must own a class,
19442 // and that class must carry exactly this row -- and the refusal
19443 // string that blocks the shape otherwise. Either way the row is
19444 // pinned HERE, so the round that lifts one of those refusals cannot
19445 // land a wrong CDF row for the shape it unlocks.
19446 const PART16: &str = "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes \
19447 only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)";
19448 let libaom: &[(usize, usize, u16, Option<&str>)] = &[
19449 (4, 4, 4621, None),
19450 (4, 8, 6743, None),
19451 (8, 4, 5893, None),
19452 (8, 8, 7866, None),
19453 (8, 16, 12551, None),
19454 (16, 8, 9394, None),
19455 (16, 16, 12408, None),
19456 (16, 32, 14301, None),
19457 (32, 16, 12756, None),
19458 (32, 32, 22343, None),
19459 // The 1:4 strips: a 16x16-level PARTITION_HORZ_4/VERT_4 gives
19460 // 4x16/16x4 (still refused by name before any leaf is coded),
19461 // a 32x32-level one 8x32/32x8.
19462 (4, 16, 12770, Some(PART16)),
19463 (16, 4, 10368, Some(PART16)),
19464 // lane-fi32x8 r1: the 32-level pair is coded (four 32x8/8x32
19465 // strips per `PARTITION_HORZ_4`/`VERT_4`) and now owns classes
19466 // 10/11; only the 16-level pair is still refused before any leaf.
19467 (8, 32, 20229, None),
19468 (32, 8, 18101, None),
19469 ];
19470 let mut classes_seen = std::collections::BTreeSet::new();
19471 for &(bw, bh, default, refused_by) in libaom {
19472 match filter_intra_size_class_rect(bw, bh) {
19473 Some(class) => {
19474 assert!(
19475 refused_by.is_none(),
19476 "{bw}x{bh} has a CDF class but is listed as refused by {refused_by:?} -- \
19477 one of the two is stale"
19478 );
19479 assert_eq!(
19480 crate::cdf::FILTER_INTRA[class][0],
19481 default,
19482 "{bw}x{bh} (class {class}) must carry default_filter_intra_cdfs' own row"
19483 );
19484 assert_eq!(
19485 &crate::cdf::FILTER_INTRA[class][1..],
19486 &[32768u16, 0][..],
19487 "{bw}x{bh} (class {class}) is a 2-symbol CDF: {{p, 32768, count}}"
19488 );
19489 assert!(
19490 classes_seen.insert(class),
19491 "class {class} is claimed by two shapes -- one of them reads the other's \
19492 probability"
19493 );
19494 }
19495 None => {
19496 let why = refused_by.unwrap_or_else(|| {
19497 panic!(
19498 "{bw}x{bh} is inside av1_filter_intra_allowed_bsize and reachable, \
19499 but has no CDF class -- its use_filter_intra symbol is never read"
19500 )
19501 });
19502 assert!(!why.is_empty(), "{bw}x{bh}'s refusal string must name the blocker");
19503 }
19504 }
19505 }
19506 // The other direction: every row of `cdf::FILTER_INTRA` was claimed
19507 // by exactly one shape above, so no row can be left over (or shared)
19508 // once a class is added or removed.
19509 assert_eq!(
19510 classes_seen.len(),
19511 crate::cdf::FILTER_INTRA.len(),
19512 "cdf::FILTER_INTRA has {} rows but only {:?} are claimed by an allowed shape",
19513 crate::cdf::FILTER_INTRA.len(),
19514 classes_seen
19515 );
19516 // Past the bound on either axis: no symbol at all (spec
19517 // `filter_intra_mode_info` never reads one).
19518 for (bw, bh) in [(64, 64), (64, 32), (32, 64)] {
19519 assert!(
19520 filter_intra_size_class_rect(bw, bh).is_none(),
19521 "{bw}x{bh} is past av1_filter_intra_allowed_bsize's <=32 bound"
19522 );
19523 }
19524 }
19525 use super::*;
19526
19527 /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR --
19528 /// `SCAN_4X16[i]` must name the transpose of the position
19529 /// `SCAN_16X4[i]` names (class scan-weights-cross-axis: a naive copy of
19530 /// libaom's column-major `default_scan_*` installs the transpose and only
19531 /// an asymmetric check catches it). Also pins both as permutations, and
19532 /// pins the same relation for the 32x8/8x32 luma pair this arm reuses.
19533 #[test]
19534 fn the_rect4_scans_are_transposed_pairs() {
19535 for (a, b, w, h) in [
19536 (&SCAN_16X4[..], &SCAN_4X16[..], 16usize, 4usize),
19537 (&SCAN_32X8[..], &SCAN_8X32[..], 32, 8),
19538 ] {
19539 let mut seen_a: Vec<u16> = a.to_vec();
19540 seen_a.sort_unstable();
19541 assert_eq!(
19542 seen_a,
19543 (0..(w * h) as u16).collect::<Vec<_>>(),
19544 "{w}x{h} scan is not a permutation of its positions"
19545 );
19546 for (i, (&pa, &pb)) in a.iter().zip(b.iter()).enumerate() {
19547 let (row, col) = (pa as usize / w, pa as usize % w);
19548 assert_eq!(
19549 pb as usize,
19550 col * w.min(h) + row,
19551 "scan step {i}: {w}x{h} visits (row {row}, col {col}) but its transpose \
19552 visits position {pb}"
19553 );
19554 }
19555 }
19556 }
19557
19558 /// lane-rectsplit r4 (class `enumerate-table-domain`): [`base_ctx`]'s
19559 /// `TX_CLASS_2D` arm must, over the WHOLE 5x5 domain of both rect shapes
19560 /// and the square one, return exactly what libaom's
19561 /// `av1_nz_map_ctx_offset[tx_size][coeff_idx]` holds -- the flat tables
19562 /// transcribed in [`cdf`], read at libaom's own COLUMN-major
19563 /// `coeff_idx = col * 32 + row`, i.e. `table[col][row]`. r1..r3 read them
19564 /// `[row][col]`, which is the transpose (the OTHER shape's rule, with 11
19565 /// and 16 swapped): it desynced the first superblock strip whose luma
19566 /// corner held a coefficient off the first row/column.
19567 #[test]
19568 fn base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain() {
19569 let grid = [0i32; 32 * 32];
19570 for (shape, table) in [
19571 (Some((64usize, 32usize)), &cdf::NZ_MAP_CTX_OFFSET_64X32),
19572 (Some((32, 64)), &cdf::NZ_MAP_CTX_OFFSET_32X64),
19573 (None, &cdf::NZ_MAP_CTX_OFFSET_32),
19574 ] {
19575 for row in 0..5usize {
19576 for col in 0..5usize {
19577 // An all-zero neighbourhood makes the magnitude term 0,
19578 // so `base_ctx` returns the offset itself.
19579 let got = base_ctx(&grid, 32, row, col, TxClass::TwoD, shape);
19580 let want = if row == 0 && col == 0 {
19581 0
19582 } else {
19583 table[col][row] as usize
19584 };
19585 assert_eq!(got, want, "{shape:?} at (row {row}, col {col})");
19586 }
19587 }
19588 }
19589 }
19590
19591 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
19592 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
19593 // single-purpose writers with their own skip-context rule (keyed to
19594 // superblock position, not the neighbour-tracked one every real block
19595 // uses), never reached by `encode_key_frame_with_modes` — decoding them
19596 // would need a second, throwaway context convention next to the real
19597 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
19598 // this decoder's one target, and the round-trip test below is against
19599 // that path with real quantised residual, not a synthetic all-DC frame.
19600
19601 /// [`SCAN_8X4`]/[`SCAN_4X8`] (lane-rectx r2): a bijection check alone
19602 /// cannot catch a transposed pair -- a swap of two orientation tables is
19603 /// still a bijection over the same 32 positions. This pins BOTH arrays
19604 /// at once, element-for-element, against literal transcriptions of
19605 /// libaom's real `default_scan_4x8`/`default_scan_8x4` in
19606 /// `av1/common/scan.c` (`~/.cache/aom-oracle/src`, read directly for
19607 /// this test, not re-derived from the zigzag formula). The two source
19608 /// sequences are themselves different in their own right (not equal to
19609 /// each other), so this is asymmetric in the two axes: if the repo's
19610 /// `SCAN_8X4`/`SCAN_4X8` were swapped with each other, one side of this
19611 /// assert pair would fail even though each individual array would still
19612 /// pass a same-orientation bijection test.
19613 #[test]
19614 fn scan_8x4_and_4x8_are_not_transposed_against_each_other() {
19615 // libaom `default_scan_4x8` verbatim (scan.c:29-32) -- this repo
19616 // names it `SCAN_8X4` under the established w/h axis swap (see
19617 // `SCAN_8X4`'s own doc comment).
19618 const LIBAOM_DEFAULT_SCAN_4X8: [u16; 32] = [
19619 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21,
19620 14, 7, 29, 22, 15, 30, 23, 31,
19621 ];
19622 // libaom `default_scan_8x4` verbatim (scan.c:44-47) -- this repo's
19623 // `SCAN_4X8`.
19624 const LIBAOM_DEFAULT_SCAN_8X4: [u16; 32] = [
19625 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22,
19626 25, 28, 23, 26, 29, 27, 30, 31,
19627 ];
19628 assert_ne!(
19629 LIBAOM_DEFAULT_SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4,
19630 "the two libaom source sequences must differ, or this pin would \
19631 pass regardless of a swap"
19632 );
19633 assert_eq!(SCAN_8X4, LIBAOM_DEFAULT_SCAN_4X8, "SCAN_8X4 vs libaom default_scan_4x8");
19634 assert_eq!(SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4, "SCAN_4X8 vs libaom default_scan_8x4");
19635 }
19636
19637 /// lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= 32",
19638 /// so a DC_PRED 16x8/8x16 strip reads a `use_filter_intra` flag exactly
19639 /// like a square 16x16 does. [`filter_intra_size_class_rect`] returned
19640 /// `None` at those two sizes, so the symbol was never read and the tile
19641 /// desynced from that block on (root-caused against an instrumented
19642 /// aomdec `EC_TRACE_COEFF` ladder on a real stream: identical `mode=0`/
19643 /// `uv_mode=9` values, our range 34808 vs the oracle's 40668 at the very
19644 /// next transform block).
19645 ///
19646 /// The two rows are ASYMMETRIC (9394 for 16x8, 12551 for 8x16), so this
19647 /// pin fails if the pair is ever transposed -- the shape the repo's
19648 /// scan tables already carry (`SCAN_8X4` == libaom `default_scan_4x8`).
19649 #[test]
19650 fn a_rect_strip_below_16x16_reads_its_own_filter_intra_cdf_row() {
19651 // `default_filter_intra_cdfs` (entropymode.c), indexed by BLOCK_SIZES_ALL:
19652 // [4] = BLOCK_8X16, [5] = BLOCK_16X8, [7] = BLOCK_16X32, [8] = BLOCK_32X16.
19653 const LIBAOM_8X16: u16 = 12551;
19654 const LIBAOM_16X8: u16 = 9394;
19655 let c16x8 = filter_intra_size_class_rect(16, 8).expect("16x8 reads use_filter_intra");
19656 let c8x16 = filter_intra_size_class_rect(8, 16).expect("8x16 reads use_filter_intra");
19657 assert_ne!(c16x8, c8x16, "the two orientations must not share a CDF row");
19658 assert_eq!(cdf::FILTER_INTRA[c16x8][0], LIBAOM_16X8, "16x8 filter_intra row");
19659 assert_eq!(cdf::FILTER_INTRA[c8x16][0], LIBAOM_8X16, "8x16 filter_intra row");
19660 // The sizes one class up keep their own distinct rows (lane-intradisp).
19661 assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(32, 16).unwrap()][0], 12756);
19662 assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(16, 32).unwrap()][0], 14301);
19663 // A size with a side over 32 is genuinely not allowed the flag.
19664 assert_eq!(filter_intra_size_class_rect(64, 32), None);
19665 }
19666
19667 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
19668 /// when both references sit on the same temporal side -- the three
19669 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
19670 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
19671 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
19672 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
19673 /// not just the three enumerated syntax pairs).
19674 #[test]
19675 fn is_uni_comp_ref_matches_forward_backward_sides() {
19676 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
19677 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
19678 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
19679 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
19680 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
19681 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
19682 }
19683
19684 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
19685 /// with the real second reference (lane-av1comp round 12: previously
19686 /// always cleared to `None` by `record_inter`, so the next block's own
19687 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
19688 /// -- could never see a real compound neighbour).
19689 #[test]
19690 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
19691 let mut n = Neighbours::new(4, 4, 16, 16);
19692 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
19693 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
19694 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
19695 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
19696 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
19697 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
19698 }
19699
19700 /// A below-16px leaf must clear the palette neighbour state over its own
19701 /// cell: before lane-palette2 r8 `record_palette_y_rect`'s `w / SUB` loops
19702 /// ran zero times for any sub-16 span, so `decode_leaf_rect` /
19703 /// `decode_leaf8` left a previous block's palette size and colours in the
19704 /// above/left arrays and the NEXT block read `palette_y_mode` off the
19705 /// wrong CDF row with a stale colour cache (class
19706 /// [[cdf-row-held-constant]]).
19707 #[test]
19708 fn a_sub16_leaf_after_a_palette_block_yields_palette_ctx_zero() {
19709 let mut n = Neighbours::new(4, 4, 16, 16);
19710 // A real 16x16 palette block covering SUB cell (1, 1).
19711 n.record_palette_y_rect((1, 1), 16, 16, 2, [7, 9, 0, 0, 0, 0, 0, 0]);
19712 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
19713 assert_eq!(ctx, 2, "the palette block itself must be visible");
19714 assert_eq!(cache, vec![7, 9]);
19715 // An 8x8 non-palette leaf in that same cell.
19716 n.record_palette_y_rect((1, 1), 8, 8, 0, [0u16; 8]);
19717 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
19718 assert_eq!(ctx, 0, "a sub-16 non-palette leaf must clear its own cell");
19719 assert!(cache.is_empty(), "and its stale colour cache with it");
19720 // Same for the chroma half.
19721 n.record_palette_uv_rect((1, 1), 16, 16, 2, [1, 2, 0, 0, 0, 0, 0, 0]);
19722 assert_eq!(n.palette_uv_cache((1, 1)), vec![1, 2]);
19723 n.record_palette_uv_rect((1, 1), 8, 8, 0, [0u16; 8]);
19724 assert!(n.palette_uv_cache((1, 1)).is_empty());
19725 }
19726
19727 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
19728 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
19729 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
19730 /// -- a few corner and interior points, not the whole 6x6 grid.
19731 #[test]
19732 fn compound_mode_ctx_map_matches_libaom_corners() {
19733 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
19734 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
19735 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
19736 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
19737 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
19738 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
19739 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
19740 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
19741 // exactly the ranges `find_mv_stack_compound` produces.
19742 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
19743 }
19744
19745 #[test]
19746 fn a_frame_with_no_mode_info_grid_is_refused() {
19747 assert!(
19748 decode_key_frame_tile(
19749 &[0u8; 4],
19750 0,
19751 32,
19752 32,
19753 0,
19754 128,
19755 false,
19756 &CdefParams::default(),
19757 &LoopFilterParams::default(),
19758 false,
19759 true,
19760 false,
19761 false,
19762 )
19763 .is_err()
19764 );
19765 }
19766
19767 /// Encodes and decodes one picture with `modes`, asserting the decoder's
19768 /// planes are byte-exact against the encoder's own reconstruction.
19769 fn round_trips(w: usize, h: usize, modes: &[u8]) {
19770 use crate::encode::{Encoded, Picture as Pic};
19771 let mut source = vec![0u16; w * h];
19772 for row in 0..h {
19773 for col in 0..w {
19774 source[row * w + col] = ((row * 3 + col * 5) % 251) as u16;
19775 }
19776 }
19777 let picture = Pic {
19778 width: w,
19779 height: h,
19780 y: source,
19781 u: vec![128; w * h / 4],
19782 v: vec![128; w * h / 4],
19783 };
19784 let Encoded {
19785 tile,
19786 reconstruction,
19787 mi_cols,
19788 mi_rows,
19789 base_q_idx,
19790 ..
19791 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
19792 let decoded = decode_key_frame_tile(
19793 &tile,
19794 mi_cols,
19795 mi_rows,
19796 base_q_idx,
19797 w as u32,
19798 h as u32,
19799 false,
19800 &CdefParams::default(),
19801 &LoopFilterParams::default(),
19802 false,
19803 true,
19804 false,
19805 false,
19806 )
19807 .unwrap();
19808 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
19809 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
19810 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
19811 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
19812 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
19813 }
19814
19815 #[test]
19816 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
19817 for (w, h) in [(128usize, 128usize), (192, 128)] {
19818 round_trips(w, h, &[DC_PRED as u8]);
19819 }
19820 }
19821
19822 /// Every one of the thirteen key-frame intra modes, at their base angle,
19823 /// on real (non-flat) content: the mode search picks whichever wins each
19824 /// block, so this exercises the directional edge/reach plumbing this
19825 /// decoder round adds, not just `DC_PRED`.
19826 #[test]
19827 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
19828 for (w, h) in [(128usize, 128usize), (192, 128)] {
19829 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
19830 }
19831 }
19832
19833 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
19834 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
19835 /// this decoder round adds.
19836 #[test]
19837 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
19838 for (w, h) in [(854usize, 480usize), (216, 96)] {
19839 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
19840 }
19841 }
19842
19843 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
19844 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
19845 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
19846 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
19847 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
19848 /// bit, `partition_w8` leaves).
19849 #[test]
19850 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
19851 for (w, h) in [(40usize, 32usize), (640, 360)] {
19852 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
19853 }
19854 }
19855
19856 /// A skipped block codes no residual syntax at all (spec 5.11.34):
19857 /// straight prediction on every plane. The real key-frame writer never
19858 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
19859 /// `0`), so this constructs the exact symbol sequence a writer that did
19860 /// emit it would produce, by hand, and asserts the decoded reconstruction
19861 /// is pure DC prediction (mid-grey, with no neighbours) rather than
19862 /// refusing.
19863 #[test]
19864 fn a_skipped_block_decodes_to_pure_prediction() {
19865 use crate::msac::SymbolEncoder;
19866 let mut cdfs = Cdfs::new(q_ctx_of(40));
19867 let mut enc = SymbolEncoder::new();
19868 // One whole, unsplit 64x64 superblock, coded skip = true.
19869 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
19870 enc.symbol(1, &mut cdfs.skip[0]);
19871 enc.symbol(
19872 DC_PRED,
19873 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
19874 );
19875 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
19876 let data = enc.finish();
19877 let decoded = decode_key_frame_tile(
19878 &data,
19879 16,
19880 16,
19881 40,
19882 64,
19883 64,
19884 false,
19885 &CdefParams::default(),
19886 &LoopFilterParams::default(),
19887 false,
19888 true,
19889 false,
19890 false,
19891 )
19892 .unwrap();
19893 assert!(
19894 decoded.y.iter().all(|&s| s == 128),
19895 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
19896 );
19897 }
19898
19899 /// An inter tile's SB-level `part64` used to be read and thrown away
19900 /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real
19901 /// non-SPLIT value there silently desynced the whole tile instead of
19902 /// refusing. Hand-writes a single whole superblock's `part64 = HORZ`
19903 /// symbol (never produced by this crate's own encoder, which only ever
19904 /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can)
19905 /// and asserts this decoder refuses by name rather than decoding garbage.
19906 #[test]
19907 fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
19908 use crate::msac::SymbolEncoder;
19909 let mut cdfs = Cdfs::new(q_ctx_of(40));
19910 let mut enc = SymbolEncoder::new();
19911 enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]);
19912 let data = enc.finish();
19913 let reference = crate::encode::Picture::grey(64, 64);
19914 let err = decode_inter_frame_tile(
19915 &data,
19916 16,
19917 16,
19918 40,
19919 64,
19920 64,
19921 &reference,
19922 [None; 8],
19923 &CdefParams::default(),
19924 &LoopFilterParams::default(),
19925 false,
19926 false,
19927 Some(mc::InterpFilterKind::Regular),
19928 false,
19929 false,
19930 )
19931 .unwrap_err();
19932 let msg = err.to_string();
19933 assert!(
19934 msg.contains("SPLIT"),
19935 "expected the named inter-SB-partition refusal, got: {msg}"
19936 );
19937 }
19938
19939 // ffmpeg cross-oracle: an independent decoder (not this crate's own
19940 // encoder-side reconstruction) agrees with what this module decodes,
19941 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
19942 // name (that module is another lane's territory this round, and the
19943 // helpers are `#[cfg(test)]`-private to it).
19944 use std::io::Write;
19945 use std::process::{Command, Stdio};
19946
19947 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
19948 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
19949 /// aomenc gate decodes its stream through ffmpeg and is meaningless
19950 /// without it -- turns it into a hard failure. Without this the require
19951 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
19952 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
19953 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
19954 fn have_ffmpeg() -> bool {
19955 let present = Command::new("ffmpeg")
19956 .arg("-version")
19957 .stdout(Stdio::null())
19958 .stderr(Stdio::null())
19959 .status()
19960 .is_ok_and(|s| s.success());
19961 assert!(
19962 present
19963 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
19964 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
19965 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
19966 );
19967 present
19968 }
19969
19970 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
19971 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
19972 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
19973 let mut child = Command::new("ffmpeg")
19974 .args([
19975 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
19976 ])
19977 .stdin(Stdio::piped())
19978 .stdout(Stdio::piped())
19979 .stderr(Stdio::piped())
19980 .spawn()
19981 .expect("ffmpeg failed to start");
19982 child
19983 .stdin
19984 .take()
19985 .expect("ffmpeg stdin")
19986 .write_all(stream)
19987 .expect("writing the stream to ffmpeg");
19988 let out = child.wait_with_output().expect("ffmpeg failed to run");
19989 assert!(
19990 out.status.success(),
19991 "ffmpeg refused the stream: {}",
19992 String::from_utf8_lossy(&out.stderr)
19993 );
19994 let (luma, chroma) = (width * height, width * height / 4);
19995 assert_eq!(
19996 out.stdout.len(),
19997 luma + 2 * chroma,
19998 "expected one 4:2:0 frame"
19999 );
20000 Picture {
20001 width,
20002 height,
20003 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
20004 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
20005 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
20006 }
20007 }
20008
20009 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
20010 fn ffmpeg_decode_sequence(
20011 stream: &[u8],
20012 width: usize,
20013 height: usize,
20014 frames: usize,
20015 ) -> Vec<Picture> {
20016 let mut child = Command::new("ffmpeg")
20017 .args([
20018 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
20019 ])
20020 .stdin(Stdio::piped())
20021 .stdout(Stdio::piped())
20022 .stderr(Stdio::piped())
20023 .spawn()
20024 .expect("ffmpeg failed to start");
20025 child
20026 .stdin
20027 .take()
20028 .expect("ffmpeg stdin")
20029 .write_all(stream)
20030 .expect("writing the stream to ffmpeg");
20031 let out = child.wait_with_output().expect("ffmpeg failed to run");
20032 assert!(
20033 out.status.success(),
20034 "ffmpeg refused the stream: {}",
20035 String::from_utf8_lossy(&out.stderr)
20036 );
20037 let (luma, chroma) = (width * height, width * height / 4);
20038 let frame_bytes = luma + 2 * chroma;
20039 assert_eq!(
20040 out.stdout.len(),
20041 frame_bytes * frames,
20042 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
20043 String::from_utf8_lossy(&out.stderr)
20044 );
20045 (0..frames)
20046 .map(|i| {
20047 let base = i * frame_bytes;
20048 Picture {
20049 width,
20050 height,
20051 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
20052 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
20053 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
20054 }
20055 })
20056 .collect()
20057 }
20058
20059 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
20060 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
20061 /// test binary runs callers on parallel threads, and a shared name lets
20062 /// one test's cleanup race another's still-reading ffprobe --
20063 /// pid-keyed-temp-path class).
20064 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
20065 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20066 let path = std::env::temp_dir().join(format!(
20067 "ec-av1-decode-probe-{}-{}.obu",
20068 std::process::id(),
20069 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20070 ));
20071 let _ = std::fs::remove_file(&path);
20072 std::fs::write(&path, stream).expect("writing the probe stream");
20073 let out = Command::new("ffprobe")
20074 .args([
20075 "-v",
20076 "error",
20077 "-f",
20078 "obu",
20079 "-select_streams",
20080 "v:0",
20081 "-show_entries",
20082 "stream=width,height",
20083 "-of",
20084 "csv=p=0",
20085 ])
20086 .arg(&path)
20087 .output()
20088 .expect("ffprobe failed to run");
20089 let _ = std::fs::remove_file(&path);
20090 assert!(
20091 out.status.success(),
20092 "ffprobe refused the stream: {}",
20093 String::from_utf8_lossy(&out.stderr)
20094 );
20095 let text = String::from_utf8_lossy(&out.stdout);
20096 let mut fields = text.trim().split(',');
20097 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
20098 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
20099 (width, height)
20100 }
20101
20102 /// This module's own decoder against an independent one (ffmpeg), not
20103 /// just against this crate's encoder-side reconstruction: both decoders
20104 /// read the identical tile bytes, so agreement here rules out a bug this
20105 /// crate's own writer and reader could otherwise share.
20106 #[test]
20107 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
20108 if !have_ffmpeg() {
20109 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
20110 return;
20111 }
20112 use crate::encode::encode_key_frame;
20113 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
20114 let picture = round_trip_test_card(width, height);
20115 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
20116 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
20117 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
20118 let ours = decode_key_frame_tile(
20119 &encoded.tile,
20120 encoded.mi_cols,
20121 encoded.mi_rows,
20122 encoded.base_q_idx,
20123 coded_w,
20124 coded_h,
20125 false,
20126 &CdefParams::default(),
20127 &LoopFilterParams::default(),
20128 false,
20129 true,
20130 false,
20131 false,
20132 )
20133 .unwrap();
20134 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
20135 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
20136 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
20137 }
20138 }
20139
20140 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
20141 let mut picture = crate::encode::Picture::grey(width, height);
20142 for row in 0..height {
20143 for col in 0..width {
20144 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
20145 }
20146 }
20147 for row in 0..height / 2 {
20148 for col in 0..width / 2 {
20149 let i = row * width / 2 + col;
20150 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
20151 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
20152 }
20153 }
20154 picture
20155 }
20156
20157 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
20158 let mut picture = crate::encode::Picture::grey(width, height);
20159 for y in 0..height {
20160 for x in 0..width {
20161 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
20162 let gradient = sx * 200.0 / width as f64;
20163 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
20164 }
20165 }
20166 for y in 0..height / 2 {
20167 for x in 0..width / 2 {
20168 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
20169 let i = y * width / 2 + x;
20170 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
20171 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
20172 }
20173 }
20174 picture
20175 }
20176
20177 /// A GOP (one key frame plus several inter frames, each panned so its
20178 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
20179 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
20180 /// reconstruction, frame by frame, chaining each decoded frame straight
20181 /// into the next as its reference -- exactly the single-slot DPB
20182 /// [`crate::encode::encode_sequence`] itself threads.
20183 fn gop_round_trips(width: usize, height: usize) {
20184 use crate::encode::encode_sequence;
20185 let pictures: Vec<_> = (0..4)
20186 .map(|i| panned_test_card(width, height, i * 3))
20187 .collect();
20188 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
20189 assert_eq!(encoded.frames.len(), 4);
20190
20191 let key = &encoded.frames[0];
20192 let mut reference = decode_key_frame_tile(
20193 &key.tile,
20194 key.mi_cols,
20195 key.mi_rows,
20196 key.base_q_idx,
20197 width as u32,
20198 height as u32,
20199 false,
20200 &CdefParams::default(),
20201 &LoopFilterParams::default(),
20202 false,
20203 true,
20204 false,
20205 false,
20206 )
20207 .unwrap();
20208 assert_eq!(
20209 reference.y, key.reconstruction.y,
20210 "{width}x{height} frame 0 luma"
20211 );
20212 assert_eq!(
20213 reference.u, key.reconstruction.u,
20214 "{width}x{height} frame 0 U"
20215 );
20216 assert_eq!(
20217 reference.v, key.reconstruction.v,
20218 "{width}x{height} frame 0 V"
20219 );
20220
20221 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
20222 let decoded = decode_inter_frame_tile(
20223 &frame.tile,
20224 frame.mi_cols,
20225 frame.mi_rows,
20226 frame.base_q_idx,
20227 width as u32,
20228 height as u32,
20229 &reference,
20230 [None; 8],
20231 &CdefParams::default(),
20232 &LoopFilterParams::default(),
20233 false,
20234 false,
20235 Some(mc::InterpFilterKind::Regular),
20236 false,
20237 false,
20238 )
20239 .unwrap();
20240 assert_eq!(
20241 decoded.y, frame.reconstruction.y,
20242 "{width}x{height} frame {i} luma"
20243 );
20244 assert_eq!(
20245 decoded.u, frame.reconstruction.u,
20246 "{width}x{height} frame {i} U"
20247 );
20248 assert_eq!(
20249 decoded.v, frame.reconstruction.v,
20250 "{width}x{height} frame {i} V"
20251 );
20252 reference = decoded;
20253 }
20254 }
20255
20256 #[test]
20257 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
20258 gop_round_trips(128, 64);
20259 }
20260
20261 /// Same claim, at a size that is not a whole number of 32x32 blocks
20262 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
20263 /// split path is exercised too.
20264 #[test]
20265 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
20266 gop_round_trips(216, 96);
20267 }
20268
20269 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
20270 /// this module does, frame for frame.
20271 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
20272 /// MV stack's *second* candidate (`near_mv`), not its first
20273 /// (`nearest_mv`) -- a hand-built symbol stream drives
20274 /// [`decode_inter_block`] directly, since this crate's own encoder never
20275 /// writes NEARMV (round 3: it never chooses the mode).
20276 #[test]
20277 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
20278 use crate::msac::SymbolEncoder;
20279 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
20280
20281 const LAST_FRAME: i8 = 1;
20282 let (mi_cols, mi_rows) = (12u32, 12u32);
20283 let side = 16usize; // one 16x16 leaf block
20284 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
20285 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
20286 let bw4 = side / 4;
20287
20288 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
20289 let (above_mv, left_mv) = ((4, 4), (8, 8));
20290 let neighbour = |mv| MiInfo {
20291 is_inter: true,
20292 ref_frame: LAST_FRAME,
20293 ref_frame1: None,
20294 mv1: None,
20295 mv,
20296 is_new_mv: false,
20297 size: 1,
20298 size_h: 1,
20299 is_global_mv0: false,
20300 is_global_mv1: false,
20301 };
20302 for col in mi_col..mi_col + bw4 {
20303 grid.set(mi_row - 1, col, neighbour(above_mv));
20304 }
20305 for row in mi_row..mi_row + bw4 {
20306 grid.set(row, mi_col - 1, neighbour(left_mv));
20307 }
20308
20309 let stack = find_mv_stack(
20310 &grid,
20311 mi_row,
20312 mi_col,
20313 bw4,
20314 bw4,
20315 LAST_FRAME,
20316 mi_cols as usize,
20317 mi_rows as usize,
20318 );
20319 // Sanity on the test's own setup, not the code under test: two equal-
20320 // weight candidates keep scan order (above, then left -- module doc).
20321 assert_eq!(stack.entries.len(), 2);
20322 assert_eq!(stack.nearest_mv, above_mv);
20323 assert_eq!(stack.near_mv, left_mv);
20324
20325 let (skip_ctx, ii_ctx, sr_ctx) = (
20326 0usize,
20327 intra_inter_ctx(true, true, false, false),
20328 single_ref_ctx(false),
20329 );
20330
20331 let mut cdfs = Cdfs::new(q_ctx_of(100));
20332 let mut enc = SymbolEncoder::new();
20333 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
20334 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
20335 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
20336 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
20337 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
20338 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
20339 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
20340 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
20341 let data = enc.finish();
20342
20343 let (width, height) = (64usize, 64usize);
20344 let ref_pattern: Vec<u16> = (0..width * height).map(|i| (i % 251) as u16).collect();
20345 let ref_plane = |scale: usize| PlaneBuf {
20346 data: ref_pattern
20347 .iter()
20348 .step_by(scale.max(1))
20349 .take((width / scale) * (height / scale))
20350 .copied()
20351 .collect(),
20352 width: width / scale,
20353 height: height / scale,
20354 true_width: width / scale,
20355 true_height: height / scale,
20356 tile_x0: 0,
20357 tile_y0: 0,
20358 tile_x1: width / scale,
20359 tile_y1: height / scale,
20360 };
20361 let ref_y = PlaneBuf {
20362 data: ref_pattern.clone(),
20363 width,
20364 height,
20365 true_width: width,
20366 true_height: height,
20367 tile_x0: 0,
20368 tile_y0: 0,
20369 tile_x1: width,
20370 tile_y1: height,
20371 };
20372 let ref_u = ref_plane(2);
20373 let ref_v = ref_plane(2);
20374
20375 let mut y = PlaneBuf {
20376 data: vec![0u16; width * height],
20377 width,
20378 height,
20379 true_width: width,
20380 true_height: height,
20381 tile_x0: 0,
20382 tile_y0: 0,
20383 tile_x1: width,
20384 tile_y1: height,
20385 };
20386 let mut u = PlaneBuf {
20387 data: vec![0u16; (width / 2) * (height / 2)],
20388 width: width / 2,
20389 height: height / 2,
20390 true_width: width / 2,
20391 true_height: height / 2,
20392 tile_x0: 0,
20393 tile_y0: 0,
20394 tile_x1: width / 2,
20395 tile_y1: height / 2,
20396 };
20397 let mut v = PlaneBuf {
20398 data: vec![0u16; (width / 2) * (height / 2)],
20399 width: width / 2,
20400 height: height / 2,
20401 true_width: width / 2,
20402 true_height: height / 2,
20403 tile_x0: 0,
20404 tile_y0: 0,
20405 tile_x1: width / 2,
20406 tile_y1: height / 2,
20407 };
20408
20409 let mut cdfs = Cdfs::new(q_ctx_of(100));
20410 let mut dec = SymbolDecoder::new(&data);
20411 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
20412 decode_inter_block(
20413 &mut dec,
20414 &mut cdfs,
20415 &mut neighbours,
20416 &mut grid,
20417 (r, c),
20418 side,
20419 mi_cols,
20420 mi_rows,
20421 &mut y,
20422 &mut u,
20423 &mut v,
20424 &ref_y,
20425 &ref_u,
20426 &ref_v,
20427 &[None; 8],
20428 &NO_SIGN_BIAS,
20429 &[ec_av1_syntax::WarpParams::default(); 7],
20430 100,
20431 TxbSet::Luma16,
20432 TxbSet::Luma16Inter,
20433 TxbSet::Chroma8,
20434 TX16,
20435 TX8,
20436 &[],
20437 &[],
20438 0,
20439 false,
20440 false,
20441 Some(mc::InterpFilterKind::Regular),
20442 false,
20443 None,
20444 false,
20445 false,
20446 false,
20447 false,
20448 0,
20449 0,
20450 [0; 7],
20451 false,
20452 [0; 2],
20453 false,
20454 false,
20455 false,
20456 side,
20457 side,
20458 false,
20459 width,
20460 )
20461 .unwrap();
20462
20463 let (px, py) = (c * SUB, r * SUB);
20464 let mut want_near = vec![0u16; side * side];
20465 crate::mc::predict(
20466 &ref_y.data,
20467 ref_y.width,
20468 ref_y.true_width,
20469 ref_y.true_height,
20470 mv_to_q4(px, left_mv.1, true),
20471 mv_to_q4(py, left_mv.0, true),
20472 side,
20473 side,
20474 &mut want_near,
20475 );
20476 let mut want_nearest = vec![0u16; side * side];
20477 crate::mc::predict(
20478 &ref_y.data,
20479 ref_y.width,
20480 ref_y.true_width,
20481 ref_y.true_height,
20482 mv_to_q4(px, above_mv.1, true),
20483 mv_to_q4(py, above_mv.0, true),
20484 side,
20485 side,
20486 &mut want_nearest,
20487 );
20488 assert_ne!(
20489 want_near, want_nearest,
20490 "test setup: the two candidate MVs must predict differently"
20491 );
20492
20493 let mut got = vec![0u16; side * side];
20494 for row in 0..side {
20495 got[row * side..(row + 1) * side].copy_from_slice(
20496 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
20497 );
20498 }
20499 assert_eq!(
20500 got, want_near,
20501 "NEARMV predicted from the wrong stack entry"
20502 );
20503 }
20504
20505 #[test]
20506 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
20507 if !have_ffmpeg() {
20508 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
20509 return;
20510 }
20511 use crate::encode::encode_sequence;
20512 let (width, height) = (128usize, 64usize);
20513 let pictures: Vec<_> = (0..3)
20514 .map(|i| panned_test_card(width, height, i * 3))
20515 .collect();
20516 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
20517 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
20518 let ffmpeg_frames =
20519 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
20520
20521 let key = &encoded.frames[0];
20522 let mut reference = decode_key_frame_tile(
20523 &key.tile,
20524 key.mi_cols,
20525 key.mi_rows,
20526 key.base_q_idx,
20527 coded_w,
20528 coded_h,
20529 false,
20530 &CdefParams::default(),
20531 &LoopFilterParams::default(),
20532 false,
20533 true,
20534 false,
20535 false,
20536 )
20537 .unwrap();
20538 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
20539
20540 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
20541 let decoded = decode_inter_frame_tile(
20542 &frame.tile,
20543 frame.mi_cols,
20544 frame.mi_rows,
20545 frame.base_q_idx,
20546 coded_w,
20547 coded_h,
20548 &reference,
20549 [None; 8],
20550 &CdefParams::default(),
20551 &LoopFilterParams::default(),
20552 false,
20553 false,
20554 Some(mc::InterpFilterKind::Regular),
20555 false,
20556 false,
20557 )
20558 .unwrap();
20559 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
20560 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
20561 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
20562 reference = decoded;
20563 }
20564 }
20565}
20566
20567#[cfg(test)]
20568mod tx4x8_table_tests {
20569 use super::*;
20570
20571 /// Asymmetric gate on the two new scan tables (class
20572 /// `reference-layout-not-spec`): a transposed pair of tables passes any
20573 /// "is a permutation" check, so this pins the pair AGAINST each other --
20574 /// `SCAN_8X4[k]` must be `SCAN_4X8[k]` reflected across the diagonal, and
20575 /// both must be bijections of `0..32` in our own row-major indexing.
20576 #[test]
20577 fn the_rect_4x8_scans_are_each_other_transposed() {
20578 let mut seen_a = [false; 32];
20579 let mut seen_b = [false; 32];
20580 for k in 0..32usize {
20581 let a = SCAN_4X8[k] as usize;
20582 let b = SCAN_8X4[k] as usize;
20583 assert!(!seen_a[a] && !seen_b[b], "scan position {k} repeats");
20584 seen_a[a] = true;
20585 seen_b[b] = true;
20586 let (row, col) = (a / 4, a % 4);
20587 assert_eq!(b, col * 8 + row, "SCAN_8X4[{k}] is not SCAN_4X8[{k}] transposed");
20588 }
20589 assert!(seen_a.iter().all(|&s| s) && seen_b.iter().all(|&s| s));
20590 }
20591
20592 /// `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/`mcol_scan_8x4`
20593 /// (libaom `scan.c`), converted out of their column-major encoding by
20594 /// `(p % h) * w + p / h` -- the head of each, pinned so the rect
20595 /// `V_DCT`/`H_DCT` walk cannot silently transpose.
20596 #[test]
20597 fn the_rect_class1_scans_match_libaom() {
20598 assert_eq!(
20599 class_scan_table_wh(4, 8, TxClass::Vert),
20600 (0..32u16).collect::<Vec<_>>()
20601 );
20602 assert_eq!(
20603 &class_scan_table_wh(4, 8, TxClass::Horiz)[..8],
20604 &[0u16, 4, 8, 12, 16, 20, 24, 28]
20605 );
20606 assert_eq!(
20607 class_scan_table_wh(8, 4, TxClass::Vert),
20608 (0..32u16).collect::<Vec<_>>()
20609 );
20610 assert_eq!(
20611 &class_scan_table_wh(8, 4, TxClass::Horiz)[..8],
20612 &[0u16, 8, 16, 24, 1, 9, 17, 25]
20613 );
20614 }
20615
20616 /// The 32-position `eob_pt` alphabet: six symbols (one more than the
20617 /// 16-position table, one fewer than the 64-position one), strictly
20618 /// increasing, terminated at 32768 with the adaptation counter after it.
20619 #[test]
20620 fn the_32_position_eob_tables_are_well_formed() {
20621 for table in [
20622 &cdf::EOB_PT_32_LUMA_Q0,
20623 &cdf::EOB_PT_32_LUMA_Q1,
20624 &cdf::EOB_PT_32_LUMA,
20625 &cdf::EOB_PT_32_LUMA_Q3,
20626 &cdf::EOB_PT_32_LUMA_CLASS1_Q0,
20627 &cdf::EOB_PT_32_LUMA_CLASS1_Q1,
20628 &cdf::EOB_PT_32_LUMA_CLASS1,
20629 &cdf::EOB_PT_32_LUMA_CLASS1_Q3,
20630 ] {
20631 assert_eq!(table.len(), 7);
20632 assert_eq!(table[5], 32768);
20633 assert_eq!(table[6], 0);
20634 for w in table[..6].windows(2) {
20635 assert!(w[0] < w[1], "{table:?} is not increasing");
20636 }
20637 }
20638 }
20639
20640 /// `Reach::of_rect` must read libaom's own `has_tr_4x8`/`has_tr_8x4`
20641 /// rows, not the 32x16 pair the two existing rect strips use: the two
20642 /// shapes disagree at a position inside the superblock, which is what
20643 /// makes this an asymmetric check rather than a tautology.
20644 #[test]
20645 fn the_sub8_rect_reach_tables_are_shape_specific() {
20646 let a = Reach::of_rect(4, 8, 4, 8, 64, 64);
20647 let b = Reach::of_rect(8, 4, 8, 4, 64, 64);
20648 assert!(
20649 a.above_right != b.above_right || a.below_left != b.below_left,
20650 "4x8 and 8x4 reach identically at mirrored positions -- one table is unused"
20651 );
20652 }
20653}