forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

decode.rs23071 lines, 1.4 MiBHistoryRawDownload
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 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
68 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
69 /// prints gigabytes otherwise). Unset = every frame, as before.
70 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
71 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
72}
73
74/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
75/// that frame's DECODE-order index.
76pub fn set_coeff_trace_frame(idx: usize) {
77 COEFF_TRACE_FRAME.with(|c| {
78 if c.get().is_none() {
79 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
80 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
81 // unset: keep tracing every frame, as before this rung existed
82 Err(_) => usize::MAX - 1,
83 };
84 c.set(Some(want));
85 }
86 });
87 COEFF_TRACE_CUR.with(|c| c.set(idx));
88 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
89 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
90 }
91}
92
93pub(crate) fn coeff_trace_on() -> bool {
94 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
95 return false;
96 }
97 match COEFF_TRACE_FRAME.with(|c| c.get()) {
98 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
99 // env var unset: trace every frame.
100 None => true,
101 Some(w) if w >= usize::MAX - 1 => true,
102 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
103 }
104}
105
106thread_local! {
107 static SB128: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
108}
109
110/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
111pub(crate) fn set_sb128(v: bool) {
112 SB128.with(|c| c.set(v));
113 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 });
114}
115
116fn sb128() -> bool {
117 SB128.with(|c| c.get())
118}
119
120/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
121pub(crate) fn sb_mi_cur() -> u32 {
122 if sb128() { SB_MI * 2 } else { SB_MI }
123}
124
125/// How many real 128-level partition symbols this decoder has read, and how
126/// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
127/// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
128thread_local! {
129 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
130 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
131 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
132}
133
134/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
135/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
136/// 5.11.4), which this decoder used to read and throw away.
137pub(crate) fn part128_gathered_symbols() -> usize {
138 PART128_GATHERED_SYMBOLS.with(|c| c.get())
139}
140
141/// Current value of [`PART128_SYMBOLS`].
142pub(crate) fn part128_symbols() -> usize {
143 PART128_SYMBOLS.with(|c| c.get())
144}
145
146/// Current value of [`PART128_SPLIT_HITS`].
147pub(crate) fn part128_split_hits() -> usize {
148 PART128_SPLIT_HITS.with(|c| c.get())
149}
150
151/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
152/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
153/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
154/// the 64/32 levels sum 6.
155fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
156 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
157 [32768 - split, 32768, 0]
158}
159
160/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
161const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
162const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
163
164// How many `use_filter_intra` symbols this decoder has read as `1`, across
165// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
166// tests read (before/after, not the absolute value) to prove a stream
167// actually exercised the filter-intra predictor rather than silently
168// skipping it.
169thread_local! {
170 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
171 const { std::cell::Cell::new(0) };
172}
173
174/// Current value of [`FILTER_INTRA_HITS`].
175pub(crate) fn filter_intra_hits() -> usize {
176 FILTER_INTRA_HITS.with(|c| c.get())
177}
178
179// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
180// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
181// `read_filter_intra_mode_info` call), which no gate exercised before this
182// round -- every inter gate recipe passed `--enable-filter-intra=0`.
183thread_local! {
184 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
185 const { std::cell::Cell::new(0) };
186}
187
188/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
189pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
190 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
191}
192
193// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
194// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
195// arms refused a nonzero luma delta before this round, and no inter gate
196// enabled `--enable-angle-delta` (aomenc's own default is 1).
197thread_local! {
198 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
199 const { std::cell::Cell::new(0) };
200 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
201 const { std::cell::Cell::new(0) };
202}
203
204/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
205pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
206 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
207}
208
209/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
210pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
211 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
212}
213
214// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
215// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
216// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
217// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
218thread_local! {
219 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
220 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
221 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
222}
223
224thread_local! {
225 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
226}
227
228/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
229/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
230pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
231 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
232}
233
234/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
235/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
236pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
237 (
238 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
239 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
240 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
241 )
242}
243
244// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
245// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
246// frame-level flag through the recursive block decode -- `0` (the default)
247// makes every call a true no-op, matching every existing gate stream's
248// `cdef_bits == 0` behaviour exactly.
249thread_local! {
250 static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
251}
252// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
253// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
254// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
255// blocks every non-8-bit stream from reaching a decode call, so this is `8`
256// on every path that runs today -- threading it now (rather than the literal
257// `8`) is stage 1 of widening past that refusal without re-deriving every
258// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
259// depth (this decoder's own internal choice, matches dav1d/libaom).
260thread_local! {
261 static BIT_DEPTH: std::cell::Cell<u8> = const { std::cell::Cell::new(8) };
262}
263/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
264/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
265pub(crate) fn sample_max() -> i32 {
266 (1i32 << BIT_DEPTH.with(std::cell::Cell::get)) - 1
267}
268/// The current stream's bit depth, for callers (e.g. dequant) that need the
269/// raw value rather than the derived clamp bound.
270pub(crate) fn bit_depth() -> u8 {
271 BIT_DEPTH.with(std::cell::Cell::get)
272}
273/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
274/// [`crate::stream`]'s decode loop.
275pub(crate) fn set_bit_depth(bit_depth: u8) {
276 BIT_DEPTH.with(|c| c.set(bit_depth));
277}
278// Whether this superblock's single CDEF unit (this decoder has no 128x128
279// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
280// read -- reset to `false` at the top of each superblock in the two tile
281// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
282thread_local! {
283 static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
284}
285// Number of superblock columns in the current tile's grid, so
286// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
287// [`CDEF_IDX_GRID`].
288thread_local! {
289 static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
290}
291// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
292// which of the header's `1 << cdef.bits` strength pairs applies to that
293// superblock's samples.
294thread_local! {
295 static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
296}
297// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
298// has read, across every call on the current thread -- the gate's proof that a
299// `cdef_bits > 0` stream actually reached the new reader rather than every
300// superblock coincidentally being all-skip.
301thread_local! {
302 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
303}
304
305// How many times a warp was suppressed for one PLANE because that plane's own
306// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
307// reconinter.c) -- the gate's proof that a stream really carries the shape,
308// since the square `side`/`chroma_side` can be 8 or more while the plane's
309// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
310thread_local! {
311 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
312}
313
314/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
315pub(crate) fn warp_plane_suppress_hits() -> usize {
316 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
317}
318
319/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
320/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
321/// block dimensions decide it -- never the square `side`/`chroma_side`, which
322/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
323/// bigger than the real block in one axis.
324fn warp_plane_allowed(w: usize, h: usize) -> bool {
325 if w >= 8 && h >= 8 {
326 return true;
327 }
328 WARP_PLANE_SUPPRESS_HITS.with(|c| c.set(c.get() + 1));
329 false
330}
331
332/// Current value of [`CDEF_IDX_HITS`].
333pub(crate) fn cdef_idx_hits() -> usize {
334 CDEF_IDX_HITS.with(|c| c.get())
335}
336
337// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
338// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
339// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
340// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
341// instead of from the coarse 16x16 cell.
342thread_local! {
343 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
344 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
345 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
346}
347
348/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
349pub(crate) fn intra_in_inter_txctx_hits() -> usize {
350 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
351}
352
353/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
354pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
355 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
356}
357
358/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
359pub(crate) fn edge_filter_mi_fix_hits() -> usize {
360 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
361}
362
363// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
364// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
365// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
366// true no-op, matching every existing gate stream's `delta_q_present == 0`
367// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
368thread_local! {
369 static DELTA_Q_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
370 static DELTA_Q_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
371}
372// The running quantizer index (spec `CurrentQIndex`, libaom
373// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
374// top of every tile (spec `decode_tile`), carried across superblocks within
375// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
376// dequantization call sites instead of the frame-constant `base_q_idx`.
377thread_local! {
378 static CURRENT_Q_IDX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
379}
380// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
381// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
382// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
383// back at every dequantization call site keyed on which plane it is doing.
384thread_local! {
385 static QUANT_DELTAS: std::cell::Cell<crate::quant::QuantDeltas> = const {
386 std::cell::Cell::new(crate::quant::QuantDeltas {
387 y_dc: 0,
388 u_dc: 0,
389 u_ac: 0,
390 v_dc: 0,
391 v_ac: 0,
392 })
393 };
394}
395// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
396// read, across every call on the current thread -- the gate's proof that a
397// `delta_q_present` stream actually reached the new reader.
398thread_local! {
399 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
400}
401
402/// Current value of [`DELTA_Q_HITS`].
403pub(crate) fn delta_q_hits() -> usize {
404 DELTA_Q_HITS.with(|c| c.get())
405}
406
407/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
408/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
409/// one), so it is always `0` here.
410fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
411 let d = QUANT_DELTAS.with(|c| c.get());
412 match plane_idx {
413 0 => (d.y_dc, 0),
414 1 => (d.u_dc, d.u_ac),
415 _ => (d.v_dc, d.v_ac),
416 }
417}
418
419/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
420/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
421/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
422/// A no-op when `delta_q_present` is unset, or when this block is not at the
423/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
424/// libaom, collapsed here to a position check since a partition tree's
425/// top-left leaf is the only block that can ever land there), or when that
426/// leaf both *is* the whole superblock and is `skip` (the one case libaom
427/// itself skips the read, state carrying over unchanged).
428fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
429 if !DELTA_Q_PRESENT.with(|c| c.get()) {
430 return;
431 }
432 let sb_mi = sb_mi_cur() as usize;
433 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
434 return;
435 }
436 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
437 // computed against the sequence's own superblock size (lane-sb128b r1:
438 // it used to be hardcoded against 64 and disabled under `sb128`, which a
439 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
440 // wrong).
441 if is_whole_sb && skip {
442 return;
443 }
444 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
445 const DELTA_Q_SMALL: i32 = 3;
446 if abs >= DELTA_Q_SMALL {
447 let rem_bits = dec.literal(3) + 1;
448 let thr = (1i32 << rem_bits) + 1;
449 abs = dec.literal(rem_bits) as i32 + thr;
450 }
451 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
452 let reduced = if sign_negative { -abs } else { abs };
453 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
454 let res = DELTA_Q_RES.with(|c| c.get());
455 CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
456}
457
458// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
459// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
460thread_local! {
461 static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
462 static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
463 static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
464}
465// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
466// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
467// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
468// updates index 0 and every reader treats that as the value for all 4
469// indices (spec `read_delta_lf_params`'s own single-cdf branch).
470thread_local! {
471 static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
472}
473// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
474// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
475thread_local! {
476 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
477}
478
479/// Current value of [`DELTA_LF_HITS`].
480pub(crate) fn delta_lf_hits() -> usize {
481 DELTA_LF_HITS.with(|c| c.get())
482}
483
484/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
485/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
486/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
487/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
488/// read once into index 0 otherwise.
489fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
490 if !DELTA_LF_PRESENT.with(|c| c.get()) {
491 return;
492 }
493 let sb_mi = sb_mi_cur() as usize;
494 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
495 return;
496 }
497 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
498 // computed against the sequence's own superblock size (lane-sb128b r1:
499 // it used to be hardcoded against 64 and disabled under `sb128`, which a
500 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
501 // wrong).
502 if is_whole_sb && skip {
503 return;
504 }
505 let multi = DELTA_LF_MULTI.with(|c| c.get());
506 let res = DELTA_LF_RES.with(|c| c.get());
507 let count = if multi { 4 } else { 1 };
508 let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
509 for i in 0..count {
510 let mut abs = if multi {
511 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
512 } else {
513 dec.symbol(&mut cdfs.delta_lf) as i32
514 };
515 const DELTA_LF_SMALL: i32 = 3;
516 if abs >= DELTA_LF_SMALL {
517 let rem_bits = dec.literal(3) + 1;
518 let thr = (1i32 << rem_bits) + 1;
519 abs = dec.literal(rem_bits) as i32 + thr;
520 }
521 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
522 let reduced = if sign_negative { -abs } else { abs };
523 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
524 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
525 }
526 CURRENT_DELTA_LF.with(|c| c.set(cur));
527}
528
529/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
530/// after `skip` is known at every block-decode call site. A no-op at
531/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
532/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
533/// `allow_intrabc`, so neither needs a separate check here. Reads once per
534/// superblock, at the first non-skip block.
535fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
536 let bits = CDEF_BITS.with(|c| c.get());
537 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
538 return;
539 }
540 let idx = dec.literal(u32::from(bits)) as u8;
541 CDEF_TRANSMITTED.with(|c| c.set(true));
542 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
543 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
544 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
545 if sb_cols > 0 {
546 CDEF_IDX_GRID.with(|g| {
547 let mut g = g.borrow_mut();
548 let i = sb_r * sb_cols + sb_c;
549 if i < g.len() {
550 g[i] = idx;
551 }
552 });
553 }
554}
555
556// ---------------------------------------------------------------------------
557// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
558// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
559// the two consumers a real stream exercises: the per-segment quantizer index
560// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
561// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
562// `read_intra_segment_id`/`read_inter_segment_id` and
563// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
564// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
565// is what the oracle every gate here compares against actually does.
566thread_local! {
567 static SEG: std::cell::RefCell<SegmentationParams> =
568 std::cell::RefCell::new(SegmentationParams::default());
569 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
570 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
571 static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
572 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
573 /// this frame has no primary reference (spec `load_previous_segment_ids`).
574 static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
575 /// `(mi_rows, mi_cols)` for both maps above.
576 static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
577 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
578 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
579 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
580 static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
581 static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
582 /// The block currently being decoded -- read back by [`block_q_idx`].
583 static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
584 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
585 static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
586 /// How many real `segment_id` symbols were read, and the set of segment
587 /// ids any block ended up with -- the gate's proof the feature fired.
588 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
589 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
590 /// How many `seg_id_predicted` symbols were read (temporal update).
591 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
592}
593
594/// Installs this frame's segmentation parameters and allocates its map, with
595/// `prev` the primary reference frame's saved map (spec
596/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
597/// slot). Called once per frame, whether or not segmentation is enabled.
598pub(crate) fn set_segmentation(
599 seg: SegmentationParams,
600 mi_rows: usize,
601 mi_cols: usize,
602 prev: Option<&[u8]>,
603) {
604 SEG.with(|s| *s.borrow_mut() = seg);
605 SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));
606 SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
607 PREV_SEG_IDS.with(|m| {
608 let mut m = m.borrow_mut();
609 m.clear();
610 if let Some(p) = prev {
611 if p.len() == mi_rows * mi_cols {
612 m.extend_from_slice(p);
613 }
614 }
615 });
616 ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
617 LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
618 CUR_SEGMENT_ID.with(|c| c.set(0));
619}
620
621/// This frame's decoded segment map, to be stored into whichever reference
622/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
623pub(crate) fn take_segment_ids() -> Vec<u8> {
624 SEG_IDS.with(|m| m.borrow().clone())
625}
626
627/// How many `segment_id` symbols have been read (never reset per frame).
628pub(crate) fn segment_id_hits() -> usize {
629 SEG_ID_HITS.with(|c| c.get())
630}
631
632/// How many distinct segment ids any decoded block has carried.
633pub(crate) fn segment_ids_seen() -> usize {
634 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
635}
636
637/// How many `seg_id_predicted` symbols have been read (temporal update).
638pub(crate) fn segment_pred_hits() -> usize {
639 SEG_PRED_HITS.with(|c| c.get())
640}
641
642/// Resets the segmentation hit counters (gate setup).
643pub(crate) fn reset_segment_hits() {
644 SEG_ID_HITS.with(|c| c.set(0));
645 SEG_IDS_SEEN.with(|c| c.set(0));
646 SEG_PRED_HITS.with(|c| c.set(0));
647}
648
649/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
650/// being decoded, with its `FeatureData` value.
651fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
652 SEG.with(|s| {
653 let s = s.borrow();
654 s.feature_active(segment_id, feature)
655 .then(|| i32::from(s.feature_data[segment_id][feature]))
656 })
657}
658
659/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
660/// `av1_get_qindex`) for the block currently being decoded: the running
661/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
662/// Every dequant call site reads the block's quantizer through here.
663fn block_q_idx() -> i32 {
664 let base = CURRENT_Q_IDX.with(|c| c.get());
665 let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
666 match seg_feature(seg_id, SEG_LVL_ALT_Q) {
667 Some(data) => (base + data).clamp(0, 255),
668 None => base,
669 }
670}
671
672/// The segment id recorded for one mi cell of the current frame's map.
673fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {
674 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
675 if mi_r >= mi_rows || mi_c >= mi_cols {
676 return 0;
677 }
678 SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
679}
680
681/// `set_segment_id`: stamps `id` over every mi cell this block covers.
682fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {
683 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
684 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
685 SEG_IDS.with(|m| {
686 let mut m = m.borrow_mut();
687 for y in 0..y_mis {
688 for x in 0..x_mis {
689 m[(mi_r + y) * mi_cols + mi_c + x] = id;
690 }
691 }
692 });
693 CUR_SEGMENT_ID.with(|c| c.set(id));
694 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
695}
696
697/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
698/// `last_frame_seg_map`): the minimum previous-frame segment id over the
699/// block's own mi footprint. `0` when there is no previous map.
700fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {
701 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
702 PREV_SEG_IDS.with(|m| {
703 let m = m.borrow();
704 if m.is_empty() {
705 return 0;
706 }
707 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
708 let mut id = u8::MAX;
709 for y in 0..y_mis {
710 for x in 0..x_mis {
711 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
712 }
713 }
714 if id == u8::MAX { 0 } else { id }
715 })
716}
717
718/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
719fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
720 if reference == 0 {
721 return diff;
722 }
723 if reference >= max - 1 {
724 return max - diff - 1;
725 }
726 let half = if 2 * reference < max {
727 diff <= 2 * reference
728 } else {
729 diff <= 2 * (max - reference - 1)
730 };
731 if half {
732 return if diff & 1 != 0 {
733 reference + ((diff + 1) >> 1)
734 } else {
735 reference - (diff >> 1)
736 };
737 }
738 if 2 * reference < max { diff } else { max - (diff + 1) }
739}
740
741/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
742/// frame's already-decoded above/left/above-left neighbours.
743fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
744 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
745 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
746 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));
747 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
748 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
749 let ctx = match prev_ul {
750 None => 0,
751 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
752 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
753 Some(_) => 0,
754 };
755 let pred = match (prev_u, prev_l) {
756 (None, l) => l.unwrap_or(0),
757 (Some(u), None) => u,
758 (Some(u), Some(l)) => {
759 if prev_ul == Some(u) {
760 u
761 } else {
762 l
763 }
764 }
765 };
766 (pred, ctx)
767}
768
769/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
770/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
771/// that prediction. Does NOT write the map -- callers do.
772fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {
773 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
774 if skip {
775 return pred as u8;
776 }
777 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
778 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
779 let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));
780 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
781}
782
783/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
784/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
785/// caller decides which by passing `pre_skip`).
786fn intra_segment_id(
787 dec: &mut SymbolDecoder,
788 cdfs: &mut Cdfs,
789 mi_r: usize,
790 mi_c: usize,
791 w_mi: usize,
792 h_mi: usize,
793 skip: bool,
794) {
795 if !SEG.with(|s| s.borrow().enabled) {
796 return;
797 }
798 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
799 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
800}
801
802/// Whether this frame's intra blocks read their `segment_id` before `skip`
803/// (`SegIdPreSkip`); `false` also when segmentation is off.
804fn seg_id_pre_skip() -> bool {
805 SEG.with(|s| {
806 let s = s.borrow();
807 s.enabled && s.seg_id_pre_skip
808 })
809}
810
811/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
812/// Called at both spec positions of an inter frame's block: `pre_skip = true`
813/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
814fn inter_segment_id(
815 dec: &mut SymbolDecoder,
816 cdfs: &mut Cdfs,
817 mi_r: usize,
818 mi_c: usize,
819 w_mi: usize,
820 h_mi: usize,
821 skip: bool,
822 pre_skip: bool,
823) {
824 let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
825 let s = s.borrow();
826 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
827 });
828 if !enabled {
829 return;
830 }
831 if !update_map {
832 // The map is inherited wholesale from the previous frame.
833 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
834 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
835 return;
836 }
837 if pre_skip && !pre_skip_frame {
838 return;
839 }
840 if !pre_skip && skip {
841 // libaom: a skipped block never codes `seg_id_predicted`, and its
842 // segment id is the spatial prediction.
843 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
844 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
845 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
846 return;
847 }
848 let id = if temporal_update {
849 let ctx = seg_pred_ctx(mi_r, mi_c);
850 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
851 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
852 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));
853 if predicted {
854 predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
855 } else {
856 read_segment_id(dec, cdfs, mi_r, mi_c, false)
857 }
858 } else {
859 read_segment_id(dec, cdfs, mi_r, mi_c, false)
860 };
861 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
862}
863
864/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
865fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
866 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
867 // so contribute 0) outside the tile -- the availability check here is
868 // what keeps a previous tile's stamps out of this tile's context.
869 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
870 let above = if mi_r > row0 {
871 ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
872 } else {
873 0
874 };
875 let left = if mi_c > col0 {
876 LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
877 } else {
878 0
879 };
880 usize::from(above + left)
881}
882
883/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
884fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {
885 ABOVE_SEG_PRED.with(|m| {
886 let mut m = m.borrow_mut();
887 for i in 0..w_mi {
888 if let Some(cell) = m.get_mut(mi_c + i) {
889 *cell = value;
890 }
891 }
892 });
893 LEFT_SEG_PRED.with(|m| {
894 let mut m = m.borrow_mut();
895 for i in 0..h_mi {
896 if let Some(cell) = m.get_mut(mi_r + i) {
897 *cell = value;
898 }
899 }
900 });
901}
902
903// How many key-frame luma blocks resolved `smooth_neighbor` (spec
904// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
905// counter, proving a stream actually put a directional block next to a
906// smooth-predicted neighbour rather than every block reading the (previously
907// hardcoded `false`) edge-filter strength bucket unchanged.
908thread_local! {
909 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
910 const { std::cell::Cell::new(0) };
911}
912
913/// Current value of [`SMOOTH_LUMA_HITS`].
914pub(crate) fn smooth_luma_hits() -> usize {
915 SMOOTH_LUMA_HITS.with(|c| c.get())
916}
917
918thread_local! {
919 /// lane-band46 r1: how many split-transform units answered their intra
920 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
921 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
922 /// apply to them (class reach-is-per-transform-unit). Every hit is a
923 /// transform unit whose above-right / below-left reference samples would
924 /// be wrong without that fix.
925 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
926 const { std::cell::Cell::new(0) };
927}
928
929/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
930pub(crate) fn split_tu_reach_fix_hits() -> usize {
931 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
932}
933
934/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
935/// answer differs from the standalone-block answer the call sites used before
936/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
937/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
938/// block's top-left `(px, py)`.
939#[allow(clippy::too_many_arguments)]
940fn tu_reach(
941 bw: usize,
942 bh: usize,
943 col_off: usize,
944 row_off: usize,
945 tx: usize,
946 block: Reach,
947 px: usize,
948 py: usize,
949 width: usize,
950 height: usize,
951) -> Reach {
952 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
953 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height);
954 if fixed != standalone {
955 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));
956 }
957 fixed
958}
959
960// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
961// across every call on the current thread -- lane-chroma r3's own before/after
962// counter, proving a stream actually exercised chroma's smooth/paeth
963// predictor (the previously-refused round-2 gap) rather than every block
964// landing on DC/CFL/directional.
965thread_local! {
966 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
967 const { std::cell::Cell::new(0) };
968}
969
970/// Current value of [`SMOOTH_UV_HITS`].
971pub(crate) fn smooth_uv_hits() -> usize {
972 SMOOTH_UV_HITS.with(|c| c.get())
973}
974
975// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
976// full superblock walk over, across every call on the current thread --
977// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
978// multi-tile stream must prove more than one tile actually fired, not just
979// that the stream carried tile_info.cols > 1.
980thread_local! {
981 static TILE_HITS: std::cell::Cell<usize> =
982 const { std::cell::Cell::new(0) };
983}
984/// Current value of [`TILE_HITS`].
985pub(crate) fn tile_hits() -> usize {
986 TILE_HITS.with(|c| c.get())
987}
988
989// How many 4-pixel deblocking edge groups [`edge_params`] has actually
990// selected for filtering, across every call on the current thread -- the same
991// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
992// exercised `apply_deblock` rather than every edge landing on level 0.
993thread_local! {
994 static DEBLOCK_HITS: std::cell::Cell<usize> =
995 const { std::cell::Cell::new(0) };
996}
997/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
998/// mirroring stream.rs's `pictures_decoded` so the two dumps index
999/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1000static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
1001 std::sync::atomic::AtomicUsize::new(0);
1002
1003/// Current value of [`DEBLOCK_HITS`].
1004pub(crate) fn deblock_hits() -> usize {
1005 DEBLOCK_HITS.with(|c| c.get())
1006}
1007
1008// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1009// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1010// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1011// stream built with `--enable-onesided-comp=1` really exercised the
1012// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1013thread_local! {
1014 static UNI_COMP_HITS: std::cell::Cell<usize> =
1015 const { std::cell::Cell::new(0) };
1016}
1017
1018/// Current value of [`UNI_COMP_HITS`].
1019pub(crate) fn uni_comp_hits() -> usize {
1020 UNI_COMP_HITS.with(|c| c.get())
1021}
1022
1023// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1024// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1025// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1026// blend and not only the wedge arm.
1027thread_local! {
1028 static DIFFWTD_HITS: std::cell::Cell<usize> =
1029 const { std::cell::Cell::new(0) };
1030}
1031
1032/// Current value of [`DIFFWTD_HITS`].
1033pub(crate) fn diffwtd_hits() -> usize {
1034 DIFFWTD_HITS.with(|c| c.get())
1035}
1036
1037// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1038// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1039// this decoder's square inter path reaches), so no `compound_type` symbol is
1040// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1041// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1042thread_local! {
1043 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1044 const { std::cell::Cell::new(0) };
1045}
1046
1047/// Current value of [`DIFFWTD_INFERRED_HITS`].
1048pub(crate) fn diffwtd_inferred_hits() -> usize {
1049 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1050}
1051
1052// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1053// with `show_frame == 0`, output later by a `show_existing_frame` header
1054// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1055// `stream::decode_stream`, which is where the frame header is consumed; the
1056// gate's proof that the on-value really reached the bitstream rather than
1057// being dropped by the rate control.
1058thread_local! {
1059 static FWD_KF_HITS: std::cell::Cell<usize> =
1060 const { std::cell::Cell::new(0) };
1061}
1062
1063/// Current value of [`FWD_KF_HITS`].
1064pub(crate) fn fwd_kf_hits() -> usize {
1065 FWD_KF_HITS.with(|c| c.get())
1066}
1067
1068/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1069pub(crate) fn note_fwd_kf() {
1070 FWD_KF_HITS.with(|c| c.set(c.get() + 1));
1071}
1072
1073// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1074// the block's own side, across every call on the current thread -- the same
1075// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1076// actually exercised a *split* transform under `TxMode::Select` rather than
1077// every block coincidentally resolving `depth=0` (indistinguishable from
1078// `TxMode::Largest` pixel-wise).
1079thread_local! {
1080 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1081 const { std::cell::Cell::new(0) };
1082}
1083
1084// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1085// transform smaller than their own side (`tx_depth != 0`) while coding a
1086// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1087// only exercises with aomenc's tx-size search left ON (its default), which
1088// every older recipe in this file pins off. Counted at the block, so a stream
1089// where RD happened to give every split-transform block a DC chroma mode
1090// reads as zero rather than silently passing for free.
1091thread_local! {
1092 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1093 const { std::cell::Cell::new(0) };
1094}
1095
1096/// Current value of [`SQ_CHROMA_TX_HITS`].
1097pub(crate) fn sq_chroma_tx_hits() -> usize {
1098 SQ_CHROMA_TX_HITS.with(|c| c.get())
1099}
1100
1101/// Current value of [`TX_DEPTH_HITS`].
1102pub(crate) fn tx_depth_hits() -> usize {
1103 TX_DEPTH_HITS.with(|c| c.get())
1104}
1105
1106// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1107// read, and how many of those actually took the split, on the current thread
1108// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1109// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1110// coincidentally coding one whole-block transform.
1111thread_local! {
1112 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1113 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1114 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1115 // strips coded one whole-block rect transform unit, and how many split
1116 // their rect max transform into square sub-transforms.
1117 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1118 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1119 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1120 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1121 // truncated low-32 corner.
1122 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1123 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1124 // inter strip, `[32x8, 8x32]`.
1125 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1126 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1127 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1128 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1129 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1130 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1131 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1132 // frame -- 16x8 and 8x16 inter leaves.
1133 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1134 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1135 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1136 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1137 // `decode_inter_block` already carries forty parameters and both are
1138 // frame-constant.
1139 static TX_SELECT_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1140 static REDUCED_TX_SET_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
1141 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1142 // frame-constant like the two above and stashed the same way -- an intra
1143 // block inside an inter frame reads `use_filter_intra` under it.
1144 static ENABLE_FILTER_INTRA_INTER: std::cell::Cell<bool> =
1145 const { std::cell::Cell::new(false) };
1146}
1147
1148/// Current value of [`TXFM_SPLIT_READS`].
1149pub(crate) fn txfm_split_reads() -> usize {
1150 TXFM_SPLIT_READS.with(|c| c.get())
1151}
1152
1153/// Current value of [`TXFM_SPLIT_HITS`].
1154pub(crate) fn txfm_split_hits() -> usize {
1155 TXFM_SPLIT_HITS.with(|c| c.get())
1156}
1157
1158/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1159pub(crate) fn inter_leaf16_horz_hits() -> usize {
1160 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1161}
1162
1163/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1164pub(crate) fn inter_leaf16_vert_hits() -> usize {
1165 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1166}
1167
1168/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1169pub(crate) fn rect_inter_tu_hits() -> usize {
1170 RECT_INTER_TU_HITS.with(|c| c.get())
1171}
1172
1173/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1174pub(crate) fn rect_inter_txsplit_hits() -> usize {
1175 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1176}
1177
1178/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1179pub(crate) fn rect64_inter_tu_hits() -> usize {
1180 RECT64_INTER_TU_HITS.with(|c| c.get())
1181}
1182
1183/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1184/// whole-block luma units of a 32x32-level 1:4 inter strip.
1185pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1186 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1187}
1188
1189/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1190/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1191pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1192 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1193}
1194
1195/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1196/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1197pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1198 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1199}
1200
1201/// Records one rectangular var-tx leaf.
1202fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1203 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1204 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1205 }
1206 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1207 cell.with(|c| {
1208 let mut h = c.get();
1209 h[usize::from(th > tw)] += 1;
1210 c.set(h);
1211 });
1212}
1213
1214/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1215/// [`ENABLE_FILTER_INTRA_INTER`].
1216pub(crate) fn set_inter_tx_mode(
1217 tx_select: bool,
1218 reduced_tx_set: bool,
1219 enable_filter_intra: bool,
1220) {
1221 TX_SELECT_INTER.with(|c| c.set(tx_select));
1222 REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));
1223 ENABLE_FILTER_INTRA_INTER.with(|c| c.set(enable_filter_intra));
1224}
1225
1226// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1227// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1228// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1229// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1230// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1231// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1232// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1233// path above).
1234thread_local! {
1235 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1236 const { std::cell::Cell::new(0) };
1237}
1238
1239/// Current value of [`VERT_B_INTRA_HITS`].
1240pub(crate) fn vert_b_intra_hits() -> usize {
1241 VERT_B_INTRA_HITS.with(|c| c.get())
1242}
1243
1244// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1245// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1246// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1247// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1248// every arm separately so a run where aomenc's RD only picked one cannot
1249// pass as proof of four.
1250thread_local! {
1251 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1252}
1253
1254/// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1255thread_local! {
1256 /// 4x4 transform units decoded inside an 8x8 square of a
1257 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1258 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1259 /// a real `--enable-tx-size-search=1` stream reaches it.
1260 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1261}
1262
1263pub(crate) fn vert_ab_tx4_hits() -> usize {
1264 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1265}
1266
1267pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1268 AB16_HITS.with(std::cell::Cell::get)
1269}
1270
1271fn bump_ab16(arm: usize) {
1272 AB16_HITS.with(|c| {
1273 let mut v = c.get();
1274 v[arm] += 1;
1275 c.set(v);
1276 });
1277}
1278
1279// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1280// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1281// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1282// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1283// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1284// superblock's z-order recursion, not raster mi position).
1285thread_local! {
1286 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1287 const { std::cell::Cell::new(0) };
1288}
1289
1290/// Current value of [`HORZ_VERT_INTRA_HITS`].
1291pub(crate) fn horz_vert_intra_hits() -> usize {
1292 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1293}
1294
1295// How many blocks were decoded as a frame-edge rect strip -- the single
1296// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1297// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1298// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1299// paths share the counter.
1300thread_local! {
1301 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1302 const { std::cell::Cell::new(0) };
1303}
1304
1305/// Current value of [`EDGE_RECT_STRIP_HITS`].
1306pub(crate) fn edge_rect_strip_hits() -> usize {
1307 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1308}
1309
1310// lane-interedge r1: frame-edge half strips on the INTER path, per partition
1311// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
1312// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
1313// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
1314// are height mod 16 == 8, so every inter frame crosses these nodes.
1315thread_local! {
1316 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
1317 const { std::cell::Cell::new([0; 6]) };
1318}
1319
1320/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1321pub(crate) fn bump_inter_edge_strip(idx: usize) {
1322 INTER_EDGE_STRIP_HITS.with(|c| {
1323 let mut v = c.get();
1324 v[idx] += 1;
1325 c.set(v);
1326 });
1327}
1328
1329// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
1330// forced split -- libaom `decode_partition` (decodeframe.c):
1331// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
1332// straddle case that reads NO symbol at all. Indexed by level:
1333// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
1334thread_local! {
1335 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
1336 const { std::cell::Cell::new([0; 4]) };
1337}
1338
1339fn bump_edge_both_cut(level: usize) {
1340 EDGE_BOTH_CUT_HITS.with(|c| {
1341 let mut v = c.get();
1342 v[level] += 1;
1343 c.set(v);
1344 });
1345}
1346
1347/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
1348pub fn inter_edge_strip_hits() -> [usize; 6] {
1349 INTER_EDGE_STRIP_HITS.with(|c| c.get())
1350}
1351
1352/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
1353/// into the next one (class `counter-from-refused-stream`).
1354pub fn reset_inter_edge_strip_hits() {
1355 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
1356}
1357
1358/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
1359pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
1360 EDGE_BOTH_CUT_HITS.with(|c| c.get())
1361}
1362
1363/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
1364pub(crate) fn reset_edge_both_cut_hits() {
1365 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
1366}
1367
1368// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1369// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1370// the case every rect path here refused by name before, and the first
1371// refusal the user's ReelB extract (600s in) stops at.
1372thread_local! {
1373 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1374 const { std::cell::Cell::new(0) };
1375}
1376
1377/// Current value of [`RECT_SPLIT_TX_HITS`].
1378pub(crate) fn rect_split_tx_hits() -> usize {
1379 RECT_SPLIT_TX_HITS.with(|c| c.get())
1380}
1381
1382// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1383// side 64) AND split past the first depth, i.e. tiled more than one unit in
1384// each axis -- the only shape with a transform unit that has neighbours on
1385// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1386// no gate fired before lane-rectsplit r2 (the shared counter above also
1387// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1388thread_local! {
1389 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1390 const { std::cell::Cell::new(0) };
1391}
1392
1393/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1394pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1395 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1396}
1397
1398// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1399// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1400// chroma half takes that had no coefficient tables before (index order:
1401// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1402// proves the pair it happens to hit cannot catch a transposed scan/context
1403// table (class scan-weights-cross-axis).
1404thread_local! {
1405 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1406 const { std::cell::Cell::new([0; 4]) };
1407}
1408
1409/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1410pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1411 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1412}
1413
1414// How many HORZ/VERT intra strips actually predicted with filter intra
1415// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1416// ("this decoder predicts square-only") until `predict_filter_intra` took
1417// `bw`x`bh`.
1418thread_local! {
1419 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1420 const { std::cell::Cell::new(0) };
1421}
1422
1423/// Current value of [`FILTER_INTRA_RECT_HITS`].
1424pub(crate) fn filter_intra_rect_hits() -> usize {
1425 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1426}
1427
1428// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1429// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1430// was never read at all before that round, so a gate needs to prove the flag
1431// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1432// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1433// carry different probabilities (18101 vs 20229), so a transposed pair is
1434// only caught by a gate that sees the flag fire on BOTH shapes (class
1435// scan-weights-cross-axis).
1436thread_local! {
1437 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1438 const { std::cell::Cell::new(0) };
1439 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1440 const { std::cell::Cell::new(0) };
1441}
1442
1443/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1444pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1445 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1446}
1447
1448/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1449pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1450 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1451}
1452
1453// How many rectangular transform units actually coded coefficients through
1454// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1455// exercised the rect coefficient reader at all rather than passing on
1456// all-skip blocks.
1457thread_local! {
1458 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1459 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1460}
1461
1462/// Current value of [`RECT_COEFF_TU_HITS`].
1463pub(crate) fn rect_coeff_tu_hits() -> usize {
1464 RECT_COEFF_TU_HITS.with(|c| c.get())
1465}
1466
1467/// Rectangular transform units whose resolved `tx_type` is a 1D class
1468/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1469/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1470/// for the square reader's own 1D types.
1471pub(crate) fn rect_class1_hits() -> usize {
1472 RECT_CLASS1_HITS.with(|c| c.get())
1473}
1474
1475// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1476// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1477// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1478// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1479// prove nothing about the new shapes.
1480thread_local! {
1481 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1482 const { std::cell::Cell::new(0) };
1483}
1484
1485/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1486pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1487 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1488}
1489
1490// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1491// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1492// counter would be satisfied by a 16x8 strip and prove nothing here.
1493thread_local! {
1494 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1495 const { std::cell::Cell::new(0) };
1496}
1497
1498/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1499pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1500 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1501}
1502
1503// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1504// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1505// call on the current thread -- the same before/after counter pattern as
1506// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1507// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1508// landing on `DCT_DCT`.
1509thread_local! {
1510 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1511 const { std::cell::Cell::new(0) };
1512}
1513
1514// How many `uv_mode` reads resolved to a directional chroma mode (neither
1515// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1516// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1517// actually exercised chroma's own directional predictor.
1518thread_local! {
1519 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1520 const { std::cell::Cell::new(0) };
1521}
1522
1523/// Current value of [`DIRECTIONAL_UV_HITS`].
1524pub(crate) fn directional_uv_hits() -> usize {
1525 DIRECTIONAL_UV_HITS.with(|c| c.get())
1526}
1527
1528// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1529// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1530// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1531// proving a stream actually exercised a nonzero angle delta.
1532thread_local! {
1533 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1534 const { std::cell::Cell::new(0) };
1535}
1536
1537// How many [`read_single_ref`] reads resolved to a reference other than
1538// `LAST_FRAME`, across every call on the current thread -- the same before/after
1539// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1540// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1541// only other supported one so far) rather than every block coincidentally
1542// resolving `LAST_FRAME`.
1543thread_local! {
1544 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1545 const { std::cell::Cell::new(0) };
1546}
1547
1548/// Current value of [`NON_LAST_REF_HITS`].
1549pub(crate) fn non_last_ref_hits() -> usize {
1550 NON_LAST_REF_HITS.with(|c| c.get())
1551}
1552
1553// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1554// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1555// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1556// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1557// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1558// `GOLDEN_FRAME` draw it did not ask for.
1559thread_local! {
1560 static LAST2_HITS: std::cell::Cell<usize> =
1561 const { std::cell::Cell::new(0) };
1562}
1563thread_local! {
1564 static LAST3_HITS: std::cell::Cell<usize> =
1565 const { std::cell::Cell::new(0) };
1566}
1567thread_local! {
1568 static GOLDEN_HITS: std::cell::Cell<usize> =
1569 const { std::cell::Cell::new(0) };
1570}
1571thread_local! {
1572 static BWDREF_HITS: std::cell::Cell<usize> =
1573 const { std::cell::Cell::new(0) };
1574}
1575thread_local! {
1576 static ALTREF2_HITS: std::cell::Cell<usize> =
1577 const { std::cell::Cell::new(0) };
1578}
1579thread_local! {
1580 static ALTREF_HITS: std::cell::Cell<usize> =
1581 const { std::cell::Cell::new(0) };
1582}
1583
1584// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1585// -- proves a `reference_select` stream actually reached a block that picked
1586// compound, not just that the header bit was set. Every such block is
1587// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1588// so this only ever counts attempted reads, never a completed decode.
1589thread_local! {
1590 static COMP_MODE_HITS: std::cell::Cell<usize> =
1591 const { std::cell::Cell::new(0) };
1592}
1593
1594/// Current value of [`COMP_MODE_HITS`].
1595pub(crate) fn comp_mode_hits() -> usize {
1596 COMP_MODE_HITS.with(|c| c.get())
1597}
1598
1599// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1600// use for, across every call on the current thread -- the same before/after
1601// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1602// exercised palette reconstruction rather than only reading and refusing the
1603// `palette_y_mode` symbol.
1604thread_local! {
1605 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1606}
1607
1608/// Current value of [`PALETTE_HITS`].
1609pub(crate) fn palette_hits() -> usize {
1610 PALETTE_HITS.with(|c| c.get())
1611}
1612
1613// lane-tiles r12: of those, how many sat at their own TILE's left column --
1614// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1615// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1616// palette gate that never hits one proves nothing about the tile guard.
1617thread_local! {
1618 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1619}
1620
1621/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1622pub(crate) fn palette_tile_left_hits() -> usize {
1623 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1624}
1625
1626// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1627// palette use -- proves a stream actually reconstructed UV palette pixels,
1628// not just read and refused the `palette_uv_mode` symbol.
1629thread_local! {
1630 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1631}
1632
1633/// Current value of [`PALETTE_UV_HITS`].
1634pub(crate) fn palette_uv_hits() -> usize {
1635 PALETTE_UV_HITS.with(|c| c.get())
1636}
1637
1638// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1639// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1640// (not just the square path's) actually fired.
1641thread_local! {
1642 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1643}
1644
1645/// Current value of [`PALETTE_RECT_HITS`].
1646pub(crate) fn palette_rect_hits() -> usize {
1647 PALETTE_RECT_HITS.with(|c| c.get())
1648}
1649
1650// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1651// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1652// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1653// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1654// RD, almost always refused-on-use because the block doesn't end up USING a
1655// palette -- see r5's report). This is the site the removed refusal
1656// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1657// fired here whether or not the block picked a palette, so this is the
1658// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1659// never observes.
1660thread_local! {
1661 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1662}
1663
1664/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1665pub(crate) fn rect_screen_content_hits() -> usize {
1666 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1667}
1668
1669// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1670// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1671// windowing actually ran, not just that the whole-block path stayed exact.
1672// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1673// first actually incremented in r7, when the refusal it guarded was lifted.
1674thread_local! {
1675 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1676}
1677
1678thread_local! {
1679 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
1680 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
1681 /// (16x8/8x16), the two shapes the lifted refusals named.
1682 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1683}
1684
1685/// Current value of [`RECT4_PALETTE_HITS`].
1686pub(crate) fn rect4_palette_hits() -> usize {
1687 RECT4_PALETTE_HITS.with(|c| c.get())
1688}
1689
1690/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1691pub(crate) fn palette_split_tx_hits() -> usize {
1692 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1693}
1694
1695thread_local! {
1696 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
1697 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
1698 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
1699 /// `--min-partition-size=8` puts them on this leaf path.
1700 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1701}
1702
1703/// Current value of [`PALETTE_LEAF8_HITS`].
1704pub(crate) fn palette_leaf8_hits() -> usize {
1705 PALETTE_LEAF8_HITS.with(|c| c.get())
1706}
1707
1708/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
1709pub(crate) fn reset_palette_leaf8_hits() {
1710 PALETTE_LEAF8_HITS.with(|c| c.set(0));
1711}
1712
1713thread_local! {
1714 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
1715 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
1716 /// block that also carries a real, corner-cropped luma transform.
1717 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1718}
1719
1720/// Current value of [`PALETTE_SB_STRIP_HITS`].
1721pub(crate) fn palette_sb_strip_hits() -> usize {
1722 PALETTE_SB_STRIP_HITS.with(|c| c.get())
1723}
1724
1725/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
1726pub(crate) fn reset_palette_sb_strip_hits() {
1727 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
1728}
1729
1730// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
1731// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
1732// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
1733// capability rather than the key frame's, which every screen stream also
1734// carries.
1735thread_local! {
1736 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1737 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1738}
1739
1740// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
1741// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
1742// shared counter too, so only this one proves a gate really reached the leaf
1743// where the refusal used to sit.
1744thread_local! {
1745 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
1746 const { std::cell::Cell::new((0, 0)) };
1747}
1748
1749/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
1750pub(crate) fn inter8_palette_hits() -> (usize, usize) {
1751 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
1752}
1753
1754/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
1755pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
1756 (
1757 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
1758 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
1759 )
1760}
1761
1762// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
1763// and which are therefore predicted one transform unit at a time (a skipped
1764// block codes no coefficients, so nothing else in the stream witnesses this
1765// path -- only the pixels do).
1766thread_local! {
1767 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1768}
1769
1770/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
1771pub fn skip_split_tx_hits() -> usize {
1772 SKIP_SPLIT_TX_HITS.with(|c| c.get())
1773}
1774
1775/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
1776pub fn reset_skip_split_tx_hits() {
1777 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
1778}
1779
1780// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
1781// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
1782// the gate's proof that the lifted path actually ran, per size.
1783thread_local! {
1784 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
1785 const { std::cell::Cell::new([0; 4]) };
1786}
1787
1788/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
1789pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
1790 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
1791}
1792
1793thread_local! {
1794 /// A just-decoded palette-Y block's own predicted pixels
1795 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1796 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1797 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1798 /// per-block override through `read_plane`'s two dozen call sites is the
1799 /// alternative this avoids). Always empty again once that call consumes
1800 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
1801 /// sees stale state.
1802 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1803 const { std::cell::RefCell::new(None) };
1804}
1805
1806
1807/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
1808/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
1809/// site whose reconstruct never runs would be picked up by the NEXT block's
1810/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1811/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1812#[track_caller]
1813fn set_palette_pred(buf: Vec<u16>) {
1814 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1815 let stale = PALETTE_PRED.with(|c| c.borrow().is_some());
1816 eprintln!(
1817 "PALSET len={} stale={stale} at {}",
1818 buf.len(),
1819 std::panic::Location::caller()
1820 );
1821 }
1822 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
1823}
1824
1825#[track_caller]
1826fn take_palette_pred() -> Option<Vec<u16>> {
1827 let got = PALETTE_PRED.with(|c| c.borrow_mut().take());
1828 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1829 eprintln!(
1830 "PALTAKE len={:?} at {}",
1831 got.as_ref().map(Vec::len),
1832 std::panic::Location::caller()
1833 );
1834 }
1835 got
1836}
1837
1838thread_local! {
1839 /// The current frame's `mi` grid, kept only while a frame header set
1840 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
1841 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
1842 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
1843 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
1844 /// does not allow intrabc (so nothing is paid for it).
1845 ///
1846 /// corner-cut: only [`decode_block`] (the square path) records into it,
1847 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
1848 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
1849 /// be wrong there; upgrade = record from the rect/leaf paths too.
1850 static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1851 const { std::cell::RefCell::new(None) };
1852 /// The block vector [`read_intra_mode`] just decoded, handed to
1853 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1854 /// which the alternative -- a tenth tuple member through every caller --
1855 /// already avoids). Always `.take()`n by the block that reads it.
1856 static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1857 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1858 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1859 /// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
1860 /// an intrabc block's chroma reads can inherit it (see
1861 /// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
1862 /// through that one arming site.
1863 static LUMA_TX_TYPE: std::cell::Cell<TxType> = const { std::cell::Cell::new(TxType::DctDct) };
1864 /// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
1865 /// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
1866 /// satisfies (`blockd.h:373`) -- and takes the *colocated luma
1867 /// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
1868 /// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
1869 /// intrabc block's two chroma [`read_plane`] calls; the type decides the
1870 /// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
1871 /// -- getting it wrong desyncs the chroma coefficients, it is not a
1872 /// reconstruction-only detail.
1873 static INTRABC_CHROMA_TX: std::cell::Cell<Option<TxType>> = const { std::cell::Cell::new(None) };
1874}
1875
1876/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
1877/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
1878/// needs no separate plumbing to reach the rect-strip mode reader.
1879fn allow_intrabc_frame() -> bool {
1880 INTRABC_MI_GRID.with(|g| g.borrow().is_some())
1881}
1882
1883thread_local! {
1884 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
1885 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
1886 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
1887 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1888}
1889
1890/// Current value of [`RECT_INTRABC_READS`].
1891pub(crate) fn rect_intrabc_reads() -> usize {
1892 RECT_INTRABC_READS.with(|c| c.get())
1893}
1894
1895/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
1896pub(crate) fn reset_rect_intrabc_reads() {
1897 RECT_INTRABC_READS.with(|c| c.set(0));
1898}
1899
1900thread_local! {
1901 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
1902 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
1903 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1904}
1905
1906/// Current value of [`LEAF8_INTRABC_HITS`].
1907pub(crate) fn leaf8_intrabc_hits() -> usize {
1908 LEAF8_INTRABC_HITS.with(|c| c.get())
1909}
1910
1911/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
1912pub(crate) fn reset_leaf8_intrabc_hits() {
1913 LEAF8_INTRABC_HITS.with(|c| c.set(0));
1914}
1915
1916/// Current value of [`INTRABC_HITS`].
1917pub(crate) fn intrabc_hits() -> usize {
1918 INTRABC_HITS.with(|c| c.get())
1919}
1920
1921/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
1922pub(crate) fn reset_intrabc_hits() {
1923 INTRABC_HITS.with(|c| c.set(0));
1924}
1925
1926/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1927/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1928/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1929/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1930fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1931 INTRABC_MI_GRID.with(|g| {
1932 let mut g = g.borrow_mut();
1933 let Some((grid, _, _)) = g.as_mut() else {
1934 return;
1935 };
1936 let info = crate::mvstack::MiInfo {
1937 is_inter: dv.is_some(),
1938 ref_frame: 0,
1939 ref_frame1: None,
1940 mv: dv.unwrap_or((0, 0)),
1941 mv1: None,
1942 is_new_mv: dv.is_some(),
1943 is_global_mv0: false,
1944 is_global_mv1: false,
1945 size: n4,
1946 size_h: n4,
1947 };
1948 for r in mi_r..mi_r + n4 {
1949 for c in mi_c..mi_c + n4 {
1950 grid.set(r, c, info);
1951 }
1952 }
1953 });
1954}
1955
1956// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
1957// proves a real `skip_mode_present` stream actually reached a block that
1958// picked it, not just that the frame header bit was set.
1959thread_local! {
1960 static SKIP_MODE_HITS: std::cell::Cell<usize> =
1961 const { std::cell::Cell::new(0) };
1962}
1963
1964/// Current value of [`SKIP_MODE_HITS`].
1965pub(crate) fn skip_mode_hits() -> usize {
1966 SKIP_MODE_HITS.with(|c| c.get())
1967}
1968
1969// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
1970// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
1971// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
1972// reached [`obmc_blend`], not just the header bit.
1973thread_local! {
1974 static OBMC_HITS: std::cell::Cell<usize> =
1975 const { std::cell::Cell::new(0) };
1976}
1977
1978// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
1979// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
1980// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
1981// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
1982// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
1983// decoder used to read with the wrong alphabet, so a gate that asserts this
1984// counter advanced proves the fixed path fired (class
1985// `gate-blind-to-feature`).
1986thread_local! {
1987 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1988}
1989
1990/// Current value of [`FIMV_ALPHABET_HITS`].
1991pub fn fimv_alphabet_hits() -> usize {
1992 FIMV_ALPHABET_HITS.with(|c| c.get())
1993}
1994
1995// lane-fimv r1: how many frame headers this decoder has decoded with
1996/// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
1997// prove the encoder really produced the header state under test rather than
1998// assume it.
1999thread_local! {
2000 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2001}
2002
2003/// Current value of [`FIMV_FRAME_HITS`].
2004pub fn fimv_frame_hits() -> usize {
2005 FIMV_FRAME_HITS.with(|c| c.get())
2006}
2007
2008/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
2009/// `force_integer_mv` bit is set.
2010pub fn note_force_integer_mv_frame() {
2011 FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1));
2012}
2013
2014/// Current value of [`OBMC_HITS`].
2015pub(crate) fn obmc_hits() -> usize {
2016 OBMC_HITS.with(|c| c.get())
2017}
2018
2019// lane-scaledref r1: per-case firing counts for the scaled-reference gate
2020// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
2021// reference would pass just as well and prove nothing, so the gate
2022// hard-asserts each combination this round lifts actually occurred:
2023// a compound block with a scaled tap, a warp block whose warp libaom
2024// suppresses because the reference is scaled, an OBMC block, an interintra
2025// block, and an 8x8 leaf.
2026thread_local! {
2027 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2028 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2029 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2030 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2031 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2032 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2033 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2034}
2035
2036/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
2037/// scaled and one unscaled tap.
2038pub(crate) fn mixed_scale_compound_hits() -> usize {
2039 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
2040}
2041
2042/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
2043/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
2044/// instead because their reference is scaled (libaom `motion_mode_allowed`,
2045/// `blockd.h:1484`).
2046pub(crate) fn scaled_warp_suppressed_hits() -> usize {
2047 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
2048}
2049
2050/// Current value of [`SCALED_COMPOUND_HITS`].
2051pub(crate) fn scaled_compound_hits() -> usize {
2052 SCALED_COMPOUND_HITS.with(|c| c.get())
2053}
2054
2055/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
2056pub(crate) fn scaled_warp_fallback_hits() -> usize {
2057 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
2058}
2059
2060/// Current value of [`SCALED_OBMC_HITS`].
2061pub(crate) fn scaled_obmc_hits() -> usize {
2062 SCALED_OBMC_HITS.with(|c| c.get())
2063}
2064
2065/// Current value of [`SCALED_INTERINTRA_HITS`].
2066pub(crate) fn scaled_interintra_hits() -> usize {
2067 SCALED_INTERINTRA_HITS.with(|c| c.get())
2068}
2069
2070/// Current value of [`SCALED_BLOCK8_HITS`].
2071pub(crate) fn scaled_block8_hits() -> usize {
2072 SCALED_BLOCK8_HITS.with(|c| c.get())
2073}
2074
2075// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
2076// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
2077// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
2078// 8x8-leaf OBMC block apart from a 16x16+ one.
2079thread_local! {
2080 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2081}
2082
2083// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
2084// pair whose two directions differ (`enable_dual_filter` only -- with dual
2085// filter off both directions take the single symbol, so this can never fire).
2086// A gate asserting it proves the stream really carries dual-filter blocks.
2087thread_local! {
2088 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2089}
2090
2091// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
2092// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
2093// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
2094// no-filter sentinel that made a neighbouring OBMC block panic).
2095thread_local! {
2096 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2097}
2098
2099/// Current value of [`DUAL_FILTER_DIFF_HITS`].
2100pub(crate) fn dual_filter_diff_hits() -> usize {
2101 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
2102}
2103
2104/// Current value of [`COMPOUND8_FILTER_HITS`].
2105pub(crate) fn compound8_filter_hits() -> usize {
2106 COMPOUND8_FILTER_HITS.with(|c| c.get())
2107}
2108
2109// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
2110// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
2111// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
2112// -- the gate's proof that a fixture really exercises the alphabet this
2113// round changed, even though the block itself still refuses (warp
2114// estimation/filter not ported).
2115thread_local! {
2116 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
2117 const { std::cell::Cell::new(0) };
2118}
2119
2120/// Current value of [`WARP_SELECTED_HITS`].
2121pub(crate) fn warp_selected_hits() -> usize {
2122 WARP_SELECTED_HITS.with(|c| c.get())
2123}
2124
2125// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
2126// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
2127// into the compound intermediate) rather than translationally -- the
2128// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
2129// really reached [`crate::warp::warp_affine_compound`].
2130thread_local! {
2131 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
2132 const { std::cell::Cell::new(0) };
2133}
2134
2135/// Current value of [`COMPOUND_WARP_HITS`].
2136pub(crate) fn compound_warp_hits() -> usize {
2137 COMPOUND_WARP_HITS.with(|c| c.get())
2138}
2139
2140// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
2141// arm ([`decode_inter_block8`]) -- that arm predicted both taps
2142// translationally until r3, so a gate needs to tell a warped 8x8 compound
2143// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
2144thread_local! {
2145 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
2146 const { std::cell::Cell::new(0) };
2147}
2148
2149/// Current value of [`COMPOUND_WARP_HITS_8`].
2150pub(crate) fn compound_warp_hits_8() -> usize {
2151 COMPOUND_WARP_HITS_8.with(|c| c.get())
2152}
2153
2154// lane-gmaffine r1: how many blocks built their prediction from a
2155// SIX-parameter (`AFFINE`) global-motion model through
2156// `crate::warp::global_warp_params` -- the gate's proof that a stream really
2157// carried an AFFINE `global_motion_params` AND that a block was predicted
2158// with it, not merely that the header parsed one.
2159thread_local! {
2160 static AFFINE_GM_HITS: std::cell::Cell<usize> =
2161 const { std::cell::Cell::new(0) };
2162}
2163
2164/// Current value of [`AFFINE_GM_HITS`].
2165pub(crate) fn affine_gm_hits() -> usize {
2166 AFFINE_GM_HITS.with(|c| c.get())
2167}
2168
2169// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
2170// differently at the block's WIDTH than at libaom's
2171// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
2172// pick the wrong motion_mode alphabet.
2173thread_local! {
2174 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2175}
2176
2177/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
2178pub fn tr_reach_longer_side_hits() -> usize {
2179 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
2180}
2181
2182// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
2183// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
2184// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
2185// reads its interp-filter symbol. Counts the blocks where that guard flips
2186// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
2187// and a 4-px side, which we used to suppress the interp read on (a pre-mode
2188// entropy desync one symbol wide).
2189thread_local! {
2190 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2191}
2192
2193/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
2194pub fn gm_nontrans_small_side_hits() -> usize {
2195 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
2196}
2197
2198// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
2199// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
2200// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
2201// only once `find_projection` returned a usable model, unlike
2202// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
2203// proof that the leaf path itself fired, not the 16x16+ one.
2204thread_local! {
2205 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2206 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2207}
2208
2209/// Current value of [`GLOBALMV_HITS_8`].
2210pub(crate) fn globalmv_hits_8() -> usize {
2211 GLOBALMV_HITS_8.with(|c| c.get())
2212}
2213
2214/// Current value of [`WARP_HITS_8`].
2215pub(crate) fn warp_hits_8() -> usize {
2216 WARP_HITS_8.with(|c| c.get())
2217}
2218
2219// How many blocks decoded `interintra == 1` with the non-wedge blended
2220// prediction applied (lane-interintra r1) -- the gate's proof that a
2221// stream actually exercised interintra.
2222thread_local! {
2223 static INTERINTRA_HITS: std::cell::Cell<usize> =
2224 const { std::cell::Cell::new(0) };
2225}
2226
2227/// Current value of [`INTERINTRA_HITS`].
2228pub(crate) fn interintra_hits() -> usize {
2229 INTERINTRA_HITS.with(|c| c.get())
2230}
2231
2232// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
2233// -- the shape `interintra_blend` used to build a square `side x side` intra
2234// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
2235// pre-existing interintra gate passed with that bug, so the rect arm needs
2236// its own counter to stop being vacuous.
2237thread_local! {
2238 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2239}
2240
2241/// Current value of [`INTERINTRA_RECT_HITS`].
2242pub fn interintra_rect_hits() -> usize {
2243 INTERINTRA_RECT_HITS.with(|c| c.get())
2244}
2245
2246// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
2247// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
2248// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
2249// gate fixture actually exercises this alphabet, even though the block
2250// still refuses (the mask blend itself is unported).
2251thread_local! {
2252 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
2253 const { std::cell::Cell::new(0) };
2254}
2255
2256/// Current value of [`MASKED_COMPOUND_HITS`].
2257pub(crate) fn masked_compound_hits() -> usize {
2258 MASKED_COMPOUND_HITS.with(|c| c.get())
2259}
2260
2261// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
2262// masked-compound block whose true footprint is rectangular, i.e. the case
2263// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
2264// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
2265// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
2266thread_local! {
2267 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
2268 const { std::cell::Cell::new(0) };
2269}
2270
2271/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
2272pub(crate) fn rect_masked_compound_hits() -> usize {
2273 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
2274}
2275
2276// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
2277// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
2278// actually exercised the wedge blend, not just the DIFFWTD half of
2279// `MASKED_COMPOUND_HITS`.
2280thread_local! {
2281 static WEDGE_HITS: std::cell::Cell<usize> =
2282 const { std::cell::Cell::new(0) };
2283}
2284
2285/// Current value of [`WEDGE_HITS`].
2286pub(crate) fn wedge_hits() -> usize {
2287 WEDGE_HITS.with(|c| c.get())
2288}
2289
2290// How many blocks decoded a real wedge-INTERINTRA block
2291// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
2292// a gate fixture exercised the wedge blend (fixed sign 0), not just the
2293// smooth arm counted by `INTERINTRA_HITS`.
2294thread_local! {
2295 static WII_HITS: std::cell::Cell<usize> =
2296 const { std::cell::Cell::new(0) };
2297}
2298
2299/// Current value of [`WII_HITS`].
2300pub(crate) fn wii_hits() -> usize {
2301 WII_HITS.with(|c| c.get())
2302}
2303
2304// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
2305// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
2306// wide <= 32 && high <= 32). The witness that a gate stream really carries a
2307// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
2308// frame carrying one.
2309thread_local! {
2310 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2311}
2312
2313/// Current value of [`NOCFL_UV_MODE_HITS`].
2314pub(crate) fn nocfl_uv_mode_hits() -> usize {
2315 NOCFL_UV_MODE_HITS.with(|c| c.get())
2316}
2317
2318/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
2319/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
2320pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
2321 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
2322
2323fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
2324 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
2325}
2326
2327// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
2328// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
2329// the rect wedge masks lifted this round actually fired, not just the square
2330// ones already counted by `WEDGE_HITS`/`WII_HITS`.
2331thread_local! {
2332 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
2333 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
2334}
2335
2336/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
2337pub(crate) fn rect_wedge_hits() -> [usize; 6] {
2338 RECT_WEDGE_HITS.with(|c| c.get())
2339}
2340
2341/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
2342pub(crate) fn rect_wii_hits() -> [usize; 6] {
2343 RECT_WII_HITS.with(|c| c.get())
2344}
2345
2346// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
2347// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
2348// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
2349// aomdec, neighbour list included).
2350thread_local! {
2351 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2352}
2353
2354/// Current value of [`OBMC_RECT_LEAF_HITS`].
2355pub(crate) fn obmc_rect_leaf_hits() -> usize {
2356 OBMC_RECT_LEAF_HITS.with(|c| c.get())
2357}
2358
2359// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
2360// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
2361// to be read from the pair's FIRST mi, which is a different block and, when
2362// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
2363// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
2364thread_local! {
2365 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2366}
2367
2368/// Current value of [`OBMC_PAIR_FILTER_HITS`].
2369pub(crate) fn obmc_pair_filter_hits() -> usize {
2370 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
2371}
2372
2373// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
2374// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
2375// own side, so a block overhanging the bottom/right still predicts the full
2376// neighbour strip (the destination write is what clips). We used to shrink the
2377// prediction to the visible part, which at 4 chroma rows/cols also swaps the
2378// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
2379thread_local! {
2380 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2381}
2382
2383/// Current value of [`OBMC_EDGE_SPAN_HITS`].
2384pub(crate) fn obmc_edge_span_hits() -> usize {
2385 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
2386}
2387
2388/// Current value of [`OBMC_HITS_8`].
2389pub(crate) fn obmc_hits_8() -> usize {
2390 OBMC_HITS_8.with(|c| c.get())
2391}
2392
2393// lane-rectgate r1: how many 32x32 quadrants actually decoded a
2394// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
2395// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
2396// `VERT_B` all still fall into the generic "a partition type this encoder
2397// never writes" refusal below) -- the gate's proof that a free-partition
2398// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
2399// coincidentally never selecting one.
2400thread_local! {
2401 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
2402 const { std::cell::Cell::new(0) };
2403}
2404
2405/// Current value of [`EXTENDED_PARTITION_HITS`].
2406pub(crate) fn extended_partition_hits() -> usize {
2407 EXTENDED_PARTITION_HITS.with(|c| c.get())
2408}
2409
2410// lane-partitions r1: how many 32x32 quadrants decoded a real
2411// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
2412// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
2413// gate's proof this round's arms actually fired.
2414thread_local! {
2415 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
2416 const { std::cell::Cell::new(0) };
2417}
2418
2419/// Current value of [`RECT_PARTITION_HITS`].
2420pub(crate) fn rect_partition_hits() -> usize {
2421 RECT_PARTITION_HITS.with(|c| c.get())
2422}
2423
2424// lane-inter8 r1: how many superblocks an inter tile coded as a single
2425// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
2426// static content, previously a named refusal).
2427thread_local! {
2428 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
2429 /// path decoded as one whole block (its gate's own witness).
2430 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2431 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
2432 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2433 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2434}
2435
2436/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
2437pub(crate) fn inter_sb128_horz_hits() -> usize {
2438 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
2439}
2440
2441/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
2442pub(crate) fn inter_sb128_vert_hits() -> usize {
2443 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
2444}
2445
2446/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
2447pub fn inter_sb128_none_hits() -> usize {
2448 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
2449}
2450
2451thread_local! {
2452 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
2453 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
2454 /// units) -- the gate's witness that the lifted refusal's case fired.
2455 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2456}
2457
2458/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
2459pub fn intra_128_in_inter_hits() -> usize {
2460 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
2461}
2462
2463thread_local! {
2464 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
2465 const { std::cell::Cell::new(0) };
2466}
2467
2468/// Current value of [`INTER_SB_NONE_HITS`].
2469pub(crate) fn inter_sb_none_hits() -> usize {
2470 INTER_SB_NONE_HITS.with(|c| c.get())
2471}
2472
2473// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
2474// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
2475// path has always run that loop, so only this counter proves the newly-lifted
2476// alphabet value fired.
2477thread_local! {
2478 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
2479 const { std::cell::Cell::new(0) };
2480}
2481
2482/// Current value of [`INTER_SUB16_SPLIT_HITS`].
2483pub(crate) fn inter_sub16_split_hits() -> usize {
2484 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
2485}
2486
2487// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
2488// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
2489// rect coefficient reader itself fired, not just the strip-level partition
2490// symbol [`RECT_PARTITION_HITS`] already counts.
2491thread_local! {
2492 static RECT_COEFF_HITS: std::cell::Cell<usize> =
2493 const { std::cell::Cell::new(0) };
2494}
2495
2496/// Current value of [`RECT_COEFF_HITS`].
2497pub(crate) fn rect_coeff_hits() -> usize {
2498 RECT_COEFF_HITS.with(|c| c.get())
2499}
2500
2501// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
2502// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
2503// charter's real-aomenc gate hard-asserts.
2504thread_local! {
2505 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
2506 const { std::cell::Cell::new(0) };
2507}
2508
2509/// Current value of [`RECT_LEAF_COEFF_HITS`].
2510pub(crate) fn rect_leaf_coeff_hits() -> usize {
2511 RECT_LEAF_COEFF_HITS.with(|c| c.get())
2512}
2513
2514// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
2515// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
2516// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
2517// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
2518// needs rectangular intra prediction" before this round.
2519thread_local! {
2520 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
2521 const { std::cell::Cell::new([0; 3]) };
2522}
2523
2524/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
2525/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
2526pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
2527 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
2528}
2529
2530// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
2531// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
2532// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
2533// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
2534// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
2535// a single counter cannot tell an axis swap from a working arm
2536// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
2537thread_local! {
2538 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
2539 const { std::cell::Cell::new([0; 2]) };
2540}
2541
2542/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
2543/// (0 = 64x32, 1 = 32x64).
2544pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
2545 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
2546}
2547
2548// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
2549// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
2550// is never incremented) -- the gate's proof that the lifted path ran per depth.
2551thread_local! {
2552 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
2553 const { std::cell::Cell::new([0; 3]) };
2554}
2555
2556// lane-t900 r21: rect intra strips inside an inter frame that read the
2557// screen-content palette syntax (`allow_screen_content_tools` set and the
2558// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
2559// refusal used to guard, so this counter is what keeps its witness gate
2560// non-vacuous.
2561thread_local! {
2562 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2563}
2564
2565/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
2566pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
2567 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
2568}
2569
2570/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
2571pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
2572 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
2573}
2574
2575/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
2576pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
2577 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2578}
2579
2580// lane-midcut r2: rect intra blocks inside an inter frame whose `tx_depth` CDF
2581// ROW moved when libaom's inter-neighbour override was applied -- i.e. exactly
2582// the blocks the key frame's deblock-grid approximation used to mis-read.
2583thread_local! {
2584 static INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS: std::cell::Cell<usize> =
2585 const { std::cell::Cell::new(0) };
2586}
2587
2588/// Current value of [`INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS`].
2589pub(crate) fn intra_rect_in_inter_txctx_override_hits() -> usize {
2590 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(std::cell::Cell::get)
2591}
2592
2593// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
2594// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
2595// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
2596// rect strip on the inter block path" before this round.
2597thread_local! {
2598 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
2599 const { std::cell::Cell::new([0; 4]) };
2600}
2601
2602/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
2603/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
2604pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
2605 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
2606}
2607
2608// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
2609// through one of the key-frame rect readers ([`decode_block_rect4`],
2610// [`decode_block_rect64`]). `Some((size_group, skip))` tells
2611// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
2612// already read by [`decode_inter_block`] and (b) the luma mode comes off
2613// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
2614// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
2615thread_local! {
2616 static INTRA_IN_INTER_MODE: std::cell::Cell<Option<(usize, bool)>> =
2617 const { std::cell::Cell::new(None) };
2618}
2619
2620// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
2621// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
2622// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
2623// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
2624thread_local! {
2625 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
2626 const { std::cell::Cell::new(0) };
2627}
2628
2629/// Current value of [`MODE_MI_OVERRIDE_HITS`].
2630pub(crate) fn mode_mi_override_hits() -> usize {
2631 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
2632}
2633
2634// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
2635// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
2636// mode from the previous tile, where libaom's `up_available`/`left_available`
2637// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
2638// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
2639// per superblock row in `start_row`, so the luma fallback cannot leak the way
2640// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
2641// the invariant that makes the coarse fallback safe.
2642thread_local! {
2643 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
2644 const { std::cell::Cell::new(0) };
2645}
2646
2647/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
2648pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
2649 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
2650}
2651
2652// lane-cfl r1: how many times a chroma intra-edge filter-type read
2653// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
2654// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
2655// r1 defect would have filtered a chroma edge with the wrong strength.
2656thread_local! {
2657 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
2658 const { std::cell::Cell::new(0) };
2659}
2660
2661/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
2662pub(crate) fn uv_mode_mi_override_hits() -> usize {
2663 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
2664}
2665
2666// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
2667// `uv_mode` from the mi GRID where the one-slot-per-column map would have
2668// answered differently -- the sub-8x8 pair case where the pair's own first
2669// half had already overwritten the column slot the chroma-ref half reads.
2670thread_local! {
2671 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
2672 const { std::cell::Cell::new(0) };
2673}
2674
2675/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
2676pub fn uv_mode_grid_override_hits() -> usize {
2677 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
2678}
2679
2680// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
2681// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
2682// from an earlier block in that pixel row/column while the mi-exact map --
2683// which an inter block only started writing this round -- correctly says the
2684// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
2685// an INTER mode, and its `uv_mode` "is not set for inter blocks").
2686thread_local! {
2687 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
2688 const { std::cell::Cell::new(0) };
2689}
2690
2691/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
2692pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
2693 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
2694}
2695
2696// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
2697// suppressed at a TILE edge that is not a frame edge -- the above/left
2698// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
2699// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
2700// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
2701// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
2702// above would decide this tile's chroma edge filter strength.
2703thread_local! {
2704 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
2705 const { std::cell::Cell::new(0) };
2706}
2707
2708/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
2709pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
2710 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
2711}
2712
2713// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
2714// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
2715// shapes the r1 chroma defect showed up on.
2716thread_local! {
2717 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2718 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2719}
2720
2721/// Current value of [`CFL_BLOCK_HITS`].
2722pub(crate) fn cfl_block_hits() -> usize {
2723 CFL_BLOCK_HITS.with(|c| c.get())
2724}
2725
2726/// Current value of [`UV_ANGLE_DELTA_HITS`].
2727pub(crate) fn uv_angle_delta_hits() -> usize {
2728 UV_ANGLE_DELTA_HITS.with(|c| c.get())
2729}
2730
2731// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
2732// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
2733// gate's proof this round's arms actually reached a real block, not just
2734// that `partition_w64` read one of those two symbol values.
2735thread_local! {
2736 static SB_RECT_HITS: std::cell::Cell<usize> =
2737 const { std::cell::Cell::new(0) };
2738}
2739
2740/// Current value of [`SB_RECT_HITS`].
2741// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
2742// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
2743// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
2744// non-SPLIT edge arm actually decoded (before this round the bit was read and
2745// thrown away, so that arm was unreachable).
2746thread_local! {
2747 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
2748}
2749
2750/// Current value of [`EDGE_PART_HITS`].
2751pub(crate) fn edge_part_hits() -> [usize; 4] {
2752 EDGE_PART_HITS.with(|c| c.get())
2753}
2754
2755/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
2756pub(crate) fn reset_edge_part_hits() {
2757 EDGE_PART_HITS.with(|c| c.set([0; 4]));
2758}
2759
2760fn bump_edge_part(slot: usize) {
2761 EDGE_PART_HITS.with(|c| {
2762 let mut h = c.get();
2763 h[slot] += 1;
2764 c.set(h);
2765 });
2766}
2767
2768pub(crate) fn sb_rect_hits() -> usize {
2769 SB_RECT_HITS.with(|c| c.get())
2770}
2771
2772// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
2773// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
2774// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
2775// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
2776// paths (intra and inter) feed the same counter.
2777//
2778// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
2779// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
2780// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
2781// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
2782// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
2783// every SB of the last row), so the 32-level slots stay 0 on that content and
2784// only these prove the arm fired.
2785thread_local! {
2786 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
2787 const { std::cell::Cell::new([0; 8]) };
2788}
2789
2790/// Current value of [`EDGE32_HITS`].
2791pub(crate) fn edge32_hits() -> [usize; 8] {
2792 EDGE32_HITS.with(|c| c.get())
2793}
2794
2795/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
2796/// reads are `if`-conditions, so the counter has to ride the expression.
2797fn bump_edge32_bit(base: usize, bit: usize) -> usize {
2798 bump_edge32(base + bit.min(1));
2799 bit
2800}
2801
2802fn bump_edge32(slot: usize) {
2803 EDGE32_HITS.with(|c| {
2804 let mut h = c.get();
2805 h[slot] += 1;
2806 c.set(h)
2807 });
2808}
2809
2810// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
2811// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
2812// strip) fired. Real aomenc picks these at 64 even with
2813// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
2814// the counter the gate hard-asserts.
2815thread_local! {
2816 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
2817 const { std::cell::Cell::new([0; 4]) };
2818}
2819
2820/// Current value of [`SB_AB_HITS`], summed over the four arms.
2821pub(crate) fn sb_ab_hits() -> usize {
2822 SB_AB_HITS.with(|c| c.get().iter().sum())
2823}
2824
2825/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
2826/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
2827/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
2828/// proof of all four.
2829pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
2830 SB_AB_HITS.with(std::cell::Cell::get)
2831}
2832
2833// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
2834// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
2835// strips). Two counters, not one, because a gate that only proved "some 1:4
2836// strip fired" would pass on a stream that never coded the other axis, and
2837// every scan/context table this round added comes in a transposed pair.
2838thread_local! {
2839 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2840 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2841}
2842
2843/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
2844pub(crate) fn sb_rect4_horz_hits() -> usize {
2845 SB_RECT4_HORZ_HITS.with(|c| c.get())
2846}
2847
2848/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
2849pub(crate) fn sb_rect4_vert_hits() -> usize {
2850 SB_RECT4_VERT_HITS.with(|c| c.get())
2851}
2852
2853// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
2854// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
2855// strips), the arms the ReelB mid-film extract stops at.
2856thread_local! {
2857 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2858 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2859 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
2860 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
2861 /// `PARTITION_VERT_4`.
2862 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2863 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2864 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
2865 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
2866 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2867 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2868 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2869 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2870}
2871
2872/// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
2873/// a gate that only counted strips would pass on an all-skip stream, which
2874/// exercises none of the new scan/context tables.
2875thread_local! {
2876 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2877}
2878
2879// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
2880// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
2881// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
2882// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
2883// counts the same for a 16x8/8x16 strip below 16x16.
2884thread_local! {
2885 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2886 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2887 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2888}
2889
2890/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
2891pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
2892 (
2893 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
2894 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
2895 )
2896}
2897
2898/// Current value of `SUB16_SPLIT_HITS`.
2899pub(crate) fn sub16_split_hits() -> usize {
2900 SUB16_SPLIT_HITS.with(|c| c.get())
2901}
2902
2903// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
2904// luma transform is SPLIT and which therefore leave through that fn's early
2905// return -- the arm that published no `TXFM_CONTEXT` band until this round.
2906thread_local! {
2907 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2908}
2909
2910/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
2911pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
2912 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
2913}
2914
2915/// Current value of `RECT4_COEFF_HITS`.
2916pub(crate) fn rect4_coeff_hits() -> usize {
2917 RECT4_COEFF_HITS.with(|c| c.get())
2918}
2919
2920// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
2921// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
2922// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
2923// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
2924// asserts the arms it proves separately so a run whose RD only picked one
2925// cannot pass as proof of the others.
2926thread_local! {
2927 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
2928}
2929
2930/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
2931/// inter frame).
2932pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
2933 SB_AB_INTER_HITS.with(std::cell::Cell::get)
2934}
2935
2936// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
2937// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
2938// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
2939// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
2940// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
2941// arm separately so a run whose RD only picked one cannot pass as proof of
2942// four.
2943thread_local! {
2944 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
2945}
2946
2947/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
2948/// inter frame).
2949pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
2950 AB16_INTER_HITS.with(std::cell::Cell::get)
2951}
2952
2953// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
2954// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
2955// counts the odd strips that close a 4:2:0 chroma pair
2956// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
2957// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
2958// the PREVIOUS strip's own mv/ref/filters -- libaom
2959// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
2960// through `is_sub8x8_inter` (same file, :54).
2961thread_local! {
2962 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2963 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2964 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2965 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2966}
2967
2968// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
2969// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
2970// pair's single 8x4 (4x8) chroma unit for BOTH strips.
2971thread_local! {
2972 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
2973 const { std::cell::Cell::new([0; 3]) };
2974}
2975
2976/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
2977/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
2978pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
2979 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
2980 (v[0], v[1], v[2])
2981}
2982
2983/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
2984/// strips, chroma pairs closed, chroma pairs built from two different
2985/// strips' motion vectors)`.
2986pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
2987 (
2988 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
2989 INTER16_VERT4_HITS.with(std::cell::Cell::get),
2990 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
2991 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
2992 )
2993}
2994
2995/// One 16x4 / 4x16 inter strip's chroma situation, handed to
2996/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
2997/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
2998/// that all mean "an ordinary block, chroma of its own".
2999#[derive(Clone, Copy)]
3000struct InterStripChroma {
3001 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
3002 /// read and reconstruct NO chroma at all.
3003 has_chroma: bool,
3004 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
3005 horz: bool,
3006 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
3007 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
3008 /// i.e. the origin of the 8x4 (4x8) chroma transform.
3009 pair_mi: (usize, usize),
3010 /// The previous (even) strip's single-reference MC parameters, `None`
3011 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
3012 /// and the whole chroma block is predicted from THIS strip's mv.
3013 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
3014}
3015
3016thread_local! {
3017 static INTER_STRIP_CHROMA: std::cell::Cell<Option<InterStripChroma>> =
3018 const { std::cell::Cell::new(None) };
3019 /// The single-reference MC parameters of the inter block that decoded
3020 /// last -- read by the next 1:4 strip to build its pair's chroma.
3021 static INTER_LAST_MC: std::cell::Cell<
3022 Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
3023 > = const { std::cell::Cell::new(None) };
3024}
3025
3026fn bump_ab16_inter(arm: usize) {
3027 AB16_INTER_HITS.with(|c| {
3028 let mut v = c.get();
3029 v[arm] += 1;
3030 c.set(v);
3031 });
3032}
3033
3034// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
3035// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
3036// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
3037thread_local! {
3038 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3039 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3040 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3041 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3042 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3043 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
3044 /// base mi differs from what the strip's own (odd) mi would have said --
3045 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
3046 /// key frame miss by 1. Zero here means a gate never exercised the fix.
3047 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3048 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
3049 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
3050 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3051}
3052
3053/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
3054/// that reconstructed as flat DC before lane-kf1200 r2).
3055pub fn skip_cfl_hits() -> usize {
3056 SKIP_CFL_HITS.with(|c| c.get())
3057}
3058
3059/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
3060/// from the pair's base mi than the strip's own mi would have given.
3061pub fn rect4_16_uv_pair_filt_hits() -> usize {
3062 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
3063}
3064
3065// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
3066// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
3067// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
3068// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
3069// intra-edge filter type must come from the chroma-reference position).
3070thread_local! {
3071 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3072 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3073}
3074
3075/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
3076pub fn reelc_chroma_counters() -> (usize, usize) {
3077 (
3078 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
3079 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
3080 )
3081}
3082
3083/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
3084/// strips, chroma-reference strips, strips with a coded residual, strips
3085/// whose luma transform is split)`.
3086pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
3087 (
3088 RECT4_16_HORZ_HITS.with(|c| c.get()),
3089 RECT4_16_VERT_HITS.with(|c| c.get()),
3090 RECT4_16_CHROMA_HITS.with(|c| c.get()),
3091 RECT4_16_COEFF_HITS.with(|c| c.get()),
3092 RECT4_16_SPLIT_HITS.with(|c| c.get()),
3093 )
3094}
3095
3096/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
3097pub(crate) fn rect4_32_horz_hits() -> usize {
3098 RECT4_32_HORZ_HITS.with(|c| c.get())
3099}
3100
3101/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
3102pub(crate) fn rect4_32_vert_hits() -> usize {
3103 RECT4_32_VERT_HITS.with(|c| c.get())
3104}
3105
3106/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
3107pub(crate) fn rect4_32_horz_inter_hits() -> usize {
3108 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
3109}
3110
3111/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
3112pub(crate) fn rect4_32_vert_inter_hits() -> usize {
3113 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
3114}
3115
3116/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
3117pub(crate) fn inter_sb_horz_hits() -> usize {
3118 INTER_SB_HORZ_HITS.with(|c| c.get())
3119}
3120
3121/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
3122pub(crate) fn inter_sb_vert_hits() -> usize {
3123 INTER_SB_VERT_HITS.with(|c| c.get())
3124}
3125
3126/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
3127pub(crate) fn inter_sb_horz4_hits() -> usize {
3128 INTER_SB_HORZ4_HITS.with(|c| c.get())
3129}
3130
3131/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
3132pub(crate) fn inter_sb_vert4_hits() -> usize {
3133 INTER_SB_VERT4_HITS.with(|c| c.get())
3134}
3135
3136// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
3137// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
3138// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
3139// just inert-compiled. Zero forever on a passing gate means that gate's
3140// stream never carries `delta_q_present=1` through a rect64 block.
3141thread_local! {
3142 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
3143 const { std::cell::Cell::new(0) };
3144}
3145
3146/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
3147pub(crate) fn rect64_qidx_drift_hits() -> usize {
3148 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
3149}
3150
3151// lane-partab r1: how many 32x32 quadrants decoded an AB partition
3152// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
3153// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
3154// free-partition gate's proof this round's arms actually fired.
3155thread_local! {
3156 static PARTAB_HITS: std::cell::Cell<usize> =
3157 const { std::cell::Cell::new(0) };
3158}
3159
3160/// Current value of [`PARTAB_HITS`].
3161pub(crate) fn partab_hits() -> usize {
3162 PARTAB_HITS.with(|c| c.get())
3163}
3164
3165// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
3166// one counter per arm rather than one shared total -- the gate hard-asserts
3167// each of these individually nonzero so a recipe that only ever fires
3168// HORZ_A can't silently stand in for the whole set.
3169thread_local! {
3170 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
3171 const { std::cell::Cell::new(0) };
3172 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
3173 const { std::cell::Cell::new(0) };
3174 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
3175 const { std::cell::Cell::new(0) };
3176 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
3177 const { std::cell::Cell::new(0) };
3178}
3179
3180/// Current value of [`INTRA_HORZ_A_HITS`].
3181pub(crate) fn intra_horz_a_hits() -> usize {
3182 INTRA_HORZ_A_HITS.with(|c| c.get())
3183}
3184/// Current value of [`INTRA_HORZ_B_HITS`].
3185pub(crate) fn intra_horz_b_hits() -> usize {
3186 INTRA_HORZ_B_HITS.with(|c| c.get())
3187}
3188/// Current value of [`INTRA_VERT_A_HITS`].
3189pub(crate) fn intra_vert_a_hits() -> usize {
3190 INTRA_VERT_A_HITS.with(|c| c.get())
3191}
3192/// Current value of [`INTRA_VERT_B_HITS`].
3193pub(crate) fn intra_vert_b_hits() -> usize {
3194 INTRA_VERT_B_HITS.with(|c| c.get())
3195}
3196
3197// How many [`read_inter_compound_mode`] reads actually happened
3198// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
3199// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
3200// mvstack build), not just that `comp_mode` fired. Still refused right
3201// after (no MV assignment or MC wired), so this only counts attempted
3202// reads.
3203thread_local! {
3204 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
3205 const { std::cell::Cell::new(0) };
3206}
3207
3208/// Current value of [`COMPOUND_MODE_HITS`].
3209pub(crate) fn compound_mode_hits() -> usize {
3210 COMPOUND_MODE_HITS.with(|c| c.get())
3211}
3212
3213/// How many query blocks folded in at least one temporal MV candidate
3214/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
3215/// temporal-MV gate's own firing counter (lane-av1tmvp).
3216///
3217/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
3218/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
3219/// this file (`decode_inter_block`) still passes `tpl: None` -- this
3220/// counter compiles and the projection math it counts is unit-tested
3221/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
3222/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
3223/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
3224/// against any real stream today. See the module doc on
3225/// `crate::motion_field` and this crate's ledger for the remaining wiring.
3226pub(crate) fn tmv_hits() -> usize {
3227 crate::mvstack::tmv_hits()
3228}
3229
3230/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
3231/// produced on this thread, the 10-bit inter gate's firing proof.
3232pub(crate) fn inter_pred_hits() -> usize {
3233 crate::mc::inter_pred_hits()
3234}
3235
3236/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
3237/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
3238/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
3239/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
3240/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
3241/// needs to turn a query block's own resolved `ref_frame` into
3242/// `TplArgs::cur_offset_0` (spec 7.9.3).
3243pub(crate) struct TplFrameArgs<'a> {
3244 pub field: &'a crate::motion_field::TplField,
3245 pub order_hint_bits: u32,
3246 pub order_hint: u32,
3247 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
3248 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
3249 /// frame's own `ref_frame_idx` names for each single reference.
3250 pub ref_order_hints: [u32; 7],
3251}
3252
3253/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
3254/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
3255/// decoded `grid`: every 4x4 unit an inter block covers reads the same
3256/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
3257/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
3258/// exact — every block this crate ever codes is at least 8x8, so no 8x8
3259/// cell straddles two different blocks' values.
3260pub(crate) fn build_motion_field(
3261 grid: &MiGrid,
3262 mi_cols: usize,
3263 mi_rows: usize,
3264 order_hint: u32,
3265 order_hint_bits: u32,
3266 ref_order_hints: [u32; 7],
3267) -> crate::motion_field::MotionField {
3268 let mut field =
3269 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
3270 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
3271 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
3272 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
3273 // referencing one stores only its OTHER side's mv. With
3274 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
3275 // nothing is skipped.
3276 let other_side = |rf: i8| -> bool {
3277 if order_hint_bits == 0 {
3278 return false;
3279 }
3280 let oh = ref_order_hints[(rf - LAST_FRAME) as usize];
3281 crate::motion_field::get_relative_dist(order_hint_bits, oh, order_hint) > 0
3282 || oh == order_hint
3283 };
3284 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
3285 // capped at 12 bits per component; a longer one is not stored at all.
3286 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
3287 for row in 0..mi_rows {
3288 for col in 0..mi_cols {
3289 let Some(info) = grid.get_frame(row, col) else {
3290 continue;
3291 };
3292 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
3293 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
3294 // so an intra block -- or an inter block whose every slot is on the
3295 // other side / over the limit -- wipes what an earlier block wrote
3296 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
3297 // share a cell).
3298 if !info.is_inter {
3299 field.set(row, col, None);
3300 continue;
3301 }
3302 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
3303 // qualifying one wins -- a compound block stores its second
3304 // reference's mv, never its first (unless the second is on the
3305 // other side or over the limit). Storing slot 0 unconditionally
3306 // put the wrong (mv, ref_frame_offset) pair in every compound
3307 // block's cell, which a later frame's temporal candidate then
3308 // projected with the wrong reference distance.
3309 let mut saved: Option<crate::motion_field::SavedMv> = None;
3310 for (rf, mv) in [
3311 (info.ref_frame, Some(info.mv)),
3312 (info.ref_frame1.unwrap_or(0), info.mv1),
3313 ] {
3314 let (Some(mv), true) = (mv, rf > 0) else {
3315 continue;
3316 };
3317 if other_side(rf) {
3318 continue;
3319 }
3320 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
3321 continue;
3322 }
3323 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
3324 }
3325 field.set(row, col, saved);
3326 }
3327 }
3328 if crate::envflags::env_flag!("EC_TRACE_TPL") {
3329 eprintln!("EC_TPL_SAVED oh={order_hint}");
3330 for (r, row) in field.occupancy().iter().enumerate() {
3331 eprintln!("EC_TPL_SAVED r{r} {row}");
3332 }
3333 }
3334 field
3335}
3336
3337/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
3338/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
3339pub(crate) fn ref_hits(ref_frame: i8) -> usize {
3340 let c = match ref_frame {
3341 LAST2_FRAME => &LAST2_HITS,
3342 LAST3_FRAME => &LAST3_HITS,
3343 GOLDEN_FRAME => &GOLDEN_HITS,
3344 BWDREF_FRAME => &BWDREF_HITS,
3345 ALTREF2_FRAME => &ALTREF2_HITS,
3346 ALTREF_FRAME => &ALTREF_HITS,
3347 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
3348 };
3349 c.with(|v| v.get())
3350}
3351
3352thread_local! {
3353 /// The sequence header's `enable_intra_edge_filter`, set once per
3354 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
3355 /// own read of it, kept off the call stack (see that function's own doc
3356 /// comment for why) rather than threaded through every `read_plane`/
3357 /// `decode_block`/`decode_leaf8` call between here and there.
3358 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3359}
3360
3361/// Set [`ENABLE_EDGE_FILTER`] for this thread.
3362///
3363/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
3364/// never did -- so an inter frame's intra blocks read whatever value the last
3365/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
3366/// harmless (its own key frame sets it first), but a caller that decodes an
3367/// inter frame directly, or a test harness running several streams on one
3368/// thread, inherits a foreign sequence's bit: decode stops being a pure
3369/// function of the bitstream. `decode_stream` now calls this once per stream
3370/// from the sequence header, which covers every frame including inter ones.
3371pub(crate) fn set_enable_edge_filter(value: bool) {
3372 ENABLE_EDGE_FILTER.with(|f| f.set(value));
3373}
3374
3375/// Current value of [`ANGLE_DELTA_HITS`].
3376pub(crate) fn angle_delta_hits() -> usize {
3377 ANGLE_DELTA_HITS.with(|c| c.get())
3378}
3379
3380/// Current value of [`TX_CLASS1_HITS`].
3381pub(crate) fn tx_class1_hits() -> usize {
3382 TX_CLASS1_HITS.with(|c| c.get())
3383}
3384
3385// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
3386// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
3387// bottom) this thread's decode actually reconstructed -- the same
3388// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
3389// genuinely exercised the sub-8x8 leaf path rather than every attempt
3390// coincidentally landing on `PARTITION_NONE`.
3391thread_local! {
3392 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3393 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
3394 /// sub-blocks (lane-intersub8).
3395 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3396 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
3397 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
3398 /// `[1] = VERT` (two BLOCK_4X8).
3399 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
3400 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
3401 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
3402 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
3403 /// MIXED groups whose chroma reference is INTER while its sibling is
3404 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
3405 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
3406 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
3407 /// so only this cell separates the split arm from the HORZ/VERT one).
3408 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
3409}
3410
3411/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
3412/// mixed groups, split 4x4 leaves)`.
3413pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
3414 SUB8_INTRA_RECT_HITS.with(|c| {
3415 let h = c.get();
3416 (h[0], h[1], h[2], h[3], h[4])
3417 })
3418}
3419
3420/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
3421pub fn sub8_inter_rect_hits() -> (usize, usize) {
3422 SUB8_INTER_RECT_HITS.with(|c| {
3423 let h = c.get();
3424 (h[0], h[1])
3425 })
3426}
3427
3428// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
3429// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
3430// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
3431// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
3432// (b) was 0 for every stream before this round -- the leaf path never touched
3433// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
3434// filtered where libaom skips it. A gate asserts both are non-zero.
3435thread_local! {
3436 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3437 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3438 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
3439 // crosses the cropped frame edge -- the only units for which "clamp at
3440 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
3441 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
3442 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
3443 // whose width or height is not a multiple of 8 is the only shape that
3444 // produces one; the straddling-band gate arms assert it grew.
3445 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3446 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
3447 // (see `Neighbours::skip_written`).
3448 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3449 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
3450 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
3451 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
3452 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
3453 // 8-tall strip pair where only one half is skip must still be FILTERED.
3454 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3455 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3456}
3457
3458/// Current value of `RECT_SKIP_BAND_HITS`.
3459pub fn rect_skip_band_hits() -> usize {
3460 RECT_SKIP_BAND_HITS.with(|c| c.get())
3461}
3462
3463/// Current value of `CDEF_MIXED_SKIP_UNITS`.
3464pub fn cdef_mixed_skip_units() -> usize {
3465 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
3466}
3467
3468/// Current value of `CDEF_SKIPPED_UNITS`.
3469pub(crate) fn cdef_skipped_units() -> usize {
3470 CDEF_SKIPPED_UNITS.with(|c| c.get())
3471}
3472
3473/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
3474/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
3475pub fn cdef_unwritten_skip_units() -> usize {
3476 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
3477}
3478
3479/// Current value of `INTER8_SKIP_BAND_HITS`.
3480pub(crate) fn inter8_skip_band_hits() -> usize {
3481 INTER8_SKIP_BAND_HITS.with(|c| c.get())
3482}
3483
3484/// Current value of `CDEF_STRADDLE_UNITS`.
3485pub(crate) fn cdef_straddle_units() -> usize {
3486 CDEF_STRADDLE_UNITS.with(|c| c.get())
3487}
3488
3489/// Current value of [`SUB8_SPLIT_HITS`].
3490pub(crate) fn sub8_split_hits() -> usize {
3491 SUB8_SPLIT_HITS.with(|c| c.get())
3492}
3493
3494/// Current value of [`SUB8_INTER_SPLIT_HITS`].
3495pub fn sub8_inter_split_hits() -> usize {
3496 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
3497}
3498
3499// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
3500// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
3501// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
3502// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
3503// first sub-block's type is never the one). Reading it off sub-block 0
3504// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
3505// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
3506// see this rule through this counter.
3507thread_local! {
3508 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3509}
3510
3511/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
3512pub fn sub8_chroma_tx_from_ref_hits() -> usize {
3513 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
3514}
3515
3516fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
3517 if coeffs && first_sub != chroma_ref {
3518 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.set(c.get() + 1));
3519 }
3520}
3521
3522// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
3523// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
3524// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
3525// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
3526// asserts on these two rather than a plain leaf count.
3527thread_local! {
3528 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3529 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3530 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
3531 /// two 4x4 transform units, predicted one after the other. A separate
3532 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
3533 /// the gate can prove THIS path fired.
3534 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3535 /// 16x8/8x16 intra strips whose prediction actually read past the block's
3536 /// own width (above-right) or height (below-left) -- the samples
3537 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
3538 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
3539 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3540 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
3541 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
3542 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3543}
3544
3545/// Current value of [`RECT8_SPLIT_TX_HITS`].
3546pub(crate) fn rect8_split_tx_hits() -> usize {
3547 RECT8_SPLIT_TX_HITS.with(|c| c.get())
3548}
3549
3550/// Current value of [`RECT_STRIP_PRED_HITS`].
3551pub(crate) fn rect_strip_pred_hits() -> usize {
3552 RECT_STRIP_PRED_HITS.with(|c| c.get())
3553}
3554
3555/// Current value of [`RECT_STRIP_REACH_HITS`].
3556pub(crate) fn rect_strip_reach_hits() -> usize {
3557 RECT_STRIP_REACH_HITS.with(|c| c.get())
3558}
3559
3560/// Current value of [`TX4X8_CODED_HITS`].
3561pub(crate) fn tx4x8_coded_hits() -> usize {
3562 TX4X8_CODED_HITS.with(|c| c.get())
3563}
3564
3565/// Current value of [`TX8X4_CODED_HITS`].
3566pub(crate) fn tx8x4_coded_hits() -> usize {
3567 TX8X4_CODED_HITS.with(|c| c.get())
3568}
3569
3570// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
3571// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
3572// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
3573// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
3574// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
3575// (`eob_pt_{16,64,128,256}_chroma_class1`).
3576thread_local! {
3577 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
3578 const { std::cell::Cell::new(0) };
3579}
3580
3581/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
3582pub(crate) fn chroma_eob_class1_hits() -> usize {
3583 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
3584}
3585
3586/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
3587/// `tx_type` put this block's `eob_pt` on the class-1 row.
3588fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
3589 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
3590 CHROMA_EOB_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3591 }
3592}
3593
3594const SUB_MI: u32 = 4;
3595const MI: usize = 4;
3596const SB: usize = 64;
3597/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
3598/// (tile start, superblock-row start).
3599///
3600/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
3601/// `av1_get_partition_plane_context` reads its own zero-initialised
3602/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
3603/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
3604/// (64), which reads identically at every level up to 64x64 but sets the bit
3605/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
3606/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
3607/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
3608const NO_NEIGHBOUR_SIDE: usize = 128;
3609const BLOCK: usize = 32;
3610const SUB: usize = 16;
3611const TX32: usize = 32;
3612const TX16: usize = 16;
3613const TX8: usize = 8;
3614const TX4: usize = 4;
3615const DC_PRED: usize = 0;
3616/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
3617/// carries an angle delta — [`crate::tile`]'s own private copy of the same
3618/// constant.
3619const V_PRED: usize = 1;
3620const H_PRED: usize = 2;
3621/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
3622/// `Fimode_To_Intradir`, libaom `blockd.h`).
3623const D157_PRED: usize = 6;
3624/// The last directional mode, `D67_PRED`.
3625const D67_PRED: usize = 8;
3626/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
3627/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
3628/// codes anything else, so this decoder never reads anything else either.
3629const ANGLE_DELTA_ZERO: usize = 3;
3630const NUM_BASE_LEVELS: i32 = 2;
3631const COEFF_BASE_RANGE: i32 = 12;
3632const BR_STEP: i32 = 3;
3633const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
3634
3635/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
3636/// whose probability mass a superblock or block half outside the frame
3637/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
3638/// duplicated here (that module is another lane's territory this round) and
3639/// kept in step with it by the byte-exact round-trip tests below rather than
3640/// by sharing code.
3641const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
3642const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
3643
3644fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
3645 if crate::envflags::env_flag!("EC_AV1_TRACE") {
3646 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
3647 }
3648}
3649
3650fn element_prob(cdf: &[u16], element: usize) -> u16 {
3651 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
3652}
3653
3654/// The two-symbol CDF a partial superblock/block's forced-split flag is read
3655/// with: the mass of `elements` becomes the probability of the one partition
3656/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
3657/// (the encoder's non-adapting counterpart to this read).
3658fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
3659 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
3660 [32768 - split, 32768, 0]
3661}
3662
3663fn unsupported(what: impl Into<String>) -> Error {
3664 Error::unsupported("AV1 tile", what.into())
3665}
3666
3667/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
3668/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
3669/// same rule.
3670pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
3671 match base_q_idx {
3672 0..=20 => 0,
3673 21..=60 => 1,
3674 61..=120 => 2,
3675 _ => 3,
3676 }
3677}
3678
3679/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
3680/// [`crate::tile`]'s writer generates its scan tables with.
3681fn default_scan(side: usize) -> Vec<u16> {
3682 let mut scan = Vec::with_capacity(side * side);
3683 for d in 0..(2 * side - 1) {
3684 let lo = d.saturating_sub(side - 1);
3685 let hi = d.min(side - 1);
3686 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
3687 if d % 2 == 0 {
3688 scan.extend(diagonal.rev());
3689 } else {
3690 scan.extend(diagonal);
3691 }
3692 }
3693 scan
3694}
3695
3696/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
3697/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
3698/// in, instead of the default zigzag. libaom's own tables are keyed by a
3699/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
3700/// physically column-major level buffer, but they decompose to the exact
3701/// same (row, col) walk as a flat row-major traversal of *our* row-major
3702/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
3703/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
3704/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
3705/// transposed (column 0 down every row, then column 1, ...).
3706fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
3707 class_scan_table_wh(side, side, class)
3708}
3709
3710/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
3711/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
3712/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
3713/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
3714/// transcribed with -- `mrow` is the plain row-major raster in our indexing
3715/// and `mcol` its transpose, at rect sizes exactly as at square ones.
3716fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
3717 match class {
3718 TxClass::Vert => (0..(w * h) as u16).collect(),
3719 TxClass::Horiz => (0..w)
3720 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
3721 .collect(),
3722 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
3723 }
3724}
3725
3726fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
3727 match scan_idx {
3728 0 => 0,
3729 i if i <= area / 8 => 1,
3730 i if i <= area / 4 => 2,
3731 _ => 3,
3732 }
3733}
3734
3735fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
3736 if row >= side || col >= side {
3737 0
3738 } else {
3739 grid[row * side + col]
3740 }
3741}
3742
3743/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
3744/// `txb_common.h`): everything but the two lone-axis-identity types this
3745/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
3746#[derive(Clone, Copy, PartialEq, Eq)]
3747enum TxClass {
3748 TwoD,
3749 Horiz,
3750 Vert,
3751}
3752
3753impl TxClass {
3754 fn of(tx_type: TxType) -> Self {
3755 match tx_type {
3756 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
3757 // key on axis alone -- FLIPADST is still ADST for this purpose.
3758 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
3759 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
3760 _ => Self::TwoD,
3761 }
3762 }
3763}
3764
3765/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
3766/// table (indexed by the position along the transform's *coded* axis --
3767/// `col` for horiz, `row` for vert) that places their contexts past the 2D
3768/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
3769/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
3770fn nz_map_ctx_offset_1d(i: usize) -> usize {
3771 match i {
3772 0 => 26,
3773 1 => 31,
3774 _ => 36,
3775 }
3776}
3777
3778fn base_ctx(
3779 grid: &[i32],
3780 side: usize,
3781 row: usize,
3782 col: usize,
3783 class: TxClass,
3784 rect_shape: Option<(usize, usize)>,
3785) -> usize {
3786 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
3787 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
3788 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
3789 // position through the full 1D neighbour sum and offset table. Skipping
3790 // that for every class desynced the last (DC) coefficient of a
3791 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
3792 // 0, which then read one extra `BR` symbol at the max and forced a
3793 // spurious third Golomb call).
3794 if class == TxClass::TwoD && row == 0 && col == 0 {
3795 return 0;
3796 }
3797 let offsets: [(usize, usize); 5] = match class {
3798 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
3799 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
3800 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
3801 };
3802 let mag: i32 = offsets
3803 .iter()
3804 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
3805 .sum();
3806 let ctx = ((mag + 1) >> 1).min(4) as usize;
3807 match class {
3808 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
3809 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
3810 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
3811 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
3812 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
3813 // strip, which own a genuinely different table from the square one
3814 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
3815 // square table vs the real ctx 13 the rect table gives).
3816 TxClass::TwoD => {
3817 // lane-rectsplit r4: apply libaom's GENERATING RULE
3818 // (`txb_common.h:199-209`) directly instead of indexing the
3819 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
3820 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
3821 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
3822 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
3823 // so 32 consecutive entries are one COLUMN: the [`cdf`]
3824 // transcriptions are `[col][row]` and this read had them as
3825 // `[row][col]` -- the transpose, i.e. the other shape's rule with
3826 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
3827 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
3828 // pins the rule against the tables over their whole 5x5 domain.
3829 if let Some((w, h)) = rect_shape {
3830 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
3831 eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}");
3832 }
3833 if w < h && row < 2 {
3834 return ctx + 11;
3835 }
3836 if w > h && col < 2 {
3837 return ctx + 16;
3838 }
3839 }
3840 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
3841 }
3842 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
3843 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
3844 }
3845}
3846
3847fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
3848 let extra = match class {
3849 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
3850 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
3851 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
3852 };
3853 let mag = neighbour(grid, side, row + 1, col).abs()
3854 + neighbour(grid, side, row, col + 1).abs()
3855 + extra;
3856 let mag = (((mag + 1) >> 1).min(6)) as usize;
3857 if row == 0 && col == 0 {
3858 return mag;
3859 }
3860 let near_origin = match class {
3861 TxClass::TwoD => row < 2 && col < 2,
3862 TxClass::Horiz => col == 0,
3863 TxClass::Vert => row == 0,
3864 };
3865 if near_origin { mag + 7 } else { mag + 14 }
3866}
3867
3868/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
3869/// transposed from libaom's column-major buffer into this decoder's row-major
3870/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
3871/// against the real table). Not the square zigzag formula generalized to
3872/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
3873const SCAN_32X16: [u16; 512] = [
3874 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
3875 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
3876 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
3877 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
3878 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
3879 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
3880 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
3881 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
3882 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
3883 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
3884 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
3885 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
3886 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
3887 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
3888 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
3889 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
3890 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
3891 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
3892 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
3893 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
3894 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
3895 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
3896 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
3897 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
3898 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
3899 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
3900 509, 478, 447, 510, 479, 511,
3901];
3902
3903/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
3904/// [`SCAN_32X16`]'s doc comment).
3905const SCAN_16X32: [u16; 512] = [
3906 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,
3907 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
3908 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
3909 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
3910 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
3911 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
3912 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
3913 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
3914 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
3915 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
3916 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
3917 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
3918 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
3919 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
3920 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
3921 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
3922 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
3923 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
3924 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
3925 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
3926 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
3927 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
3928 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
3929 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
3930 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
3931 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
3932];
3933
3934/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
3935/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
3936/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
3937/// the same source).
3938const SCAN_4X8: [u16; 32] = [
3939 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,
3940 23, 26, 29, 27, 30, 31,
3941];
3942
3943/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
3944const SCAN_8X4: [u16; 32] = [
3945 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,
3946 29, 22, 15, 30, 23, 31,
3947];
3948
3949/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
3950/// [`SCAN_32X16`]'s doc comment).
3951const SCAN_16X8: [u16; 128] = [
3952 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,
3953 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
3954 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
3955 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
3956 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
3957 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
3958];
3959
3960/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
3961/// [`SCAN_32X16`]'s doc comment).
3962const SCAN_8X16: [u16; 128] = [
3963 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,
3964 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
3965 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
3966 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
3967 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
3968 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
3969];
3970
3971/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
3972/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
3973/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
3974/// scans column-major (`p = col * height + row`), so a naive copy of
3975/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
3976/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
3977/// are byte-identical to this decoder's [`SCAN_8X16`].
3978const SCAN_32X8: [u16; 256] = [
3979 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
3980 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
3981 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
3982 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
3983 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
3984 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
3985 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
3986 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
3987 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
3988 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
3989 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
3990 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
3991 222, 191, 254, 223, 255,
3992];
3993/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
3994/// 16x64 `PARTITION_VERT_4` strip).
3995const SCAN_8X32: [u16; 256] = [
3996 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,
3997 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
3998 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
3999 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
4000 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
4001 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
4002 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
4003 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
4004 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
4005 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
4006 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
4007 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
4008 239, 246, 253, 247, 254, 255,
4009];
4010/// `Default_Scan_16x4`, this decoder's own row-major transcription of
4011/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
4012/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
4013/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
4014/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
4015/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
4016/// were emitted -- a naive copy installs the transpose (class
4017/// reference-layout-not-spec).
4018const SCAN_16X4: [u16; 64] = [
4019 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,
4020 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
4021 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
4022];
4023/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
4024/// 8x32 `PARTITION_VERT_4` strip).
4025const SCAN_4X16: [u16; 64] = [
4026 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,
4027 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
4028 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
4029];
4030
4031/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
4032/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
4033/// asymmetric-extent pattern).
4034fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
4035 if row >= h || col >= w {
4036 0
4037 } else {
4038 grid[row * w + col]
4039 }
4040}
4041
4042/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
4043/// the rect generalization is libaom's own comment in
4044/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
4045/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
4046/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
4047/// [`decode_block_rect`] codes (see that function's own doc comment).
4048fn base_ctx_rect(
4049 grid: &[i32],
4050 w: usize,
4051 h: usize,
4052 row: usize,
4053 col: usize,
4054 class: TxClass,
4055) -> usize {
4056 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
4057 // the 2D class short-circuits the DC position.
4058 if class == TxClass::TwoD && row == 0 && col == 0 {
4059 return 0;
4060 }
4061 let offsets: [(usize, usize); 5] = match class {
4062 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
4063 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
4064 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
4065 };
4066 let mag: i32 = offsets
4067 .iter()
4068 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
4069 .sum();
4070 let ctx = ((mag + 1) >> 1).min(4) as usize;
4071 match class {
4072 TxClass::TwoD => {
4073 if w < h && row < 2 {
4074 return ctx + 11;
4075 }
4076 if w > h && col < 2 {
4077 return ctx + 16;
4078 }
4079 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
4080 }
4081 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
4082 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
4083 // position along one axis only).
4084 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
4085 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
4086 }
4087}
4088
4089/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
4090/// neighbour-offset math itself is shape-independent, only the boundary
4091/// clamp needs the real bound in each axis.
4092fn br_ctx_rect(
4093 grid: &[i32],
4094 w: usize,
4095 h: usize,
4096 row: usize,
4097 col: usize,
4098 class: TxClass,
4099) -> usize {
4100 let extra = match class {
4101 TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(),
4102 TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(),
4103 TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(),
4104 };
4105 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
4106 + neighbour_rect(grid, w, h, row, col + 1).abs()
4107 + extra;
4108 let mag = (((mag + 1) >> 1).min(6)) as usize;
4109 if row == 0 && col == 0 {
4110 return mag;
4111 }
4112 let near_origin = match class {
4113 TxClass::TwoD => row < 2 && col < 2,
4114 TxClass::Horiz => col == 0,
4115 TxClass::Vert => row == 0,
4116 };
4117 if near_origin { mag + 7 } else { mag + 14 }
4118}
4119
4120fn dc_vote(dc: Option<bool>) -> i32 {
4121 match dc {
4122 None => 0,
4123 Some(true) => -1,
4124 Some(false) => 1,
4125 }
4126}
4127
4128fn dc_sign_ctx(vote: i32) -> usize {
4129 match vote.signum() {
4130 0 => 0,
4131 -1 => 1,
4132 _ => 2,
4133 }
4134}
4135
4136/// The remainder of a level the base and base-range syntax could not reach
4137/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
4138/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
4139fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
4140 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
4141 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
4142 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
4143 // for every tail any encoder writes -- our own writer tops out at 19 zeros
4144 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
4145 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
4146 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
4147 // RED: seed 67 stops here today, and with the cap raised it decodes to a
4148 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
4149 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
4150 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
4151 // together with that defect's fix, not before.
4152 let mut length = 1u32;
4153 while dec.literal(1) == 0 {
4154 length += 1;
4155 if length > 20 {
4156 return Err(unsupported("a Golomb tail longer than this decoder reads"));
4157 }
4158 }
4159 let mut x = 1u32;
4160 for _ in 1..length {
4161 x = (x << 1) | dec.literal(1);
4162 }
4163 Ok(x - 1)
4164}
4165
4166/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
4167/// [`crate::tile`]'s `write_eob`.
4168fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
4169 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
4170 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
4171
4172 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
4173 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
4174 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
4175 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
4176 // `eob_multi_ctx`). Missing that split desynced the very first
4177 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
4178 // against a real aomdec trace).
4179 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
4180 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
4181 (_, Some(class1)) => class1,
4182 };
4183 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
4184 let (range, value) = dec.debug_state();
4185 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
4186 }
4187 let group = dec.symbol(eob_pt) + 1;
4188 if trace {
4189 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
4190 }
4191 let bits = OFFSET_BITS[group];
4192 let mut offset = 0u32;
4193 if bits > 0 {
4194 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
4195 if trace {
4196 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
4197 }
4198 offset = top << (bits - 1);
4199 if bits > 1 {
4200 offset |= dec.literal(bits - 1);
4201 }
4202 }
4203 GROUP_START[group] + offset as usize
4204}
4205
4206/// One transform block's levels, the inverse of [`crate::tile`]'s
4207/// `write_coeffs`, returned as a `side * side` grid in raster order, along
4208/// with the transform type that grid was coded under (`DCT_DCT` when the
4209/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
4210/// 64-point transforms, which never code anything else).
4211///
4212/// # Errors
4213/// Returns an error if the `tx_type` symbol decodes to a value outside its
4214/// CDF's own set (a corrupt or unsupported bitstream) — every value the
4215/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
4216/// produce dispatches to a real inverse transform.
4217/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
4218/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
4219/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
4220/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
4221/// the plane's own predicted mode instead. Every entry this table can
4222/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
4223/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
4224/// table ever names), so unlike the CDF-coded luma path there is no
4225/// ext-tx-set membership check to fall back from here.
4226fn default_intra_tx_type(mode: u8) -> TxType {
4227 use crate::intra::{
4228 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
4229 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
4230 };
4231 match mode {
4232 DC_PRED | D45_PRED => TxType::DctDct,
4233 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
4234 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
4235 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
4236 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
4237 }
4238}
4239
4240/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
4241/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
4242/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
4243fn is_smooth_mode(mode: usize) -> bool {
4244 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
4245}
4246
4247fn read_coeffs(
4248 dec: &mut SymbolDecoder,
4249 coding: &mut TxbTables,
4250 scan: &[u16],
4251 skip_ctx: usize,
4252 sign_ctx: usize,
4253 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
4254 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
4255 // nothing at all; `DctDct` for every luma call and every chroma call at
4256 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
4257 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
4258 default_tx_type: TxType,
4259 // `Some((w, h))` with `w != h` when this read is a superblock-level
4260 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
4261 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
4262 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
4263 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
4264 // caller's block genuinely is `side` x `side`.
4265 rect_shape: Option<(usize, usize)>,
4266) -> Result<(Vec<i32>, TxType)> {
4267 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
4268 let side = coding.side;
4269 let mut grid = vec![0i32; side * side];
4270 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
4271 let (range, value) = dec.debug_state();
4272 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
4273 }
4274 let dbg_txbskip = if coeff_trace_on() {
4275 coding.txb_skip[skip_ctx]
4276 } else {
4277 [0; 3]
4278 };
4279 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
4280 if coeff_trace_on() {
4281 let (rng, _) = dec.debug_state();
4282 eprintln!(
4283 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
4284 coding.side,
4285 all_zero as i32
4286 );
4287 }
4288 if crate::envflags::env_flag!("EC_AV1_TELL") {
4289 eprintln!(
4290 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
4291 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
4292 );
4293 }
4294 if trace {
4295 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
4296 }
4297 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
4298 let (range, value) = dec.debug_state();
4299 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
4300 }
4301 if all_zero {
4302 return Ok((grid, TxType::DctDct));
4303 }
4304 let mut tx_type = default_tx_type;
4305 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
4306 // The CDF row's own width names its set (lane-cdffwd2: extended
4307 // past the original two-way intra split once wider `reduced_tx_set
4308 // == 0` inter sets joined the table): 17 slots (16 symbols) is
4309 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
4310 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
4311 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
4312 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
4313 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
4314 let len = tx_type_cdf.len();
4315 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
4316 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
4317 }
4318 let t = dec.symbol(tx_type_cdf);
4319 if coeff_trace_on() {
4320 let (rng, _) = dec.debug_state();
4321 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
4322 }
4323 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
4324 let (range, value) = dec.debug_state();
4325 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
4326 }
4327 if trace {
4328 eprintln!("TRACE tx_type value={t} len={len}");
4329 }
4330 tx_type = match len {
4331 17 => TxType::from_symbol_all16(t),
4332 13 => TxType::from_symbol_set2_12(t),
4333 8 => TxType::from_symbol_set1(t),
4334 _ => TxType::from_symbol(t),
4335 }
4336 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
4337 }
4338
4339 let class = TxClass::of(tx_type);
4340 if class != TxClass::TwoD {
4341 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
4342 RECT_CLASS1_HITS.with(|c| c.set(c.get() + 1));
4343 }
4344 let eob = read_eob(dec, coding, class);
4345 if trace {
4346 eprintln!("TRACE eob value={eob}");
4347 }
4348 let ec_trace_coeff = coeff_trace_on();
4349 if ec_trace_coeff {
4350 let (rng, _) = dec.debug_state();
4351 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
4352 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
4353 }
4354 let class_scan;
4355 let scan: &[u16] = if class == TxClass::TwoD {
4356 scan
4357 } else {
4358 class_scan = class_scan_table(side, class);
4359 &class_scan
4360 };
4361 let mut levels = vec![0i32; side * side];
4362 for scan_idx in (0..eob).rev() {
4363 let pos = scan[scan_idx] as usize;
4364 let (row, col) = (pos / side, pos % side);
4365 let level = if scan_idx == eob - 1 {
4366 let ctx = eob_coeff_ctx(scan_idx, side * side);
4367 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
4368 if trace {
4369 eprintln!(
4370 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
4371 );
4372 }
4373 v
4374 } else {
4375 let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
4376 let v = dec.symbol(&mut coding.base[ctx]) as i32;
4377 if ec_trace_coeff {
4378 let (rng, _) = dec.debug_state();
4379 // `pos` in libaom's column-major `coeff_idx` convention, so
4380 // the ladder lines up with instrumented `aomdec`.
4381 let apos = col * side + row;
4382 eprintln!(
4383 "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"
4384 );
4385 }
4386 if trace {
4387 eprintln!(
4388 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
4389 );
4390 }
4391 v
4392 };
4393 let level = if level > NUM_BASE_LEVELS {
4394 let ctx = br_ctx(&levels, side, row, col, class);
4395 let mut level = level;
4396 let mut sent = 0;
4397 loop {
4398 let k = dec.symbol(&mut coding.br[ctx]) as i32;
4399 if ec_trace_coeff {
4400 // lane-leaf8tx r3: the `br` rung was missing from THIS
4401 // path's trace, so the cross-decoder range ladder was
4402 // blind to every base-range symbol and mis-reported the
4403 // first divergence (class [[gate-blind-to-feature]]).
4404 let (rng, _) = dec.debug_state();
4405 let apos = col * side + row;
4406 eprintln!(
4407 "EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}"
4408 );
4409 }
4410 if trace {
4411 eprintln!(
4412 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
4413 );
4414 }
4415 level += k;
4416 sent += BR_STEP;
4417 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
4418 break;
4419 }
4420 }
4421 level
4422 } else {
4423 level
4424 };
4425 if ec_trace_coeff && scan_idx == eob - 1 {
4426 let (rng, _) = dec.debug_state();
4427 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
4428 }
4429 levels[pos] = level;
4430 }
4431 if ec_trace_coeff {
4432 let (rng, _) = dec.debug_state();
4433 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
4434 }
4435
4436 for (c, &pos) in scan[..eob].iter().enumerate() {
4437 let level = levels[pos as usize];
4438 if level == 0 {
4439 continue;
4440 }
4441 let negative = if pos == 0 {
4442 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
4443 if trace {
4444 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
4445 }
4446 v
4447 } else {
4448 dec.literal(1) == 1
4449 };
4450 if ec_trace_coeff {
4451 let (rng, _) = dec.debug_state();
4452 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
4453 }
4454 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
4455 let g = read_golomb(dec)?;
4456 if trace {
4457 eprintln!("TRACE golomb pos={pos} value={g}");
4458 }
4459 level + g as i32
4460 } else {
4461 level
4462 };
4463 if ec_trace_coeff {
4464 let (rng, _) = dec.debug_state();
4465 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
4466 }
4467 grid[pos as usize] = if negative { -level } else { level };
4468 }
4469 Ok((grid, tx_type))
4470}
4471
4472/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
4473/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
4474/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
4475/// can ever produce, since every `tx_type` this decoder's rect sets can read
4476/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
4477/// rather than guess-decode if a non-2D class ever shows up here, since
4478/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
4479/// form for those.
4480fn read_coeffs_rect(
4481 dec: &mut SymbolDecoder,
4482 coding: &mut TxbTables,
4483 scan: &[u16],
4484 w: usize,
4485 h: usize,
4486 skip_ctx: usize,
4487 sign_ctx: usize,
4488 default_tx_type: TxType,
4489) -> Result<(Vec<i32>, TxType)> {
4490 let rect_trace = coeff_trace_on();
4491 let mut grid = vec![0i32; w * h];
4492 let entry_rng = dec.debug_state().0;
4493 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
4494 if rect_trace {
4495 eprintln!(
4496 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
4497 all_zero as i32,
4498 dec.debug_state().0
4499 );
4500 }
4501 if all_zero {
4502 return Ok((grid, TxType::DctDct));
4503 }
4504 RECT_COEFF_TU_HITS.with(|c| c.set(c.get() + 1));
4505 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
4506 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
4507 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
4508 // context offsets -- both of which now have rect forms
4509 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
4510 // The rect sets that carry no symbol at all still pass `None` here.
4511 let mut tx_type = default_tx_type;
4512 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
4513 let len = tx_type_cdf.len();
4514 let t = dec.symbol(tx_type_cdf);
4515 tx_type = match len {
4516 17 => TxType::from_symbol_all16(t),
4517 13 => TxType::from_symbol_set2_12(t),
4518 8 => TxType::from_symbol_set1(t),
4519 _ => TxType::from_symbol(t),
4520 }
4521 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
4522 if rect_trace {
4523 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
4524 }
4525 }
4526 let class = TxClass::of(tx_type);
4527 if class != TxClass::TwoD {
4528 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
4529 }
4530 let eob = read_eob(dec, coding, class);
4531 if rect_trace {
4532 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
4533 }
4534 let class_scan;
4535 let scan: &[u16] = if class == TxClass::TwoD {
4536 scan
4537 } else {
4538 class_scan = class_scan_table_wh(w, h, class);
4539 &class_scan
4540 };
4541 let mut levels = vec![0i32; w * h];
4542 for scan_idx in (0..eob).rev() {
4543 let pos = scan[scan_idx] as usize;
4544 let (row, col) = (pos / w, pos % w);
4545 // libaom's column-major `coeff_idx`, for ladder comparison.
4546 let apos = col * h + row;
4547 let level = if scan_idx == eob - 1 {
4548 let ctx = eob_coeff_ctx(scan_idx, w * h);
4549 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
4550 if rect_trace {
4551 eprintln!(
4552 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
4553 dec.debug_state().0
4554 );
4555 }
4556 v
4557 } else {
4558 let ctx = base_ctx_rect(&levels, w, h, row, col, class);
4559 let v = dec.symbol(&mut coding.base[ctx]) as i32;
4560 if rect_trace {
4561 eprintln!(
4562 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
4563 dec.debug_state().0
4564 );
4565 }
4566 v
4567 };
4568 let level = if level > NUM_BASE_LEVELS {
4569 let ctx = br_ctx_rect(&levels, w, h, row, col, class);
4570 let mut level = level;
4571 let mut sent = 0;
4572 loop {
4573 let k = dec.symbol(&mut coding.br[ctx]) as i32;
4574 if rect_trace {
4575 eprintln!(
4576 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
4577 dec.debug_state().0
4578 );
4579 }
4580 level += k;
4581 sent += BR_STEP;
4582 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
4583 break;
4584 }
4585 }
4586 level
4587 } else {
4588 level
4589 };
4590 levels[pos] = level;
4591 if rect_trace {
4592 let (rng, _) = dec.debug_state();
4593 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
4594 }
4595 }
4596 if rect_trace {
4597 let (rng, _) = dec.debug_state();
4598 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
4599 }
4600 for &pos in &scan[..eob] {
4601 let level = levels[pos as usize];
4602 if level == 0 {
4603 continue;
4604 }
4605 let negative = if pos == 0 {
4606 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
4607 } else {
4608 dec.literal(1) == 1
4609 };
4610 if rect_trace {
4611 let (rng, _) = dec.debug_state();
4612 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative));
4613 }
4614 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
4615 let g = read_golomb(dec)?;
4616 level + g as i32
4617 } else {
4618 level
4619 };
4620 grid[pos as usize] = if negative { -level } else { level };
4621 }
4622 Ok((grid, tx_type))
4623}
4624
4625/// What one coded block leaves behind for the blocks that read it as a
4626/// neighbour: whether it coded anything at all, and the sign of its DC —
4627/// [`crate::tile`]'s own private `Neighbour`.
4628#[derive(Clone, Copy, Default)]
4629struct Neighbour {
4630 /// The transform unit's cumulative coefficient level (spec `cul_level`,
4631 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
4632 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
4633 /// boolean (`level != 0`) is enough for every context this decoder read
4634 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
4635 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
4636 /// needs the actual magnitude tier of its above/left neighbours, not
4637 /// just whether they coded anything.
4638 level: u8,
4639 dc: Option<bool>,
4640}
4641
4642fn neighbour_state(grid: &[i32]) -> Neighbour {
4643 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
4644 Neighbour {
4645 level: cul.min(7) as u8,
4646 dc: (grid[0] != 0).then_some(grid[0] < 0),
4647 }
4648}
4649
4650/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
4651/// transform unit smaller than the block it sits in): `top`/`left` are the
4652/// above/left neighbours' magnitude tiers, each already clamped to 4.
4653const SKIP_CONTEXTS: [[usize; 5]; 5] = [
4654 [1, 2, 2, 2, 3],
4655 [2, 4, 4, 4, 5],
4656 [2, 4, 4, 4, 5],
4657 [2, 4, 4, 4, 5],
4658 [3, 5, 5, 5, 6],
4659];
4660
4661/// The neighbour state a block's contexts are read from — a duplicate of
4662/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
4663/// territory this round), kept at the same two granularities the real writer
4664/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
4665/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
4666/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
4667/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
4668/// chroma transform straddling the true, odd-sized frame edge see its
4669/// neighbour's state clamped at its own subsampled edge rather than luma's.
4670struct Neighbours {
4671 above: Vec<[Neighbour; 3]>,
4672 left: Vec<[Neighbour; 3]>,
4673 above_mode: Vec<usize>,
4674 left_mode: Vec<usize>,
4675 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
4676 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
4677 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
4678 /// luma one -- the same block can (and often does) code a different
4679 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
4680 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
4681 /// within-block neighbour finer than this grid) is luma-only -- a known,
4682 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
4683 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
4684 above_uv_mode: Vec<usize>,
4685 left_uv_mode: Vec<usize>,
4686 above_side: Vec<usize>,
4687 left_side: Vec<usize>,
4688 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
4689 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
4690 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
4691 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
4692 /// array cannot tell the second leaf's partition symbol that the first
4693 /// one was coded at 8x8.
4694 above_side_mi: Vec<usize>,
4695 left_side_mi: Vec<usize>,
4696 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
4697 /// / row, with the mi position it was written at
4698 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
4699 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
4700 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
4701 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
4702 /// leaf whose neighbour is another split group needs that group's leaf 3
4703 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
4704 /// and read only by [`decode_leaf_split4`]; the position guard makes it
4705 /// fall back to the coarse slot whenever the real neighbour was a block
4706 /// of 8x8 or larger (whose one mode is correct for every row it spans).
4707 sub8_mode_col: Vec<(usize, usize)>,
4708 sub8_mode_row: Vec<(usize, usize)>,
4709 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
4710 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
4711 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
4712 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
4713 /// the leaf above writes the same row slot the block to the left owns.
4714 uv_mode_col: Vec<(usize, usize)>,
4715 uv_mode_row: Vec<(usize, usize)>,
4716 /// Every mi cell's own `uv_mode`, the mi grid libaom's
4717 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
4718 /// blockd.h). lane-t900 r12: the one-slot-per-column
4719 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
4720 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
4721 /// overwrote the row the pair's chroma-ref half then wanted to read --
4722 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
4723 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
4724 uv_mode_grid: Vec<u8>,
4725 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
4726 /// every other band here).
4727 uv_grid_cols: usize,
4728 /// Whether the block above/left of this column/row was coded `skip` --
4729 /// an inter frame's own `skip` context (spec `SkipContext`), which the
4730 /// key-frame writer never tracks (its skip context is always zero); a
4731 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
4732 /// `left_skip`.
4733 above_skip: Vec<bool>,
4734 left_skip: Vec<bool>,
4735 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
4736 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
4737 /// pixels last written over each unit by `set_txfm_ctxs`/
4738 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
4739 /// symbol reads its context from (lane-txselect, spec 5.11.17).
4740 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
4741 /// array is exactly libaom's per-superblock-row reset, since each mi row
4742 /// is only ever visited inside one superblock row.
4743 above_txfm: Vec<u8>,
4744 left_txfm: Vec<u8>,
4745 /// Whether the block above/left of this column/row coded `skip_mode`
4746 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
4747 /// lane-av1comp round 14.
4748 above_skip_mode: Vec<bool>,
4749 left_skip_mode: Vec<bool>,
4750 /// Whether the block above/left was coded inter -- the `is_inter`
4751 /// context (spec `av1_get_intra_inter_context`), a duplicate of
4752 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
4753 above_inter: Vec<bool>,
4754 left_inter: Vec<bool>,
4755 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
4756 /// alphabet) the block above/left of this column/row coded, or `-1` for
4757 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
4758 /// functions (`mvstack::ref_ctx` family) need the real reference, not
4759 /// just "was it inter" (lane-av1refs: every inter block used to be
4760 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
4761 /// enough).
4762 above_ref: Vec<i8>,
4763 left_ref: Vec<i8>,
4764 /// The block above/left's *second* reference frame when it was coded
4765 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
4766 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
4767 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
4768 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
4769 /// (no decode path here ever produces a compound block yet).
4770 above_ref1: Vec<Option<i8>>,
4771 left_ref1: Vec<Option<i8>>,
4772 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
4773 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
4774 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
4775 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
4776 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
4777 above_comp_group_idx: Vec<u8>,
4778 left_comp_group_idx: Vec<u8>,
4779 above_compound_idx: Vec<u8>,
4780 left_compound_idx: Vec<u8>,
4781 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
4782 /// `3` = "no info": an intra neighbour or the frame's own border) of the
4783 /// block above/left of this column/row -- spec
4784 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
4785 above_filter: Vec<[u8; 2]>,
4786 left_filter: Vec<[u8; 2]>,
4787 mi_cols: usize,
4788 mi_rows: usize,
4789 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
4790 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
4791 /// 7.15) never filters an 8x8 luma block whose covering coded block read
4792 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
4793 /// grain [`Self::record_mi`] already writes at), read back at 8x8
4794 /// granularity by [`apply_cdef`] since `skip` is constant across every
4795 /// mi cell one coded block covers.
4796 skip_grid: Vec<bool>,
4797 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
4798 /// [`Self::skip_grid`] at this mi cell during this frame. A fresh
4799 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
4800 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
4801 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
4802 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
4803 /// unobservable from the pixels alone. Counted by
4804 /// [`cdef_unwritten_skip_units`].
4805 skip_written: Vec<bool>,
4806 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
4807 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
4808 /// which re-enables the loop filter at a prediction boundary between two
4809 /// skipped inter blocks (lane-mergefix r4). Written by
4810 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
4811 blk_org_grid: Vec<[u16; 2]>,
4812 skip_grid_cols_mi: usize,
4813 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
4814 /// never splits a coded block's transform below its own size (round 2:
4815 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
4816 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
4817 /// edge-length lookup (`apply_deblock`).
4818 tx_grid: Vec<u8>,
4819 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
4820 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
4821 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
4822 tx_h_grid: Vec<u8>,
4823 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
4824 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
4825 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
4826 /// does NOT follow luma's `tx_depth` split, so deriving it as
4827 /// `tx_grid / 2` invented chroma transform edges the deblocker then
4828 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
4829 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
4830 /// every caller routes through.
4831 uv_tx_grid: Vec<u8>,
4832 uv_tx_h_grid: Vec<u8>,
4833 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
4834 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
4835 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
4836 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
4837 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
4838 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
4839 /// reference onto `LAST_FRAME`'s own delta).
4840 ref_grid: Vec<i8>,
4841 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
4842 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
4843 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
4844 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
4845 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
4846 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
4847 /// to know which mode produced the value.
4848 delta_lf_grid: Vec<[i8; 4]>,
4849 /// The block above/left's own palette-Y size (0 = not a palette block)
4850 /// and its base colours -- `av1_get_palette_mode_ctx`/
4851 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
4852 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
4853 above_palette_size: Vec<usize>,
4854 left_palette_size: Vec<usize>,
4855 above_palette_colors: Vec<[u16; 8]>,
4856 left_palette_colors: Vec<[u16; 8]>,
4857 /// As the four fields above, for the neighbour's own chroma (U-channel
4858 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
4859 /// palette size/colours (lane-palette2 r1).
4860 above_palette_uv_size: Vec<usize>,
4861 left_palette_uv_size: Vec<usize>,
4862 above_palette_uv_colors: Vec<[u16; 8]>,
4863 left_palette_uv_colors: Vec<[u16; 8]>,
4864 /// This tile's own top-left corner, in 4x4 mode-info units (spec
4865 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
4866 /// neighbour" check compares against this instead of literal `0`, since a
4867 /// block at the tile's own top/left edge has no usable neighbour even
4868 /// though a decoded block sits there in the picture (spec `decode_tile`'s
4869 /// per-tile `clear_above_context`/`left_available`/`up_available`).
4870 /// `0` for a single-tile frame, matching every existing caller exactly.
4871 tile_row0_mi: usize,
4872 tile_col0_mi: usize,
4873}
4874
4875impl Neighbours {
4876 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
4877 /// true (unpadded) size in 4x4 mode-info units.
4878 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
4879 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
4880 // neighbour state over the whole 64-row extent, past the frame's last
4881 // mi row (mi_rows 198, block rows 192..208). libaom's own context
4882 // buffers are superblock-aligned for exactly that reason
4883 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
4884 // side arrays to a superblock multiple and leave those cells unread --
4885 // every availability check uses the true `mi_rows`/`mi_cols` below.
4886 let sb_sub = (sb_mi_cur() as usize) / (SUB / MI);
4887 let (cols, rows) = (
4888 cols.next_multiple_of(sb_sub),
4889 rows.next_multiple_of(sb_sub),
4890 );
4891 Self {
4892 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
4893 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
4894 above_mode: vec![DC_PRED; cols],
4895 left_mode: vec![DC_PRED; rows],
4896 above_uv_mode: vec![DC_PRED; cols],
4897 left_uv_mode: vec![DC_PRED; rows],
4898 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
4899 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
4900 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
4901 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
4902 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
4903 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
4904 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
4905 uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
4906 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
4907 uv_grid_cols: cols * (SUB / MI),
4908 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
4909 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
4910 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
4911 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
4912 // 16x16 block beside it, which a SUB-grid slot cannot name
4913 // (class context-read-from-one-cell).
4914 above_skip: vec![false; cols * (SUB / MI)],
4915 left_skip: vec![false; rows * (SUB / MI)],
4916 above_skip_mode: vec![false; cols * (SUB / MI)],
4917 left_skip_mode: vec![false; rows * (SUB / MI)],
4918 above_inter: vec![false; cols * (SUB / MI)],
4919 left_inter: vec![false; rows * (SUB / MI)],
4920 above_ref: vec![-1; cols * (SUB / MI)],
4921 left_ref: vec![-1; rows * (SUB / MI)],
4922 above_ref1: vec![None; cols * (SUB / MI)],
4923 left_ref1: vec![None; rows * (SUB / MI)],
4924 above_comp_group_idx: vec![0; cols * (SUB / MI)],
4925 left_comp_group_idx: vec![0; rows * (SUB / MI)],
4926 above_compound_idx: vec![0; cols * (SUB / MI)],
4927 left_compound_idx: vec![0; rows * (SUB / MI)],
4928 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
4929 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
4930 mi_cols,
4931 mi_rows,
4932 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
4933 skip_written: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
4934 blk_org_grid: vec![[0u16; 2]; cols * (SUB / MI) * rows * (SUB / MI)],
4935 skip_grid_cols_mi: cols * (SUB / MI),
4936 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4937 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4938 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4939 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4940 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
4941 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
4942 above_palette_size: vec![0; cols * (SUB / MI)],
4943 left_palette_size: vec![0; rows * (SUB / MI)],
4944 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
4945 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
4946 above_palette_uv_size: vec![0; cols * (SUB / MI)],
4947 left_palette_uv_size: vec![0; rows * (SUB / MI)],
4948 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
4949 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
4950 tile_row0_mi: 0,
4951 tile_col0_mi: 0,
4952 }
4953 }
4954
4955 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
4956 /// tile's own column span (`col1_mi` exclusive), plus recording
4957 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
4958 /// availability check below. Left context resets every superblock row
4959 /// regardless of tile ([`Self::start_row`], already called once per SB
4960 /// row by every caller) so it needs no tile-specific reset here.
4961 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
4962 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
4963 // are tile-relative, same as every other neighbour lookup here.
4964 SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
4965 self.tile_row0_mi = row0_mi;
4966 self.tile_col0_mi = col0_mi;
4967 let end = col1_mi.min(self.above.len());
4968 for i in col0_mi.min(end)..end {
4969 self.above[i] = Default::default();
4970 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE;
4971 }
4972 let (sc0, sc1) = (
4973 col0_mi / (SUB / MI),
4974 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
4975 );
4976 for i in sc0.min(sc1)..sc1 {
4977 self.above_mode[i] = DC_PRED;
4978 self.above_side[i] = NO_NEIGHBOUR_SIDE;
4979 }
4980 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
4981 // the tile's own mi column span directly.
4982 let mend = col1_mi.min(self.above_skip.len());
4983 for i in col0_mi.min(mend)..mend {
4984 self.above_skip[i] = false;
4985 self.above_skip_mode[i] = false;
4986 self.above_inter[i] = false;
4987 self.above_ref[i] = -1;
4988 self.above_ref1[i] = None;
4989 self.above_comp_group_idx[i] = 0;
4990 self.above_compound_idx[i] = 0;
4991 self.above_filter[i] = [3u8; 2];
4992 }
4993 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
4994 // stale `(row, mode)` from the tile to the LEFT names an mi row this
4995 // tile's first block would read as its own above neighbour.
4996 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
4997 for i in col0_mi.min(mcol_end)..mcol_end {
4998 self.sub8_mode_col[i] = (usize::MAX, 0);
4999 self.uv_mode_col[i] = (usize::MAX, 0);
5000 }
5001 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
5002 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
5003 // not zero) -- without it a second tile column reads the first one's
5004 // resolved transform sizes as its own above context.
5005 let tend = col1_mi.min(self.above_txfm.len());
5006 for i in col0_mi.min(tend)..tend {
5007 self.above_txfm[i] = TXFM_CTX_INIT;
5008 }
5009 }
5010
5011 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
5012 /// for a non-palette block, clearing any stale neighbour state) into every
5013 /// [`SUB`]-grid cell it covers on both the above and left edges --
5014 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
5015 /// call sites are all square blocks).
5016 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
5017 self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors);
5018 }
5019
5020 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
5021 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
5022 /// [`Self::record`]): a true rect strip's above/left neighbour spans
5023 /// differ.
5024 fn record_palette_y_rect(
5025 &mut self,
5026 mi: (usize, usize),
5027 w: usize,
5028 h: usize,
5029 size: usize,
5030 colors: [u16; 8],
5031 ) {
5032 let (r, c) = mi;
5033 if crate::envflags::env_flag!("EC_PALPUB") {
5034 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
5035 }
5036 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
5037 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
5038 // cell immediately left of the block, not its 16px [`SUB`] cell. The
5039 // old SUB grid let a 16x8 strip pair share one slot, so the second
5040 // strip of mi(0,8) read the FIRST strip's palette size and the colour
5041 // cache came out one entry short (class [[context-read-from-one-cell]]).
5042 for cell in 0..(w / MI).max(1) {
5043 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
5044 *e = size;
5045 self.above_palette_colors[c + cell] = colors;
5046 }
5047 }
5048 for cell in 0..(h / MI).max(1) {
5049 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
5050 *e = size;
5051 self.left_palette_colors[r + cell] = colors;
5052 }
5053 }
5054 }
5055
5056 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
5057 /// neighbours that are themselves a palette-Y block, plus
5058 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
5059 /// cache (pred_common.c:73).
5060 ///
5061 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
5062 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
5063 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
5064 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
5065 /// the ctx too made every superblock in the frame's second SB row read
5066 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
5067 /// palette block decoded as "no palette" and the tile desynced from
5068 /// there (class [[cdf-row-held-constant]]).
5069 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
5070 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
5071 }
5072
5073 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
5074 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
5075 /// drops the above neighbour on a 64-px superblock boundary
5076 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
5077 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
5078 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
5079 /// every strip in an SB's top cell row, which libaom does not do.
5080 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
5081 let (r, c) = mi;
5082 let above_ok = r % 16 != 0;
5083 // `xd->above_mbmi` exists for every row but the tile's own first.
5084 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
5085 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
5086 (self.above_palette_size[c], self.above_palette_colors[c])
5087 } else {
5088 (0, [0u16; 8])
5089 };
5090 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
5091 // is NULL whenever the block sits at its TILE's own left column
5092 // (`left_available`), not the frame's -- without this guard a second
5093 // tile column reads the previous tile's palette colours into its cache
5094 // and its `palette_y_mode` ctx.
5095 let left_ok = c > self.tile_col0_mi;
5096 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
5097 (self.left_palette_size[r], self.left_palette_colors[r])
5098 } else {
5099 (0, [0u16; 8])
5100 };
5101 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
5102 let mut cache = Vec::with_capacity(16);
5103 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
5104 if cache.last() != Some(&v) {
5105 cache.push(v);
5106 }
5107 };
5108 let (mut ai, mut li) = (0usize, 0usize);
5109 while ai < above_n && li < left_n {
5110 let (va, vl) = (above_colors[ai], left_colors[li]);
5111 if vl < va {
5112 push_dedup(&mut cache, vl);
5113 li += 1;
5114 } else {
5115 push_dedup(&mut cache, va);
5116 ai += 1;
5117 if vl == va {
5118 li += 1;
5119 }
5120 }
5121 }
5122 while ai < above_n {
5123 push_dedup(&mut cache, above_colors[ai]);
5124 ai += 1;
5125 }
5126 while li < left_n {
5127 push_dedup(&mut cache, left_colors[li]);
5128 li += 1;
5129 }
5130 (ctx, cache)
5131 }
5132
5133 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
5134 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
5135 /// same way (lane-palette2 r1).
5136 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
5137 self.record_palette_uv_rect(
5138 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
5139 side,
5140 side,
5141 size,
5142 colors,
5143 );
5144 }
5145
5146 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
5147 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
5148 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
5149 /// luma resolution regardless of which plane the recorded state is for).
5150 fn record_palette_uv_rect(
5151 &mut self,
5152 mi: (usize, usize),
5153 w: usize,
5154 h: usize,
5155 size: usize,
5156 colors: [u16; 8],
5157 ) {
5158 let (r, c) = mi;
5159 // mi granularity, see [`Self::record_palette_y_rect`].
5160 for cell in 0..(w / MI).max(1) {
5161 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
5162 *e = size;
5163 self.above_palette_uv_colors[c + cell] = colors;
5164 }
5165 }
5166 for cell in 0..(h / MI).max(1) {
5167 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
5168 *e = size;
5169 self.left_palette_uv_colors[r + cell] = colors;
5170 }
5171 }
5172 }
5173
5174 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
5175 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
5176 /// no neighbour lookup at all (it is this block's own just-decided Y
5177 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
5178 /// so only the cache is wanted here.
5179 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
5180 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
5181 }
5182
5183 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
5184 /// [`Self::palette_ctx_and_cache_mi`].
5185 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
5186 let (r, c) = mi;
5187 let above_ok = r % 16 != 0;
5188 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
5189 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
5190 } else {
5191 (0, [0u16; 8])
5192 };
5193 // Same tile-relative left availability as the luma cache above.
5194 let left_ok = c > self.tile_col0_mi;
5195 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
5196 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
5197 } else {
5198 (0, [0u16; 8])
5199 };
5200 let mut cache = Vec::with_capacity(16);
5201 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
5202 if cache.last() != Some(&v) {
5203 cache.push(v);
5204 }
5205 };
5206 let (mut ai, mut li) = (0usize, 0usize);
5207 while ai < above_n && li < left_n {
5208 let (va, vl) = (above_colors[ai], left_colors[li]);
5209 if vl < va {
5210 push_dedup(&mut cache, vl);
5211 li += 1;
5212 } else {
5213 push_dedup(&mut cache, va);
5214 ai += 1;
5215 if vl == va {
5216 li += 1;
5217 }
5218 }
5219 }
5220 while ai < above_n {
5221 push_dedup(&mut cache, above_colors[ai]);
5222 ai += 1;
5223 }
5224 while li < left_n {
5225 push_dedup(&mut cache, left_colors[li]);
5226 li += 1;
5227 }
5228 cache
5229 }
5230
5231 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
5232 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
5233 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
5234 /// units as [`Self::fill_skip_grid`].
5235 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
5236 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
5237 }
5238
5239 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
5240 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
5241 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
5242 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
5243 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
5244 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
5245 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
5246 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
5247 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
5248 /// block's published transform extent to its own size is exactly that
5249 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
5250 /// that needs it is the 128 root, whose chroma extent (64) is the one
5251 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
5252 /// never suppressed (libaom's `is_inter_block` term), so this is called
5253 /// only from the skipped-inter branch.
5254 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
5255 let (mi_r, mi_c) = at_mi;
5256 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
5257 for rr in 0..h_mi {
5258 for cc in 0..w_mi {
5259 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5260 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
5261 *cell = uv_w;
5262 }
5263 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
5264 *cell = uv_h;
5265 }
5266 }
5267 }
5268 }
5269
5270 fn fill_lf_grid_rect(
5271 &mut self,
5272 at_mi: (usize, usize),
5273 w_mi: usize,
5274 h_mi: usize,
5275 tx_px: u8,
5276 tx_h_px: u8,
5277 ref_frame: i8,
5278 ) {
5279 let (mi_r, mi_c) = at_mi;
5280 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
5281 // half its luma one (min 4 px, the smallest transform), capped at
5282 // TX_32X32 -- independent of this block's luma `tx_depth`.
5283 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
5284 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
5285 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
5286 eprintln!("EC_LFGRID mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}");
5287 }
5288 let cur = CURRENT_DELTA_LF.with(|c| c.get());
5289 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
5290 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
5291 } else {
5292 [cur[0].clamp(-63, 63) as i8; 4]
5293 };
5294 for rr in 0..h_mi {
5295 for cc in 0..w_mi {
5296 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5297 if let Some(cell) = self.tx_grid.get_mut(idx) {
5298 *cell = tx_px;
5299 }
5300 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
5301 *cell = tx_h_px;
5302 }
5303 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
5304 *cell = uv_tx_w;
5305 }
5306 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
5307 *cell = uv_tx_h;
5308 }
5309 if let Some(cell) = self.ref_grid.get_mut(idx) {
5310 *cell = ref_frame;
5311 }
5312 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
5313 *cell = snapshot;
5314 }
5315 }
5316 }
5317 }
5318
5319 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
5320 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
5321 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
5322 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
5323 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
5324 /// dims from the LEAF span and so invented chroma transform edges the
5325 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
5326 /// are already correct from the block's own fill over the same span.
5327 fn fill_lf_grid_leaf_luma(
5328 &mut self,
5329 at_mi: (usize, usize),
5330 w_mi: usize,
5331 h_mi: usize,
5332 tx_px: u8,
5333 tx_h_px: u8,
5334 ) {
5335 let (mi_r, mi_c) = at_mi;
5336 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
5337 eprintln!("EC_LFLEAF mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}");
5338 }
5339 for rr in 0..h_mi {
5340 for cc in 0..w_mi {
5341 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5342 if let Some(cell) = self.tx_grid.get_mut(idx) {
5343 *cell = tx_px;
5344 }
5345 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
5346 *cell = tx_h_px;
5347 }
5348 }
5349 }
5350 }
5351
5352 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
5353 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
5354 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
5355 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
5356 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
5357 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
5358 }
5359
5360 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
5361 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
5362 let (mi_r, mi_c) = at_mi;
5363 if skip && w_mi != h_mi {
5364 RECT_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1));
5365 }
5366 for rr in 0..h_mi {
5367 for cc in 0..w_mi {
5368 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5369 if let Some(cell) = self.skip_grid.get_mut(idx) {
5370 *cell = skip;
5371 }
5372 if let Some(cell) = self.skip_written.get_mut(idx) {
5373 *cell = true;
5374 }
5375 if let Some(org) = self.blk_org_grid.get_mut(idx) {
5376 *org = [mi_r as u16, mi_c as u16];
5377 }
5378 }
5379 }
5380 }
5381
5382 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
5383 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
5384 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
5385 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
5386 /// straddle the region with a mix of skip/non-skip blocks).
5387 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
5388 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
5389 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
5390 /// filtered edge's two sides are each exactly one coded block wide.
5391 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
5392 self.skip_grid
5393 .get(mi_r * self.skip_grid_cols_mi + mi_c)
5394 .copied()
5395 .unwrap_or(false)
5396 }
5397
5398 /// The `skip_txfm` context of a block whose top-left mi cell is
5399 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
5400 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
5401 /// with an absent neighbour contributing 0. The mi grid is per tile, so
5402 /// row/column 0 is a tile edge and has no neighbour on that axis.
5403 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
5404 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
5405 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
5406 }
5407
5408 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
5409 (0..2).all(|rr| {
5410 (0..2).all(|cc| {
5411 self.skip_grid
5412 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
5413 .copied()
5414 .unwrap_or(false)
5415 })
5416 })
5417 }
5418
5419 fn start_row(&mut self) {
5420 self.left.iter_mut().for_each(|l| *l = Default::default());
5421 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
5422 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
5423 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
5424 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
5425 self.left_skip.iter_mut().for_each(|s| *s = false);
5426 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
5427 self.left_inter.iter_mut().for_each(|i| *i = false);
5428 self.left_ref.iter_mut().for_each(|r| *r = -1);
5429 self.left_ref1.iter_mut().for_each(|r| *r = None);
5430 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
5431 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
5432 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
5433 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
5434 // context (a tile/SB-row boundary has no left neighbour).
5435 self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
5436 self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
5437 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
5438 // are per-mi maps like every other one here, so they reset with the
5439 // row too -- the left guard above is what actually stops a cross-tile
5440 // read, this keeps a stale colour out of the arrays at all.
5441 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
5442 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
5443 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
5444 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
5445 // lane-mergefix r2: `av1_zero_left_context` memsets
5446 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
5447 // every superblock row of every tile -- the var-tx left context does
5448 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
5449 // previous tile column's last block otherwise).
5450 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
5451 }
5452
5453 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
5454 /// block that reads it as a neighbour -- [`crate::tile`]'s
5455 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
5456 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
5457 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
5458 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
5459 /// the real value, not just `is_inter`).
5460 fn record_inter(
5461 &mut self,
5462 at: (usize, usize),
5463 side: usize,
5464 skip: bool,
5465 is_inter: bool,
5466 ref_frame: i8,
5467 filter: [u8; 2],
5468 skip_mode: bool,
5469 ) {
5470 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
5471 }
5472
5473 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
5474 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
5475 /// r1: a true rectangular strip's above-context span (its own width) and
5476 /// left-context span (its own height) differ, unlike every caller before
5477 /// this round (class neighbour-votes-all-its-fields).
5478 #[allow(clippy::too_many_arguments)]
5479 fn record_inter_rect(
5480 &mut self,
5481 at: (usize, usize),
5482 w_sub: usize,
5483 h_sub: usize,
5484 skip: bool,
5485 is_inter: bool,
5486 ref_frame: i8,
5487 filter: [u8; 2],
5488 skip_mode: bool,
5489 ) {
5490 let (r, c) = at;
5491 self.record_inter_rect_mi(
5492 (r * (SUB / MI), c * (SUB / MI)),
5493 w_sub / MI,
5494 h_sub / MI,
5495 skip,
5496 is_inter,
5497 ref_frame,
5498 filter,
5499 skip_mode,
5500 );
5501 }
5502
5503 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
5504 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
5505 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
5506 /// routes through the wrapper above.
5507 #[allow(clippy::too_many_arguments)]
5508 fn record_inter_rect_mi(
5509 &mut self,
5510 at_mi: (usize, usize),
5511 w_mi: usize,
5512 h_mi: usize,
5513 skip: bool,
5514 is_inter: bool,
5515 ref_frame: i8,
5516 filter: [u8; 2],
5517 skip_mode: bool,
5518 ) {
5519 let (r, c) = at_mi;
5520 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
5521 // writes for a whole block class): an INTER block left the luma mode
5522 // map untouched, so a later intra block's `get_intra_edge_filter_type`
5523 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
5524 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
5525 // block in that pixel row -- the directional edge filter then ran at
5526 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
5527 // which for an inter block is an INTER mode (>= NEARESTMV) and is
5528 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
5529 // already stamped it).
5530 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
5531 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
5532 // uv map must read DC_PRED over an inter block's cells too.
5533 if is_inter {
5534 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
5535 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
5536 }
5537 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
5538 for cell in 0..w_mi {
5539 self.above_skip[c + cell] = skip;
5540 self.above_skip_mode[c + cell] = skip_mode;
5541 self.above_inter[c + cell] = is_inter;
5542 self.above_ref[c + cell] = ref_frame;
5543 // lane-av1comp: no caller of `record_inter` ever decodes a
5544 // compound block yet (see [`Self::above_ref1`]'s doc); the
5545 // parameter this becomes lands with `read_ref_frames`.
5546 self.above_ref1[c + cell] = None;
5547 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
5548 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
5549 // as `3`/`1` even though this block has no second reference.
5550 // `record_compound_ctx` overwrites this with the real bit for an
5551 // actual compound block's cells, called right after this one.
5552 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
5553 self.above_compound_idx[c + cell] = u8::from(altref);
5554 self.above_filter[c + cell] = filter;
5555 }
5556 for cell in 0..h_mi {
5557 self.left_skip[r + cell] = skip;
5558 self.left_skip_mode[r + cell] = skip_mode;
5559 self.left_inter[r + cell] = is_inter;
5560 self.left_ref[r + cell] = ref_frame;
5561 self.left_ref1[r + cell] = None;
5562 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
5563 self.left_compound_idx[r + cell] = u8::from(altref);
5564 self.left_filter[r + cell] = filter;
5565 }
5566 }
5567
5568 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
5569 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
5570 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
5571 /// `get_comp_index_context`) -- called right after `record_inter` for
5572 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
5573 /// stamps `above_ref1`/`left_ref1` with the block's real second
5574 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
5575 /// this is the one caller that actually knows it) -- so the next block's
5576 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
5577 /// neighbour instead of `record_inter`'s single-ref default.
5578 fn record_compound_ctx(
5579 &mut self,
5580 at: (usize, usize),
5581 side: usize,
5582 ref1: i8,
5583 comp_group_idx: u8,
5584 compound_idx: u8,
5585 ) {
5586 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
5587 }
5588
5589 /// [`Self::record_compound_ctx`] with independent above/left extents,
5590 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
5591 #[allow(clippy::too_many_arguments)]
5592 fn record_compound_ctx_rect(
5593 &mut self,
5594 at: (usize, usize),
5595 w_sub: usize,
5596 h_sub: usize,
5597 ref1: i8,
5598 comp_group_idx: u8,
5599 compound_idx: u8,
5600 ) {
5601 let (r, c) = at;
5602 self.record_compound_ctx_rect_mi(
5603 (r * (SUB / MI), c * (SUB / MI)),
5604 w_sub / MI,
5605 h_sub / MI,
5606 ref1,
5607 comp_group_idx,
5608 compound_idx,
5609 );
5610 }
5611
5612 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
5613 /// [`Self::record_inter_rect_mi`]).
5614 fn record_compound_ctx_rect_mi(
5615 &mut self,
5616 at_mi: (usize, usize),
5617 w_mi: usize,
5618 h_mi: usize,
5619 ref1: i8,
5620 comp_group_idx: u8,
5621 compound_idx: u8,
5622 ) {
5623 let (r, c) = at_mi;
5624 for cell in 0..w_mi {
5625 self.above_ref1[c + cell] = Some(ref1);
5626 self.above_comp_group_idx[c + cell] = comp_group_idx;
5627 self.above_compound_idx[c + cell] = compound_idx;
5628 }
5629 for cell in 0..h_mi {
5630 self.left_ref1[r + cell] = Some(ref1);
5631 self.left_comp_group_idx[r + cell] = comp_group_idx;
5632 self.left_compound_idx[r + cell] = compound_idx;
5633 }
5634 }
5635
5636 /// The context of a block's partition symbol: delegates to the mi-precise
5637 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
5638 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
5639 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
5640 /// only touches the finer mi arrays -- leaves them stale for the *next*
5641 /// sibling's own partition symbol.
5642 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
5643 let (r, c) = at;
5644 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
5645 }
5646
5647 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
5648 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
5649 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
5650 /// than the enclosing 16x16 slot's stale, shared state.
5651 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
5652 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
5653 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
5654 }
5655
5656 /// The gathered coded/DC-sign state of the blocks above and to the left
5657 /// of a block `side` samples across, per plane.
5658 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
5659 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
5660 }
5661
5662 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
5663 /// units, for the same reason [`Self::record_mi`] does.
5664 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
5665 let side_mi = side / MI;
5666 std::array::from_fn(|plane| {
5667 let mut above_coded = false;
5668 let mut left_coded = false;
5669 let mut vote = 0;
5670 for cell in 0..side_mi {
5671 let above = &self.above[mi_c + cell][plane];
5672 let left = &self.left[mi_r + cell][plane];
5673 above_coded |= above.level != 0;
5674 left_coded |= left.level != 0;
5675 vote += dc_vote(above.dc) + dc_vote(left.dc);
5676 }
5677 (above_coded, left_coded, vote)
5678 })
5679 }
5680
5681 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
5682 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
5683 /// extent pattern for a true rectangular strip's own coefficient context.
5684 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
5685 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
5686 }
5687
5688 /// [`Self::around_rect`] taking the block's position directly in 4x4
5689 /// mode-info units, mirroring [`Self::around_mi`].
5690 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
5691 let (w_mi, h_mi) = (w / MI, h / MI);
5692 std::array::from_fn(|plane| {
5693 let mut above_coded = false;
5694 let mut left_coded = false;
5695 let mut vote = 0;
5696 for cell in 0..w_mi {
5697 let above = &self.above[mi_c + cell][plane];
5698 above_coded |= above.level != 0;
5699 vote += dc_vote(above.dc);
5700 }
5701 for cell in 0..h_mi {
5702 let left = &self.left[mi_r + cell][plane];
5703 left_coded |= left.level != 0;
5704 vote += dc_vote(left.dc);
5705 }
5706 if crate::envflags::env_flag!("EC_DCDUMP") {
5707 let ab: Vec<String> = (0..w_mi)
5708 .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level))
5709 .collect();
5710 let lf: Vec<String> = (0..h_mi)
5711 .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level))
5712 .collect();
5713 eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(","));
5714 }
5715 (above_coded, left_coded, vote)
5716 })
5717 }
5718
5719 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
5720 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
5721 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
5722 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
5723 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
5724 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
5725 /// is always 0, spec's `plane_bsize == tx_size` branch).
5726 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
5727 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
5728 }
5729
5730 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
5731 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
5732 /// context over `tx_size_wide` and the left one over `tx_size_high`.
5733 fn luma_skip_ctx_rect(
5734 &self,
5735 (mi_r, mi_c): (usize, usize),
5736 w_mi: usize,
5737 h_mi: usize,
5738 ) -> usize {
5739 let side_mi = w_mi;
5740 let mut top = 0u8;
5741 let mut left = 0u8;
5742 for cell in 0..w_mi {
5743 top |= self.above[mi_c + cell][0].level;
5744 }
5745 for cell in 0..h_mi {
5746 left |= self.left[mi_r + cell][0].level;
5747 }
5748 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
5749 if crate::envflags::env_flag!("EC_ECDUMP") {
5750 let ab: Vec<String> =
5751 (0..w_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect();
5752 let lf: Vec<String> =
5753 (0..h_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect();
5754 eprintln!(
5755 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]",
5756 ab.join(","), lf.join(",")
5757 );
5758 }
5759 if crate::envflags::env_flag!("EC_AV1_TRACE") {
5760 eprintln!(
5761 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
5762 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
5763 );
5764 }
5765 ctx
5766 }
5767
5768 /// Writes one coded block into every cell it covers, on both grids: the
5769 /// mode/side arrays up to `side`'s own width, and the coefficient-context
5770 /// arrays up to the true frame edge — the units past it are left at their
5771 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
5772 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
5773 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
5774 /// not from this block's own side).
5775 fn record(
5776 &mut self,
5777 at: (usize, usize),
5778 side: usize,
5779 mode: usize,
5780 uv_mode: usize,
5781 grids: &[Vec<i32>; 3],
5782 ) {
5783 self.record_rect(at, side, side, mode, uv_mode, grids);
5784 }
5785
5786 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
5787 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
5788 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
5789 /// spec's per-edge partition-context rule, so a true rectangular block
5790 /// naturally wants two different values here rather than one.
5791 /// Writes this block's luma `mode` into the mi-granular
5792 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
5793 /// position a *later* neighbour would read it from: the block's LAST mi
5794 /// row for every column it spans (what the block below reads via
5795 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
5796 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
5797 /// read these back, and only when the recorded position is exactly their
5798 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
5799 fn record_mode_mi(
5800 &mut self,
5801 mi_r: usize,
5802 mi_c: usize,
5803 mi_w: usize,
5804 mi_h: usize,
5805 mode: usize,
5806 ) {
5807 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
5808 for cell in 0..mi_w {
5809 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
5810 *slot = (last_r, mode);
5811 }
5812 }
5813 for cell in 0..mi_h {
5814 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
5815 *slot = (last_c, mode);
5816 }
5817 }
5818 }
5819
5820 /// The mi-exact above/left neighbour luma mode for a block whose top-left
5821 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
5822 /// mi position (then the coarse [`SUB`]-grid slot is right by
5823 /// construction). See [`Self::record_mode_mi`].
5824 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
5825 match self.sub8_mode_col.get(mi_c) {
5826 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m),
5827 _ => None,
5828 }
5829 }
5830
5831 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
5832 match self.sub8_mode_row.get(mi_r) {
5833 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m),
5834 _ => None,
5835 }
5836 }
5837
5838 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
5839 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
5840 fn record_uv_mode_mi(
5841 &mut self,
5842 mi_r: usize,
5843 mi_c: usize,
5844 mi_w: usize,
5845 mi_h: usize,
5846 uv_mode: usize,
5847 ) {
5848 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
5849 for cell in 0..mi_w {
5850 if let Some(slot) = self.uv_mode_col.get_mut(mi_c + cell) {
5851 *slot = (last_r, uv_mode);
5852 }
5853 }
5854 for cell in 0..mi_h {
5855 if let Some(slot) = self.uv_mode_row.get_mut(mi_r + cell) {
5856 *slot = (last_c, uv_mode);
5857 }
5858 }
5859 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
5860 // covers, so the chroma neighbour read below is a plain grid read.
5861 let stride = self.uv_grid_cols;
5862 for row in mi_r..=last_r {
5863 for col in mi_c..=last_c {
5864 if col < stride
5865 && let Some(cell) = self.uv_mode_grid.get_mut(row * stride + col)
5866 {
5867 *cell = uv_mode as u8;
5868 }
5869 }
5870 }
5871 }
5872
5873 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
5874 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
5875 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
5876 /// block has recorded the exact neighbouring mi.
5877 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
5878 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
5879 // REFERENCE block, not off the mi that carries the chroma syntax.
5880 // `set_mi_row_col` (`blockd.h`) takes
5881 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
5882 // only then `chroma_above_mbmi = base_mi[-stride]` /
5883 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
5884 // the ODD mi, so without the snap we looked one mi row/column too far
5885 // down/right -- the mi-exact slot never matched and the coarse
5886 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
5887 // 8x4 at (688, 100) = mi (51, 344): libaom's
5888 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
5889 // `UV_SMOOTH_PRED`), ours was 0, which flips
5890 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
5891 // false for type 1, TRUE for type 0) and upsampled an edge libaom
5892 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
5893 // predicting from it (class `context-read-from-one-cell`).
5894 self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c)
5895 }
5896
5897 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
5898 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
5899 /// counter wants this: it measures how often the snap CHANGES the answer,
5900 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
5901 /// decode path uses the snapping form.
5902 fn smooth_uv_neighbour_unsnapped(
5903 &self,
5904 mi_r: usize,
5905 mi_c: usize,
5906 r: usize,
5907 c: usize,
5908 ) -> bool {
5909 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
5910 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
5911 // array that `start_tile` does not clear, so a block on a tile's first
5912 // mi row used to read the uv_mode of the block above it in the tile
5913 // ABOVE and filter its chroma edge at that neighbour's strength
5914 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
5915 // at chroma (120, 32), the top-right tile's first block).
5916 let have_above = mi_r > self.tile_row0_mi;
5917 let have_left = mi_c > self.tile_col0_mi;
5918 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
5919 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
5920 {
5921 UV_TILE_EDGE_SUPPRESSED_HITS.with(|h| h.set(h.get() + 1));
5922 }
5923 // The mi grid is libaom's own read; the two maps below stay as the
5924 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
5925 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
5926 (col < self.uv_grid_cols)
5927 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
5928 .flatten()
5929 .filter(|&m| m != u8::MAX)
5930 .map(usize::from)
5931 };
5932 let above = match self.uv_mode_col.get(mi_c) {
5933 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m,
5934 Some(&(row, m)) if have_above && row == mi_r - 1 => m,
5935 _ if have_above => self.above_uv_mode[c],
5936 _ => DC_PRED,
5937 };
5938 let left = match self.uv_mode_row.get(mi_r) {
5939 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m,
5940 Some(&(col, m)) if have_left && col == mi_c - 1 => m,
5941 _ if have_left => self.left_uv_mode[r],
5942 _ => DC_PRED,
5943 };
5944 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
5945 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if row == mi_r - 1 && cm == m)
5946 }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| {
5947 !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if col == mi_c - 1 && cm == m)
5948 }) {
5949 UV_MODE_GRID_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
5950 }
5951 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
5952 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
5953 // have been filtered at the wrong strength by the coarse map alone.
5954 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
5955 UV_MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
5956 }
5957 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
5958 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
5959 {
5960 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|h| h.set(h.get() + 1));
5961 }
5962 is_smooth_mode(above) || is_smooth_mode(left)
5963 }
5964
5965 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
5966 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
5967 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
5968 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
5969 /// holding an OLDER, larger block's mode -- it only ever recorded into the
5970 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
5971 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
5972 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
5973 /// a different CDF for the same mode value).
5974 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
5975 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
5976 /// only when `up_available` and `left_mbmi` only when `left_available`;
5977 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
5978 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
5979 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
5980 /// strip's mode as its "left neighbour" (measured on the band fixture at
5981 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
5982 fn modes_above_left_mi(
5983 &self,
5984 mi_r: usize,
5985 mi_c: usize,
5986 fallback: (usize, usize),
5987 ) -> (usize, usize) {
5988 let above = if mi_r > self.tile_row0_mi {
5989 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
5990 } else {
5991 DC_PRED
5992 };
5993 let left = if mi_c > self.tile_col0_mi {
5994 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
5995 } else {
5996 DC_PRED
5997 };
5998 (above, left)
5999 }
6000
6001 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
6002 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
6003 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
6004 /// per superblock row and never per tile, so the first block column of
6005 /// tile 2..N read the previous tile's mode as its left neighbour, and the
6006 /// above band survives across a tile ROW boundary the same way lane-mtfix's
6007 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
6008 /// `up_available`/`left_available` and uses DC_PRED otherwise
6009 /// ([`Self::modes_above_left_mi`]).
6010 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
6011 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
6012 let (above, left) =
6013 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
6014 if above != self.above_mode[c] || left != self.left_mode[r] {
6015 MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
6016 }
6017 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
6018 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
6019 {
6020 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|h| h.set(h.get() + 1));
6021 }
6022 // A neighbour the coarse band offered where the tile edge makes it
6023 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
6024 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
6025 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
6026 {
6027 MODE_TILE_EDGE_COARSE_LEAKS.with(|h| h.set(h.get() + 1));
6028 }
6029 (above, left)
6030 }
6031
6032 fn record_rect(
6033 &mut self,
6034 at: (usize, usize),
6035 w: usize,
6036 h: usize,
6037 mode: usize,
6038 uv_mode: usize,
6039 grids: &[Vec<i32>; 3],
6040 ) {
6041 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
6042 }
6043
6044 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
6045 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
6046 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
6047 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
6048 /// the [`SUB`]-unit path does).
6049 fn record_rect_mi(
6050 &mut self,
6051 at_mi: (usize, usize),
6052 w: usize,
6053 h: usize,
6054 mode: usize,
6055 uv_mode: usize,
6056 grids: &[Vec<i32>; 3],
6057 ) {
6058 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
6059 // lane-inter4 r2: a strip whose own footprint runs past the frame's
6060 // last 16-px column/row stamps only the cells that exist (libaom's
6061 // arrays are padded past the frame and those cells are never read).
6062 for cell in 0..w / SUB {
6063 if c + cell >= self.above_mode.len() {
6064 break;
6065 }
6066 self.above_mode[c + cell] = mode;
6067 self.above_uv_mode[c + cell] = uv_mode;
6068 self.above_side[c + cell] = w;
6069 }
6070 for cell in 0..h / SUB {
6071 if r + cell >= self.left_mode.len() {
6072 break;
6073 }
6074 self.left_mode[r + cell] = mode;
6075 self.left_uv_mode[r + cell] = uv_mode;
6076 self.left_side[r + cell] = h;
6077 }
6078 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
6079 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
6080 self.record_mi_rect(at_mi, w, h, grids);
6081 }
6082
6083 /// The coefficient-context half of [`Self::record`], taking the block's
6084 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
6085 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
6086 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
6087 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
6088 self.record_mi_rect(at_mi, side, side, grids);
6089 }
6090
6091 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
6092 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
6093 fn record_mi_rect(
6094 &mut self,
6095 at_mi: (usize, usize),
6096 w: usize,
6097 h: usize,
6098 grids: &[Vec<i32>; 3],
6099 ) {
6100 let (mi_r, mi_c) = at_mi;
6101 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
6102 let (w_mi, h_mi) = (w / MI, h / MI);
6103 if crate::envflags::env_flag!("EC_ECPUB") {
6104 eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level);
6105 }
6106 for cell in 0..h_mi {
6107 if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) {
6108 *slot = h;
6109 }
6110 }
6111 for cell in 0..w_mi {
6112 if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) {
6113 *slot = w;
6114 }
6115 }
6116 // A chroma 4x4 unit straddling the true luma edge is still whole in
6117 // chroma's own halved grid, so libaom rounds the luma bound up to the
6118 // plane's own 4x4 unit before clamping a subsampled plane
6119 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
6120 let round_up_even = |n: usize| n.div_ceil(2) * 2;
6121 let bound_h = [
6122 self.mi_rows,
6123 round_up_even(self.mi_rows),
6124 round_up_even(self.mi_rows),
6125 ];
6126 let bound_w = [
6127 self.mi_cols,
6128 round_up_even(self.mi_cols),
6129 round_up_even(self.mi_cols),
6130 ];
6131 for cell in 0..h_mi {
6132 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
6133 // past the padded side arrays (mi_rows 198, block rows 192..208);
6134 // libaom's own arrays are superblock-sized, so those cells simply
6135 // have no reader. Same guard the `left_side_mi` loop above uses.
6136 let Some(left_slot) = self.left.get_mut(mi_r + cell) else {
6137 break;
6138 };
6139 *left_slot = std::array::from_fn(|plane| {
6140 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
6141 states[plane]
6142 } else {
6143 Default::default()
6144 }
6145 });
6146 }
6147 for cell in 0..w_mi {
6148 let Some(above_slot) = self.above.get_mut(mi_c + cell) else {
6149 break;
6150 };
6151 *above_slot = std::array::from_fn(|plane| {
6152 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
6153 states[plane]
6154 } else {
6155 Default::default()
6156 }
6157 });
6158 }
6159 }
6160
6161 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
6162 /// inside a coded block whose luma transform is smaller than its own
6163 /// side (`TxMode::Select`): the real per-transform-unit coefficient
6164 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
6165 /// coarse per-block `tx_grid`/`fill_lf_grid` state
6166 /// [`Self::record_split_luma`] still writes once for the whole block.
6167 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
6168 /// the caller's own [`Self::record_split_luma`] call sets those once,
6169 /// at the block's own true side, not this TU's.
6170 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
6171 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
6172 }
6173
6174 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
6175 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
6176 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
6177 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
6178 /// coefficient-context arrays are indexed by luma mi, the convention
6179 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
6180 /// clamp included.
6181 fn record_mi_chroma(
6182 &mut self,
6183 (mi_r, mi_c): (usize, usize),
6184 w_px: usize,
6185 h_px: usize,
6186 plane: usize,
6187 grid: &[i32],
6188 ) {
6189 let round_up_even = |n: usize| n.div_ceil(2) * 2;
6190 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
6191 let state = neighbour_state(grid);
6192 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
6193 self.left[mi_r + cell][plane] = state;
6194 }
6195 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
6196 self.above[mi_c + cell][plane] = state;
6197 }
6198 }
6199
6200 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
6201 /// r1): the above context spans the unit's width, the left context its
6202 /// height, which for a square unit is the same loop it always was.
6203 fn record_mi_luma_rect(
6204 &mut self,
6205 (mi_r, mi_c): (usize, usize),
6206 w_px: usize,
6207 h_px: usize,
6208 grid: &[i32],
6209 ) {
6210 let state = neighbour_state(grid);
6211 if crate::envflags::env_flag!("EC_ECPUB") {
6212 eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level);
6213 }
6214 for cell in 0..h_px / MI {
6215 if mi_r + cell < self.mi_rows {
6216 self.left[mi_r + cell][0] = state;
6217 }
6218 }
6219 for cell in 0..w_px / MI {
6220 if mi_c + cell < self.mi_cols {
6221 self.above[mi_c + cell][0] = state;
6222 }
6223 }
6224 }
6225
6226 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
6227 /// block whose luma was decoded as several transform units through
6228 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
6229 /// whole-block luma write -- everything [`Self::record`] does except
6230 /// plane 0, which is already correct per-TU by the time this runs.
6231 fn record_split_luma(
6232 &mut self,
6233 at: (usize, usize),
6234 side: usize,
6235 mode: usize,
6236 uv_mode: usize,
6237 chroma_grids: [&[i32]; 2],
6238 ) {
6239 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
6240 }
6241
6242 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
6243 /// extents in pixels (lane-rectsplit r1), the same relationship
6244 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
6245 /// luma transform split into several square units needs exactly this
6246 /// bookkeeping, at its own true rectangular extents.
6247 fn record_split_luma_rect(
6248 &mut self,
6249 at: (usize, usize),
6250 w: usize,
6251 h: usize,
6252 mode: usize,
6253 uv_mode: usize,
6254 chroma_grids: [&[i32]; 2],
6255 ) {
6256 let (r, c) = at;
6257 self.record_split_luma_rect_mi(
6258 (r * (SUB / MI), c * (SUB / MI)),
6259 w,
6260 h,
6261 mode,
6262 uv_mode,
6263 chroma_grids,
6264 );
6265 }
6266
6267 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
6268 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
6269 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
6270 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
6271 /// convention [`decode_block_rect4`] already established for 1:4 strips.
6272 fn record_split_luma_rect_mi(
6273 &mut self,
6274 at_mi: (usize, usize),
6275 w: usize,
6276 h: usize,
6277 mode: usize,
6278 uv_mode: usize,
6279 chroma_grids: [&[i32]; 2],
6280 ) {
6281 let (mi_r, mi_c) = at_mi;
6282 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
6283 for cell in 0..w.div_ceil(SUB) {
6284 if c + cell >= self.above_mode.len() {
6285 break;
6286 }
6287 self.above_mode[c + cell] = mode;
6288 self.above_uv_mode[c + cell] = uv_mode;
6289 self.above_side[c + cell] = w;
6290 }
6291 for cell in 0..h.div_ceil(SUB) {
6292 if r + cell >= self.left_mode.len() {
6293 break;
6294 }
6295 self.left_mode[r + cell] = mode;
6296 self.left_uv_mode[r + cell] = uv_mode;
6297 self.left_side[r + cell] = h;
6298 }
6299
6300 let (w_mi, h_mi) = (w / MI, h / MI);
6301 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
6302 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
6303 for cell in 0..h_mi {
6304 if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) {
6305 *slot = h;
6306 }
6307 }
6308 for cell in 0..w_mi {
6309 if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) {
6310 *slot = w;
6311 }
6312 }
6313 let round_up_even = |n: usize| n.div_ceil(2) * 2;
6314 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
6315 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
6316 let plane = plane_idx + 1;
6317 let state = neighbour_state(grid);
6318 for cell in 0..h_mi {
6319 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
6320 self.left[mi_r + cell][plane] = state;
6321 }
6322 }
6323 for cell in 0..w_mi {
6324 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
6325 self.above[mi_c + cell][plane] = state;
6326 }
6327 }
6328 }
6329 }
6330}
6331
6332/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
6333/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
6334/// exactly — including its skip context, which the real key-frame writer
6335/// always writes at a fixed context of zero (it never tracks a neighbour-based
6336/// one for intra blocks; that is the inter-frame writer's rule instead).
6337/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
6338/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
6339/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
6340/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
6341/// plain DC chroma.
6342/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
6343/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
6344/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
6345/// instead (the defect commit 1a89ed9 fixed at the square sites).
6346fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
6347 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
6348 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
6349}
6350
6351/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
6352/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
6353/// bound (spec `filter_intra_mode_info` never reads a symbol there).
6354fn filter_intra_size_class(side: usize) -> Option<usize> {
6355 match side {
6356 4 => Some(0),
6357 8 => Some(1),
6358 16 => Some(2),
6359 32 => Some(3),
6360 _ => None,
6361 }
6362}
6363
6364/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
6365/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
6366/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
6367/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
6368fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
6369 match (bw, bh) {
6370 (32, 16) => Some(4),
6371 (16, 32) => Some(5),
6372 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
6373 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
6374 // here dropped that symbol on every DC_PRED strip of that size and
6375 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
6376 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
6377 (16, 8) => Some(6),
6378 (8, 16) => Some(7),
6379 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
6380 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
6381 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
6382 (4, 8) => Some(8),
6383 (8, 4) => Some(9),
6384 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
6385 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
6386 // `use_filter_intra` symbol on those strips although aomenc writes
6387 // one for every DC_PRED block of that shape with
6388 // `--enable-filter-intra=1` (its default), silently desyncing the
6389 // tile (class symbol-consumption-gap).
6390 (32, 8) => Some(10),
6391 (8, 32) => Some(11),
6392 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
6393 // strips), rows 17/16 of `default_filter_intra_cdfs`.
6394 (16, 4) => Some(12),
6395 (4, 16) => Some(13),
6396 _ if bw == bh => filter_intra_size_class(bw),
6397 _ => None,
6398 }
6399}
6400
6401/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
6402/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
6403/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
6404/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
6405/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
6406fn palette_bsize_ctx(side: usize) -> Option<usize> {
6407 palette_bsize_ctx_wh(side, side)
6408}
6409
6410/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
6411/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
6412/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
6413/// for ANY bsize, not just the square ones a hand-picked table happened to
6414/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
6415/// row breaks the moment its indexing field moves off the diagonal, and a
6416/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
6417/// block dimension is a power of two, so `bw*bh` always is too and
6418/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
6419/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
6420fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
6421 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
6422 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
6423 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
6424 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
6425 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
6426 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
6427 if bw > 64 || bh > 64 || bw * bh < 64 {
6428 return None;
6429 }
6430 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
6431}
6432
6433/// A just-decoded palette-Y block's own size, base colours (only the first
6434/// `size` entries are real), and per-pixel colour-index map (`side*side`,
6435/// row-major, each entry `< size`).
6436struct PaletteY {
6437 size: usize,
6438 colors: [u16; 8],
6439 map: Vec<u8>,
6440}
6441
6442/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
6443/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
6444/// shared between U and V, both co-located after 4:2:0 subsampling) plus
6445/// each plane's own base colours.
6446struct PaletteUv {
6447 size: usize,
6448 u_colors: [u16; 8],
6449 v_colors: [u16; 8],
6450 map: Vec<u8>,
6451}
6452
6453/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
6454/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
6455/// `get_unsigned_bits`, which is the same formula): smallest `n` with
6456/// `2^n >= x`, `0` for `x <= 1`.
6457fn ceil_log2(x: u32) -> u32 {
6458 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
6459}
6460
6461/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
6462/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
6463fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
6464 let l = ceil_log2(n as u32);
6465 let m = (1usize << l) - n;
6466 let v = dec.literal(l - 1) as usize;
6467 if v < m {
6468 v
6469 } else {
6470 (v << 1) - m + dec.literal(1) as usize
6471 }
6472}
6473
6474/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
6475/// colours (already-known, from the above/left neighbours) with the
6476/// ascending `transmitted` ones (delta-coded off the wire) back into one
6477/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
6478/// value picks the cached copy first, matching the C `<=`.
6479fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
6480 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
6481 let (mut ci, mut ti) = (0, 0);
6482 while ci < cached.len() && ti < transmitted.len() {
6483 if cached[ci] <= transmitted[ti] {
6484 out.push(cached[ci]);
6485 ci += 1;
6486 } else {
6487 out.push(transmitted[ti]);
6488 ti += 1;
6489 }
6490 }
6491 out.extend_from_slice(&cached[ci..]);
6492 out.extend_from_slice(&transmitted[ti..]);
6493 out
6494}
6495
6496/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
6497/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
6498/// each delta's width, the `range` bound and the clamp) is sized by
6499/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
6500/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
6501/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
6502/// the msac range, so a cross-decoder range ladder stays bit-identical
6503/// through the whole miscount -- only the decoded VALUE differs (class
6504/// `compare-range-not-tell`'s blind spot). (this
6505/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
6506/// (one flag bit each, in cache order), then delta-codes the remainder
6507/// (first value raw, each following delta `>= 1` off a shrinking bit width),
6508/// and merges the two ascending lists back together.
6509fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
6510 let mut cached = Vec::with_capacity(n);
6511 for &c in cache {
6512 if cached.len() >= n {
6513 break;
6514 }
6515 if dec.literal(1) == 1 {
6516 cached.push(c);
6517 }
6518 }
6519 let bd = u32::from(bit_depth());
6520 let max_val = (1i32 << bd) - 1;
6521 let mut colors = [0u16; 8];
6522 let n_cached = cached.len();
6523 if n_cached < n {
6524 let mut transmitted = Vec::with_capacity(n - n_cached);
6525 let first = dec.literal(bd) as u16;
6526 transmitted.push(first);
6527 if n_cached + 1 < n {
6528 let min_bits = bd - 3;
6529 let mut bits = min_bits + dec.literal(2);
6530 let mut range = (1i32 << bd) - i32::from(first) - 1;
6531 for _ in (n_cached + 1)..n {
6532 let delta = dec.literal(bits) as i32 + 1;
6533 let prev = *transmitted.last().unwrap();
6534 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
6535 range -= i32::from(val) - i32::from(prev);
6536 bits = bits.min(ceil_log2(range.max(0) as u32));
6537 transmitted.push(val);
6538 }
6539 }
6540 let merged = merge_colors(&transmitted, &cached);
6541 colors[..n].copy_from_slice(&merged);
6542 } else {
6543 colors[..n].copy_from_slice(&cached[..n]);
6544 }
6545 colors
6546}
6547
6548/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
6549/// `bit_depth` (see [`read_palette_colors_y`]): U reads
6550/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
6551/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
6552/// unbiased by `+1` -- both differences from Y's own reader, matching the C
6553/// side by side). V never uses a cache: a leading bit picks either `n` raw
6554/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
6555/// rather than clamp.
6556fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
6557 let mut cached = Vec::with_capacity(n);
6558 for &c in cache {
6559 if cached.len() >= n {
6560 break;
6561 }
6562 if dec.literal(1) == 1 {
6563 cached.push(c);
6564 }
6565 }
6566 let bd = u32::from(bit_depth());
6567 let max_val = 1i32 << bd;
6568 let mut u_colors = [0u16; 8];
6569 let n_cached = cached.len();
6570 if n_cached < n {
6571 let mut transmitted = Vec::with_capacity(n - n_cached);
6572 let first = dec.literal(bd) as u16;
6573 transmitted.push(first);
6574 if n_cached + 1 < n {
6575 let min_bits = bd - 3;
6576 let mut bits = min_bits + dec.literal(2);
6577 let mut range = max_val - i32::from(first);
6578 for _ in (n_cached + 1)..n {
6579 let delta = dec.literal(bits) as i32;
6580 let prev = *transmitted.last().unwrap();
6581 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
6582 range -= i32::from(val) - i32::from(prev);
6583 bits = bits.min(ceil_log2(range.max(0) as u32));
6584 transmitted.push(val);
6585 }
6586 }
6587 let merged = merge_colors(&transmitted, &cached);
6588 u_colors[..n].copy_from_slice(&merged);
6589 } else {
6590 u_colors[..n].copy_from_slice(&cached[..n]);
6591 }
6592 let mut v_colors = [0u16; 8];
6593 if dec.literal(1) == 1 {
6594 let min_bits_v = bd - 4;
6595 let bits = min_bits_v + dec.literal(2);
6596 v_colors[0] = dec.literal(bd) as u16;
6597 for i in 1..n {
6598 let mut delta = dec.literal(bits) as i32;
6599 if delta != 0 && dec.literal(1) == 1 {
6600 delta = -delta;
6601 }
6602 let mut val = i32::from(v_colors[i - 1]) + delta;
6603 if val < 0 {
6604 val += max_val;
6605 }
6606 if val >= max_val {
6607 val -= max_val;
6608 }
6609 v_colors[i] = val as u16;
6610 }
6611 } else {
6612 for i in 0..n {
6613 v_colors[i] = dec.literal(bd) as u16;
6614 }
6615 }
6616 (u_colors, v_colors)
6617}
6618
6619/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
6620/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
6621/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
6622const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
6623
6624/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
6625/// map's own per-pixel context and colour-order permutation, from the
6626/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
6627/// selection sort). `map`'s stride is `side` (this decoder never crops a
6628/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
6629/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
6630/// actual colour index to store.
6631fn palette_color_index_context(
6632 map: &[u8],
6633 side: usize,
6634 row: usize,
6635 col: usize,
6636 n: usize,
6637) -> (usize, [u8; 8]) {
6638 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
6639 let up_left = if col >= 1 && row >= 1 {
6640 Some(map[(row - 1) * side + col - 1])
6641 } else {
6642 None
6643 };
6644 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
6645 let mut scores = [0i32; 8];
6646 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
6647 if let Some(v) = neighbour {
6648 scores[v as usize] += weight;
6649 }
6650 }
6651 let mut color_order = [0u8; 8];
6652 for i in 0..8 {
6653 color_order[i] = i as u8;
6654 }
6655 for i in 0..3 {
6656 let mut max = scores[i];
6657 let mut max_idx = i;
6658 for j in (i + 1)..n {
6659 if scores[j] > max {
6660 max = scores[j];
6661 max_idx = j;
6662 }
6663 }
6664 if max_idx != i {
6665 let max_score = scores[max_idx];
6666 let max_color = color_order[max_idx];
6667 for k in (i + 1..=max_idx).rev() {
6668 scores[k] = scores[k - 1];
6669 color_order[k] = color_order[k - 1];
6670 }
6671 scores[i] = max_score;
6672 color_order[i] = max_color;
6673 }
6674 }
6675 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
6676 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
6677 (ctx as usize, color_order)
6678}
6679
6680/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
6681/// map's wavefront decode over a `side x side` grid -- this decoder's
6682/// palette blocks are always square and never straddle the frame's true
6683/// (possibly odd) edge without already allocating the full `side*side`
6684/// region (every other skip/residual path here does the same), so no
6685/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
6686/// libaom's own non-block-aligned split.
6687fn decode_color_index_map(
6688 dec: &mut SymbolDecoder,
6689 cdfs: &mut Cdfs,
6690 n: usize,
6691 side: usize,
6692 uv: bool,
6693) -> Vec<u8> {
6694 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
6695}
6696
6697/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
6698/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
6699/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
6700/// independently rather than one shared `side` -- the square call above is
6701/// just `bw == bh`.
6702fn decode_color_index_map_wh(
6703 dec: &mut SymbolDecoder,
6704 cdfs: &mut Cdfs,
6705 n: usize,
6706 bw: usize,
6707 bh: usize,
6708 uv: bool,
6709) -> Vec<u8> {
6710 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6711 let mut map = vec![0u8; bw * bh];
6712 if trace {
6713 let (rng, _) = dec.debug_state();
6714 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
6715 }
6716 map[0] = read_uniform(dec, n) as u8;
6717 if trace {
6718 let (rng, _) = dec.debug_state();
6719 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
6720 }
6721 for i in 1..(bw + bh - 1) {
6722 let j_hi = i.min(bw - 1);
6723 let j_lo = i.saturating_sub(bh - 1);
6724 for j in (j_lo..=j_hi).rev() {
6725 let row = i - j;
6726 let col = j;
6727 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
6728 if trace {
6729 let (rng, _) = dec.debug_state();
6730 let row_cdf = if uv {
6731 &cdfs.palette_uv_color_index[n - 2][ctx]
6732 } else {
6733 &cdfs.palette_y_color_index[n - 2][ctx]
6734 };
6735 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]);
6736 }
6737 let symbol = if uv {
6738 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
6739 } else {
6740 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
6741 };
6742 map[row * bw + col] = color_order[symbol];
6743 if trace {
6744 let (rng, _) = dec.debug_state();
6745 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
6746 }
6747 }
6748 }
6749 map
6750}
6751
6752/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
6753/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
6754/// size class comes from [`filter_intra_size_class_rect`] instead of the
6755/// square-only [`filter_intra_size_class`], and the palette read (when
6756/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
6757/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
6758/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
6759/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
6760#[allow(clippy::too_many_arguments)]
6761fn read_intra_mode_rect(
6762 dec: &mut SymbolDecoder,
6763 cdfs: &mut Cdfs,
6764 above_mode: usize,
6765 left_mode: usize,
6766 cfl: bool,
6767 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
6768 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
6769 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
6770 // chroma is coded once, on the closing strip). Every other caller is a
6771 // block big enough to own its chroma and passes `true`.
6772 has_chroma: bool,
6773 bw: usize,
6774 bh: usize,
6775 enable_filter_intra: bool,
6776 skip_ctx: usize,
6777 allow_screen_content_tools: bool,
6778 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
6779 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
6780 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
6781 palette: Option<(usize, &[u16])>,
6782 palette_uv_cache: &[u16],
6783 mi_r: usize,
6784 mi_c: usize,
6785) -> Result<(
6786 bool,
6787 usize,
6788 i32,
6789 usize,
6790 i32,
6791 Option<(i32, i32)>,
6792 Option<usize>,
6793 Option<PaletteY>,
6794 Option<PaletteUv>,
6795)> {
6796 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
6797 if ec_istep {
6798 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
6799 // (decodemv.c:818), printed at the same point: before the first
6800 // mode-info symbol of the block, so a cross-decoder range ladder can
6801 // be keyed on the BLOCK, not just on the symbol sequence.
6802 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}", enable_filter_intra as i32, filter_intra_size_class_rect(bw, bh), dec.debug_state().0);
6803 }
6804 macro_rules! istep {
6805 ($name:literal, $val:expr) => {
6806 if ec_istep {
6807 let (rng, _) = dec.debug_state();
6808 eprintln!(
6809 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
6810 $name, $val
6811 );
6812 }
6813 };
6814 }
6815 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
6816 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
6817 // the one point every rect caller routes through, so no call site can
6818 // offer the 14-symbol CFL alphabet on a 64-axis block (class
6819 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
6820 let cfl = if cfl && bw.max(bh) > 32 {
6821 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
6822 false
6823 } else {
6824 cfl
6825 };
6826 // lane-intra14 r1: on the INTER block path everything up to and including
6827 // `is_inter` was already read by [`decode_inter_block`], so this reader
6828 // starts at the mode syntax with the `skip` that caller read.
6829 let inter = INTRA_IN_INTER_MODE.with(std::cell::Cell::get);
6830 let skip = if let Some((_, skip)) = inter {
6831 skip
6832 } else {
6833 // Same `intra_segment_id` placement as the square reader above.
6834 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
6835 if seg_id_pre_skip() {
6836 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
6837 }
6838 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
6839 istep!("skip", skip as i32);
6840 if !seg_id_pre_skip() {
6841 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
6842 }
6843 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
6844 istep!("cdef", 0);
6845 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
6846 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
6847 // `false`.
6848 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
6849 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
6850 istep!("dq", 0);
6851 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
6852 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
6853 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
6854 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
6855 // rect strips read it exactly like square leaves ([`read_intra_mode`],
6856 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
6857 // decoder at the FIRST symbol of the first rect block of every
6858 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
6859 // block at this shape is out of scope, so the flag is consumed and
6860 // refused by name when it fires.
6861 if allow_intrabc_frame() {
6862 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
6863 RECT_INTRABC_READS.with(|c| c.set(c.get() + 1));
6864 istep!("intrabc", use_intrabc as i32);
6865 if use_intrabc {
6866 INTRABC_HITS.with(|c| c.set(c.get() + 1));
6867 return Err(unsupported(
6868 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
6869 ));
6870 }
6871 }
6872 skip
6873 };
6874 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
6875 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
6876 // off `kf_y_mode_cdf[above][left]`).
6877 let mode = if let Some((size_group, _)) = inter {
6878 dec.symbol(&mut cdfs.y_mode[size_group])
6879 } else {
6880 let above_ctx = INTRA_MODE_CTX[above_mode];
6881 let left_ctx = INTRA_MODE_CTX[left_mode];
6882 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
6883 };
6884 istep!("mode", mode as i32);
6885 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
6886 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
6887 } else {
6888 0
6889 };
6890 istep!("angle_y", angle_delta_y);
6891 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
6892 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
6893 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
6894 // here, from the block's own size, is the single point every caller routes
6895 // through -- a caller passing `true` for a >32 strip used to pick the
6896 // 14-symbol CFL CDF, same value but a different range (class
6897 // wrong-alphabet-same-value).
6898 let cfl = cfl && bw <= 32 && bh <= 32;
6899 let uv_mode = if !has_chroma {
6900 DC_PRED
6901 } else if cfl {
6902 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
6903 } else {
6904 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
6905 };
6906 istep!("uv_mode", uv_mode as i32);
6907 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
6908 Some(read_cfl_alphas(dec, cdfs))
6909 } else {
6910 None
6911 };
6912 if has_chroma && (9..=12).contains(&uv_mode) {
6913 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
6914 }
6915 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
6916 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
6917 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
6918 } else {
6919 0
6920 };
6921 istep!("angle_uv", angle_delta_uv);
6922 if angle_delta_uv != 0 {
6923 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
6924 }
6925 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
6926 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
6927 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
6928 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
6929 // colours only here, the colour-index maps deferred past `filter_intra`
6930 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
6931 // runs from the caller, after the whole mode-info read).
6932 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
6933 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
6934 if allow_screen_content_tools
6935 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
6936 {
6937 // r6: this is the exact site the removed blanket refusal used to
6938 // guard -- reached for EVERY rect strip in a screen-content frame,
6939 // independent of whether the block ends up using a palette.
6940 RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1));
6941 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
6942 let use_palette_y =
6943 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
6944 if use_palette_y {
6945 if palette.is_none() {
6946 return Err(unsupported(
6947 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
6948 ));
6949 }
6950 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
6951 let colors = read_palette_colors_y(dec, n, cache);
6952 palette_y_pending = Some((n, colors));
6953 }
6954 let palette_uv_mode_ctx = usize::from(use_palette_y);
6955 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
6956 if has_chroma
6957 && uv_mode == DC_PRED
6958 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
6959 {
6960 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
6961 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
6962 palette_uv_pending = Some((n, u_colors, v_colors));
6963 }
6964 }
6965 let mut filter_intra = None;
6966 if crate::envflags::env_flag!("EC_AV1_TRACE") {
6967 let (rng, _) = dec.debug_state();
6968 eprintln!(
6969 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
6970 class={:?} rng={rng}",
6971 enable_filter_intra as i32,
6972 filter_intra_size_class_rect(bw, bh)
6973 );
6974 }
6975 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
6976 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
6977 if mode == DC_PRED
6978 && enable_filter_intra
6979 && palette_y_pending.is_none()
6980 && let Some(class) = filter_intra_size_class_rect(bw, bh)
6981 {
6982 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
6983 if crate::envflags::env_flag!("EC_AV1_TRACE") {
6984 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
6985 }
6986 istep!("use_filter_intra", use_filter_intra as i32);
6987 if use_filter_intra {
6988 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
6989 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
6990 istep!("filter_intra_mode", fi_mode as i32);
6991 filter_intra = Some(fi_mode);
6992 }
6993 }
6994 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
6995 // same order as [`read_intra_mode`]'s own square path.
6996 let palette_y = palette_y_pending.map(|(n, colors)| {
6997 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
6998 PALETTE_HITS.with(|c| c.set(c.get() + 1));
6999 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
7000 PaletteY { size: n, colors, map }
7001 });
7002 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
7003 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
7004 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
7005 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
7006 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
7007 // chroma palette and desynced the tile from there.
7008 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
7009 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
7010 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
7011 PaletteUv { size: n, u_colors, v_colors, map }
7012 });
7013 Ok((
7014 skip,
7015 mode,
7016 angle_delta_y,
7017 uv_mode,
7018 angle_delta_uv,
7019 alpha,
7020 filter_intra,
7021 palette_y,
7022 palette_uv,
7023 ))
7024}
7025
7026/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
7027/// at the strip's REAL mi position. `av1_get_palette_cache` reads
7028/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
7029/// block, so each strip owns its own rows and columns and no aliasing rule
7030/// is needed (lane-kf900 r6).
7031#[allow(clippy::too_many_arguments)]
7032fn record_strip_palette(
7033 n: &mut Neighbours,
7034 mi: (usize, usize),
7035 bw: usize,
7036 bh: usize,
7037 y_size: usize,
7038 y_colors: [u16; 8],
7039 uv_size: usize,
7040 uv_colors: [u16; 8],
7041) {
7042 let (r, c) = mi;
7043 // lane-t900 r23 rung: every publication of a block's palette state into
7044 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
7045 // path left a stale `left_palette_size` behind when
7046 // `av1_get_palette_mode_ctx` disagrees with libaom's.
7047 if crate::envflags::env_flag!("EC_PALPUB") {
7048 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
7049 }
7050 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
7051 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
7052 // existed because the 16px [`SUB`] cell held one slot for all the strips
7053 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
7054 // real neighbour leaf 1 reads.
7055 {
7056 for cell in 0..(bw / MI).max(1) {
7057 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
7058 *e = y_size;
7059 n.above_palette_colors[c + cell] = y_colors;
7060 n.above_palette_uv_size[c + cell] = uv_size;
7061 n.above_palette_uv_colors[c + cell] = uv_colors;
7062 }
7063 }
7064 }
7065 {
7066 for cell in 0..(bh / MI).max(1) {
7067 if n.left_palette_size.get(r + cell).is_none() {
7068 break;
7069 }
7070 n.left_palette_size[r + cell] = y_size;
7071 n.left_palette_colors[r + cell] = y_colors;
7072 n.left_palette_uv_size[r + cell] = uv_size;
7073 n.left_palette_uv_colors[r + cell] = uv_colors;
7074 }
7075 }
7076}
7077
7078/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
7079/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
7080/// above against this block's own *width* and the neighbour to the left
7081/// against its own *height* -- for a square block those are the same value,
7082/// which is why the square-only version can get away with one `own_side`.
7083fn tx_size_context_rect(
7084 n: &Neighbours,
7085 (mi_r, mi_c): (usize, usize),
7086 own_w: usize,
7087 own_h: usize,
7088) -> usize {
7089 // `get_tx_size_context` compares against `max_txsize_rect_lookup[bsize]`,
7090 // not the block's own side: no transform is wider or taller than 64, so a
7091 // block with a 128 side resolves against 64 (the square path already caps
7092 // this way, lane-sb128b r1). Without the cap the 64x128 half of a 128-root
7093 // VERT reads the tx-depth symbol off row 0 where libaom uses row 1.
7094 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
7095 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
7096 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
7097 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
7098 eprintln!(
7099 "EC_TXCTX mi_row={mi_r} mi_col={mi_c} w={own_w} h={own_h} above_px={} left_px={} ctx={}",
7100 if mi_r > n.tile_row0_mi { tx_px_at(n, false, mi_r - 1, mi_c) } else { 0 },
7101 if mi_c > n.tile_col0_mi { tx_h_px_at(n, false, mi_r, mi_c - 1) } else { 0 },
7102 usize::from(above) + usize::from(left)
7103 );
7104 }
7105 usize::from(above) + usize::from(left)
7106}
7107
7108/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
7109fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
7110 let (cw, ch) = (bw / 2, bh / 2);
7111 let mut ac = vec![0i32; cw * ch];
7112 let mut sum = 0i32;
7113 for cy in 0..ch {
7114 for cx in 0..cw {
7115 let (lx, ly) = (px + cx * 2, py + cy * 2);
7116 let q3 = (i32::from(y.data[ly * y.width + lx])
7117 + i32::from(y.data[ly * y.width + lx + 1])
7118 + i32::from(y.data[(ly + 1) * y.width + lx])
7119 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
7120 << 1;
7121 ac[cy * cw + cx] = q3;
7122 sum += q3;
7123 }
7124 }
7125 let num_pel = (cw * ch) as i32;
7126 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
7127 ac.iter_mut().for_each(|v| *v -= avg);
7128 ac
7129}
7130
7131/// Everything a rect strip already read out of the stream before its luma
7132/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
7133/// (nine values that would otherwise be nine more parameters).
7134struct RectStripModes {
7135 skip: bool,
7136 mode: usize,
7137 angle_delta_y: i32,
7138 uv_predict_mode: usize,
7139 angle_delta_uv: i32,
7140 alpha: Option<(i32, i32)>,
7141 filter_intra: Option<usize>,
7142 smooth_neighbor: bool,
7143 smooth_neighbor_uv: bool,
7144 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
7145 /// mapped through the colour table), sliced per transform unit below --
7146 /// palette prediction reads no edge pixels, so a unit's slice of the
7147 /// whole-block map IS its prediction. Without this a palette strip whose
7148 /// transform splits predicted DC and came out flat grey while the entropy
7149 /// stream stayed in sync (the coefficients are read either way).
7150 palette_y: Option<Vec<u16>>,
7151 /// As `palette_y`, for the un-split chroma transform (U, V).
7152 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
7153}
7154
7155/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
7156/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
7157/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
7158/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
7159/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
7160/// TX_32X16`) and only the second reaches a square -- the reason
7161/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
7162/// already square) mis-tiled 1:4 strips.
7163fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) {
7164 let (mut w, mut h) = (bw.min(64), bh.min(64));
7165 for _ in 0..depth {
7166 match w.cmp(&h) {
7167 std::cmp::Ordering::Greater => w /= 2,
7168 std::cmp::Ordering::Less => h /= 2,
7169 std::cmp::Ordering::Equal => {
7170 w /= 2;
7171 h /= 2;
7172 }
7173 }
7174 }
7175 (w, h)
7176}
7177
7178/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
7179/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
7180/// rect path here refused by name until now ("per-unit rect prediction is not
7181/// ported").
7182///
7183/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
7184/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
7185/// strip the very first step already lands on a SQUARE transform
7186/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
7187/// every further step halves a square) -- so each unit is square and reads
7188/// through the ordinary square [`read_plane`]. What is genuinely rectangular
7189/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
7190/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
7191/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
7192/// split by luma's depth.
7193///
7194/// Each unit predicts off whatever the earlier units of this same block
7195/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
7196/// inside `av1_foreach_transformed_block`, raster order), which is exactly
7197/// what predicting the whole strip in one shot got wrong.
7198#[allow(clippy::too_many_arguments)]
7199fn decode_rect_split(
7200 dec: &mut SymbolDecoder,
7201 cdfs: &mut Cdfs,
7202 neighbours: &mut Neighbours,
7203 at_mi: (usize, usize),
7204 bw: usize,
7205 bh: usize,
7206 // The transform unit's own width and height in pixels. Square for every
7207 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
7208 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
7209 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
7210 tx_w: usize,
7211 tx_h: usize,
7212 m: &RectStripModes,
7213 y: &mut PlaneBuf,
7214 u: &mut PlaneBuf,
7215 v: &mut PlaneBuf,
7216 base_q_idx: u8,
7217 reduced_tx_set: bool,
7218) -> Result<()> {
7219 let (mi_r, mi_c) = at_mi;
7220 let (px, py) = (mi_c * MI, mi_r * MI);
7221 let (cpx, cpy) = (px / 2, py / 2);
7222 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
7223 // The chroma transform is picked before any symbol is read, so an
7224 // unsupported chroma shape refuses before this strip desyncs the tile.
7225 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
7226 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
7227 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
7228 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
7229 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
7230 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
7231 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
7232 // squares a rect transform down to a CDF set by
7233 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
7234 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
7235 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
7236 // paths already prove for these same shapes.
7237 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
7238 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
7239 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
7240 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
7241 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
7242 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
7243 _ => None,
7244 };
7245 if !m.skip {
7246 if let Some(i) = match (chroma_w, chroma_h) {
7247 (32, 8) => Some(0),
7248 (8, 32) => Some(1),
7249 (8, 4) => Some(2),
7250 (4, 8) => Some(3),
7251 _ => None,
7252 } {
7253 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
7254 let mut hits = c.get();
7255 hits[i] += 1;
7256 c.set(hits);
7257 });
7258 }
7259 if chroma.is_none() {
7260 // Diagnostic for the next caller that lands here (class
7261 // refusal-names-a-correlate: the message names the tool, not the
7262 // shape); the refusal below keeps its inventory-pinned wording.
7263 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
7264 }
7265 }
7266 // lane-rectsplit r2 (verifier finding): with both callers wired
7267 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
7268 // 64x32/32x64) every shape that reaches here has a table above, so this
7269 // arm is UNREACHABLE today. It stays as the shape guard for the next
7270 // caller -- a new strip size would otherwise hit the `expect` below and
7271 // panic instead of refusing by name -- and so stays in
7272 // `refusal_inventory::REFUSALS`.
7273 if !m.skip && chroma.is_none() {
7274 return Err(unsupported(
7275 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
7276 ));
7277 }
7278 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
7279 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
7280 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1));
7281 }
7282 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
7283 // A square unit reads through the ordinary square [`read_plane`]; a rect
7284 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
7285 // the very tables the unsplit 16x8/32x16 paths use.
7286 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
7287 (w, h) if w == h => None,
7288 (16, 8) | (8, 16) => Some((
7289 if reduced_tx_set {
7290 TxbSet::LumaRect16x8
7291 } else {
7292 TxbSet::LumaRect16x8Set1
7293 },
7294 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
7295 )),
7296 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
7297 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
7298 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
7299 // strip, read through the `luma_64corner` arm below instead of a rect
7300 // table -- a 64-length axis codes only its low 32 coefficients
7301 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
7302 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
7303 // depth-0 arm already reads on the key-frame path.
7304 //
7305 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
7306 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
7307 // sub-8x8 intra leaves still refused: with those lifted (r2) the
7308 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
7309 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
7310 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
7311 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
7312 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
7313 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
7314 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
7315 (64, 32) | (32, 64) => None,
7316 _ => {
7317 return Err(unsupported(format!(
7318 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
7319 coefficient tables for that shape here)"
7320 )))
7321 }
7322 };
7323 // The `None` above that is NOT the square arm.
7324 let luma_64corner = tx_w != tx_h;
7325 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
7326 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
7327 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
7328 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
7329 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
7330 // per-unit rect walk stay wired above/below; the round that finds that
7331 // defect deletes this refusal and nothing else.
7332 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
7333 let luma_scan = default_scan(tx_w.min(tx_h));
7334 let zero_tu = vec![0i32; tx_w * tx_h];
7335 // The strip's OWN edge availability, the fallback for a transform unit
7336 // whose top-right/bottom-left pixels fall outside the strip.
7337 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
7338 for tu_row in 0..bh / tx_h {
7339 for tu_col in 0..bw / tx_w {
7340 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
7341 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
7342 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
7343 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
7344 // libaom clips `av1_foreach_transformed_block_in_plane` to
7345 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
7346 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
7347 // TOP-LEFT sample falls outside the frame is never coded. We read
7348 // coefficients for those phantom units and desynced the stream at
7349 // the very next symbol.
7350 if tu_px >= y.true_width || tu_py >= y.true_height {
7351 continue;
7352 }
7353 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
7354 // transform unit INSIDE a block, which is a different rule from
7355 // the standalone-block table [`Reach::of`] applies -- and the
7356 // reason a depth-2 superblock strip came out one sample off
7357 // before this: `Reach::of(tx, ..)` answered as if the unit were
7358 // its own block at that superblock position.
7359 // * top-right: if the unit's right neighbour is still inside the
7360 // strip the pixels are already reconstructed (`col_off +
7361 // tx_wide < plane_bw`); otherwise only the strip's own top row
7362 // of units can reach past it, through the block-level answer.
7363 // * bottom-left: a unit that is not in the strip's left column
7364 // has none (`col_off > 0` returns 0); inside the strip
7365 // (`row_off + tx_high < plane_bh`) they are the left
7366 // neighbour's, already reconstructed; the last row falls back
7367 // to the block-level answer.
7368 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
7369 // The unit's own window on the block's palette prediction.
7370 if let Some(buf) = &m.palette_y {
7371 let tu_buf: Vec<u16> = (0..tx_h)
7372 .flat_map(|i| {
7373 let base = (row_off + i) * bw + col_off;
7374 buf[base..base + tx_w].iter().copied()
7375 })
7376 .collect();
7377 set_palette_pred(tu_buf);
7378 }
7379 if m.skip {
7380 y.reconstruct_rect(
7381 tu_px,
7382 tu_py,
7383 tx_w,
7384 tx_h,
7385 m.mode,
7386 m.angle_delta_y,
7387 tu_reach,
7388 &zero_tu,
7389 None,
7390 m.filter_intra,
7391 m.smooth_neighbor,
7392 );
7393 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
7394 } else if luma_64corner && luma_rect.is_none() {
7395 // The un-split 64-level luma transform: `read_coeffs` on the
7396 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
7397 // and the real rect shape passed through for
7398 // `av1_nz_map_ctx_offset` -- byte for byte
7399 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
7400 // 64-level strip gate already proves. `tx_type` is not coded
7401 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
7402 // the square-up size is TX_64X64), and this unit covers its
7403 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
7404 if crate::envflags::env_flag!("EC_RECT64TU") {
7405 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
7406 }
7407 RECT64_CORNER_TU_HITS.with(|c| {
7408 let mut v = c.get();
7409 v[usize::from(tx_h > tx_w)] += 1;
7410 c.set(v);
7411 });
7412 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
7413 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
7414 let (corner, tu_tx_type) = read_coeffs(
7415 dec,
7416 &mut coding,
7417 &default_scan(TX32),
7418 0,
7419 dc_sign_ctx(tu_around.2),
7420 TxType::DctDct,
7421 Some((tx_w, tx_h)),
7422 )?;
7423 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
7424 let mut tu_grid = vec![0i32; tx_w * tx_h];
7425 for row in 0..ch {
7426 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
7427 }
7428 let residual = dequant_and_inverse_typed_wh(
7429 &tu_grid,
7430 tx_w,
7431 tx_h,
7432 crate::decode::bit_depth(),
7433 block_q_idx(),
7434 plane_q_delta(0).0,
7435 plane_q_delta(0).1,
7436 tu_tx_type,
7437 );
7438 y.reconstruct_rect(
7439 tu_px,
7440 tu_py,
7441 tx_w,
7442 tx_h,
7443 m.mode,
7444 m.angle_delta_y,
7445 tu_reach,
7446 &residual,
7447 None,
7448 m.filter_intra,
7449 m.smooth_neighbor,
7450 );
7451 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
7452 } else if let Some((rect_set, rect_scan)) = luma_rect {
7453 // The rect-unit twin of the square arm below: same contexts,
7454 // same order, through the rect coefficient reader. The
7455 // `tx_type` CDF row of a filter-intra block is
7456 // `fimode_to_intradir[filter_intra_mode]`, never the block's
7457 // own (always DC_PRED) mode -- [`read_plane`] applies that
7458 // for the square arm, so this one must too.
7459 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
7460 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
7461 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
7462 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
7463 // neighbour-magnitude table is for a unit SMALLER than its
7464 // block. [`decode_block_rect`]'s own unsplit read passes a
7465 // literal 0 for the same reason; this arm applied the table
7466 // unconditionally and desynced every depth-0 rect strip that
7467 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
7468 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
7469 0
7470 } else {
7471 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
7472 };
7473 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
7474 let (tu_grid, tu_tx_type) = read_coeffs_rect(
7475 dec,
7476 &mut coding,
7477 rect_scan,
7478 tx_w,
7479 tx_h,
7480 tu_skip_ctx,
7481 dc_sign_ctx(tu_around.2),
7482 TxType::DctDct,
7483 )?;
7484 let residual = dequant_and_inverse_typed_wh(
7485 &tu_grid,
7486 tx_w,
7487 tx_h,
7488 crate::decode::bit_depth(),
7489 block_q_idx(),
7490 plane_q_delta(0).0,
7491 plane_q_delta(0).1,
7492 tu_tx_type,
7493 );
7494 y.reconstruct_rect(
7495 tu_px,
7496 tu_py,
7497 tx_w,
7498 tx_h,
7499 m.mode,
7500 m.angle_delta_y,
7501 tu_reach,
7502 &residual,
7503 None,
7504 m.filter_intra,
7505 m.smooth_neighbor,
7506 );
7507 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
7508 } else {
7509 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
7510 // This unit is smaller than the block it sits in, so
7511 // `txb_skip_ctx` is the neighbour-magnitude table, not the
7512 // lone-TU 0 (spec `get_txb_ctx_general`).
7513 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
7514 let tu_grid = read_plane(
7515 dec,
7516 cdfs,
7517 luma_set,
7518 &luma_scan,
7519 0,
7520 tu_around,
7521 m.mode,
7522 m.mode,
7523 m.angle_delta_y,
7524 tu_reach,
7525 y,
7526 tu_px,
7527 tu_py,
7528 tx_w,
7529 tx_w,
7530 base_q_idx,
7531 None,
7532 m.filter_intra,
7533 Some(tu_skip_ctx),
7534 m.smooth_neighbor,
7535 )?;
7536 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
7537 }
7538 }
7539 }
7540 // CHROMA: one un-split rect transform for the whole strip.
7541 let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7542 let reach = block_reach;
7543 let (u_grid, v_grid) = if m.skip {
7544 let zero = vec![0i32; chroma_w * chroma_h];
7545 if let Some((ub, _)) = &m.palette_uv {
7546 set_palette_pred(ub.clone());
7547 }
7548 u.reconstruct_rect(
7549 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
7550 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
7551 );
7552 if let Some((_, vb)) = &m.palette_uv {
7553 set_palette_pred(vb.clone());
7554 }
7555 v.reconstruct_rect(
7556 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
7557 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
7558 );
7559 (zero.clone(), zero)
7560 } else {
7561 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
7562 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
7563 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
7564 // so only the 16x8/8x16 pair takes the mode-indexed default.
7565 let default_tx = if chroma_w.max(chroma_h) >= 32 {
7566 TxType::DctDct
7567 } else {
7568 default_intra_tx_type(m.uv_predict_mode as u8)
7569 };
7570 let around = neighbours.around_mi_rect(at_mi, bw, bh);
7571 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
7572 for plane_idx in 1..=2 {
7573 let skip_ctx =
7574 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
7575 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
7576 let (levels, tx_type) = read_coeffs_rect(
7577 dec,
7578 &mut coding,
7579 chroma_scan,
7580 chroma_w,
7581 chroma_h,
7582 skip_ctx,
7583 dc_sign_ctx(around[plane_idx].2),
7584 default_tx,
7585 )?;
7586 // The same delta_q proof the unsplit rect64 path records
7587 // (lane-rectsplit r4: lifting the split-transform refusal moved
7588 // superblock strips onto this path, so only counting there would
7589 // leave the delta_q gate's counter silent for them).
7590 if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) {
7591 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
7592 }
7593 let residual = dequant_and_inverse_typed_wh(
7594 &levels,
7595 chroma_w,
7596 chroma_h,
7597 crate::decode::bit_depth(),
7598 CURRENT_Q_IDX.with(|c| c.get()),
7599 plane_q_delta(plane_idx).0,
7600 plane_q_delta(plane_idx).1,
7601 tx_type,
7602 );
7603 let cfl = m
7604 .alpha
7605 .zip(ac.as_deref())
7606 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
7607 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
7608 if let Some((ub, vb)) = &m.palette_uv {
7609 let buf = if plane_idx == 1 { ub } else { vb };
7610 set_palette_pred(buf.clone());
7611 }
7612 plane.reconstruct_rect(
7613 cpx,
7614 cpy,
7615 chroma_w,
7616 chroma_h,
7617 m.uv_predict_mode,
7618 m.angle_delta_uv,
7619 reach,
7620 &residual,
7621 cfl,
7622 None,
7623 m.smooth_neighbor_uv,
7624 );
7625 grids.push(levels);
7626 }
7627 let mut it = grids.into_iter();
7628 (it.next().unwrap(), it.next().unwrap())
7629 };
7630 neighbours.record_split_luma_rect_mi(
7631 at_mi,
7632 bw,
7633 bh,
7634 m.mode,
7635 m.uv_predict_mode,
7636 [&u_grid, &v_grid],
7637 );
7638 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
7639 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
7640 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7641 let (rng, _) = dec.debug_state();
7642 eprintln!(
7643 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
7644 tx={tx_w}x{tx_h} rng={rng}"
7645 );
7646 }
7647 Ok(())
7648}
7649
7650/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
7651/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
7652/// because it predicts squares only. Every pixel here goes through the rect
7653/// machinery the key-frame paths already prove: [`decode_rect_split`], which
7654/// at `depth == 0` is the unsplit strip as a single transform unit and
7655/// beyond it the per-unit walk of [`depth_to_tx_wh`].
7656///
7657/// What is genuinely different from [`decode_block_rect`] is the mode
7658/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
7659/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
7660/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
7661/// intra-in-inter arm's own reads at the rect footprint, including its
7662/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
7663/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
7664/// square and this arm) and a nonzero luma angle delta refused by name.
7665///
7666/// The strip's own neighbour records (luma per transform unit, chroma, skip
7667/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
7668/// inter-side bands and the mi map.
7669#[allow(clippy::too_many_arguments)]
7670/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
7671/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
7672/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
7673/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
7674/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
7675/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
7676/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
7677/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
7678/// table here rather than a shift of `bw.min(bh)`.
7679fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
7680 Some(match (bw.min(bh), bw.max(bh)) {
7681 (8, 16) => (1usize, 1usize),
7682 (16, 32) => (2, 2),
7683 (32, 64) => (3, 3),
7684 (8, 32) => (1, 2),
7685 (16, 64) => (2, 3),
7686 _ => return None,
7687 })
7688}
7689
7690/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
7691/// block path"): the shapes that can reach that arm, enumerated against the
7692/// MEASURED domain of the inter block path
7693/// ([`INTER_BLOCK_SHAPES`], the census the gate
7694/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
7695/// fills from three real streams).
7696///
7697/// [`decode_intra_rect_in_inter`] is called from one site, under
7698/// `write_w != side || write_h != side`, and only after two earlier arms have
7699/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
7700/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
7701/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
7702/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
7703/// and each of those has a row, so the refusal names a shape no measured
7704/// stream can present.
7705#[test]
7706fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
7707 let mut checked = 0;
7708 for &(side, w, h) in &INTER_BLOCK_SHAPES {
7709 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
7710 continue;
7711 }
7712 assert!(
7713 intra_in_inter_size_row(w, h).is_some(),
7714 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
7715 the \"no size-group/tx-category row\" refusal"
7716 );
7717 checked += 1;
7718 }
7719 assert_eq!(
7720 checked, 10,
7721 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
7722 lookup, not the 10 this claim was measured over"
7723 );
7724}
7725
7726fn decode_intra_rect_in_inter(
7727 dec: &mut SymbolDecoder,
7728 cdfs: &mut Cdfs,
7729 neighbours: &mut Neighbours,
7730 at: (usize, usize),
7731 bw: usize,
7732 bh: usize,
7733 skip: bool,
7734 allow_screen_content_tools: bool,
7735 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
7736 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
7737 strip16: Option<(bool, bool)>,
7738 y: &mut PlaneBuf,
7739 u: &mut PlaneBuf,
7740 v: &mut PlaneBuf,
7741 base_q_idx: u8,
7742) -> Result<()> {
7743 // `at` is in MI units (the inter path's own unit since lane-inter4);
7744 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
7745 // below are still keyed by.
7746 let (mi_r, mi_c) = at;
7747 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
7748 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
7749 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
7750 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
7751 // finding -- the category is NOT the same for every strip size).
7752 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
7753 // it is refused by name rather than read from the wrong CDF row.
7754 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
7755 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
7756 // tx-depth category is 1 -- but nothing here has to know either, because
7757 // the strip decodes through the very body the KEY FRAME path proves for
7758 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
7759 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
7760 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
7761 // inter-frame difference is the mode-info read, which
7762 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
7763 // `y_mode[0]` plus the `skip` this caller already read.
7764 if let Some((horz, has_chroma)) = strip16 {
7765 // lane-t900 r22: the screen-content refusal here was STALE (class
7766 // stale-premise): [`decode_rect4_16_strip`] takes
7767 // `allow_screen_content_tools` and reads the whole palette syntax
7768 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
7769 // pair) -- the key frame proves that body. Lifted with the 10-bit
7770 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
7771 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
7772 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
7773 INTRA_IN_INTER_MODE.with(|c| c.set(Some((0, skip))));
7774 let res = decode_rect4_16_strip(
7775 dec,
7776 cdfs,
7777 neighbours,
7778 (mi_r, mi_c),
7779 horz,
7780 has_chroma,
7781 // The inter strips of the same partition publish their own
7782 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
7783 // has nothing to add here.
7784 None,
7785 y,
7786 u,
7787 v,
7788 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
7789 allow_screen_content_tools,
7790 base_q_idx,
7791 TX_SELECT_INTER.with(std::cell::Cell::get),
7792 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
7793 );
7794 INTRA_IN_INTER_MODE.with(|c| c.set(None));
7795 let (mode, uv, (tx_w, tx_h)) = res?;
7796 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
7797 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
7798 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
7799 // block of an inter frame, intra ones included, and
7800 // `txfm_partition_update` for the var-tx context. The key-frame body
7801 // writes neither (a key frame has no var-tx tree and its own readers
7802 // use the deblock grid), so the block AFTER this strip read a stale
7803 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
7804 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
7805 // 16x16 row.
7806 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
7807 for i in 0..bw / MI {
7808 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
7809 *cell = tx_w as u8;
7810 }
7811 }
7812 for i in 0..bh / MI {
7813 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
7814 *cell = tx_h as u8;
7815 }
7816 }
7817 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
7818 // coarse 16-px cell holds one entry for the whole 16x16 and the last
7819 // block to write it wins).
7820 neighbours.above_mode[c] = mode;
7821 neighbours.left_mode[r] = mode;
7822 if let Some(uvm) = uv {
7823 neighbours.above_uv_mode[c] = uvm;
7824 neighbours.left_uv_mode[r] = uvm;
7825 }
7826 neighbours.above_side[c] = bw;
7827 neighbours.left_side[r] = bh;
7828 if crate::envflags::env_flag!("EC_INTRA16X4") {
7829 eprintln!(
7830 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
7831 mi_c * MI,
7832 mi_r * MI
7833 );
7834 }
7835 INTRA16X4_IN_INTER_HITS.with(|h| {
7836 let mut v = h.get();
7837 v[usize::from(!horz)] += 1;
7838 v[2] += usize::from(has_chroma);
7839 h.set(v);
7840 });
7841 return Ok(());
7842 }
7843 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
7844 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
7845 // puts BLOCK_128X64/64X128/128X128 in group 3 and
7846 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
7847 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
7848 // block decodes through the very body the KEY FRAME path proves for this
7849 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
7850 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
7851 // `Reach` rule and the frame-edge write clip). The only inter-frame
7852 // differences live inside that body: the mode-info read
7853 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
7854 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
7855 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
7856 // palette (>64) do not exist at this size and are refused by name there.
7857 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
7858 // `intra128_in_inter_witness2.obu` (gate
7859 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
7860 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
7861 // all 15 frames, so the hits are counted out of exact frames (class
7862 // `counter-from-refused-stream`). What r16/r17 could not find, and what
7863 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
7864 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
7865 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
7866 // where the frame EDGE forces it: a partial last superblock row has
7867 // `has_rows128 == false`, so the 128x64 top half is implied, and a
7868 // partial last column implies the 64x128 left half. Put content no
7869 // reference holds (a fresh smooth ramp) in exactly those two bands of an
7870 // inter frame and the encoder codes those forced halves INTRA.
7871 if bw.max(bh) == 128 {
7872 if allow_screen_content_tools {
7873 return Err(unsupported(
7874 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
7875 is consumed for square blocks only)",
7876 ));
7877 }
7878 if coeff_trace_on() {
7879 // lane-t900 r16: which decode-order frame this arm fires in --
7880 // interleaved with the `EC_COEFF_FRAME` markers, this is what
7881 // proves the hit is counted out of a frame that compares exact
7882 // (class `counter-from-refused-stream`).
7883 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
7884 }
7885 INTRA_IN_INTER_MODE.with(|c| c.set(Some((3, skip))));
7886 let res = decode_block_128rect(
7887 dec,
7888 cdfs,
7889 neighbours,
7890 (r, c),
7891 bw,
7892 bh,
7893 y,
7894 u,
7895 v,
7896 base_q_idx,
7897 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
7898 allow_screen_content_tools,
7899 TX_SELECT_INTER.with(std::cell::Cell::get),
7900 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
7901 );
7902 INTRA_IN_INTER_MODE.with(|c| c.set(None));
7903 return res;
7904 }
7905 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
7906 if crate::envflags::env_flag!("EC_OBMCREC") {
7907 eprintln!(
7908 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
7909 );
7910 }
7911 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
7912 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
7913 // can arrive here are enumerated against the measured block-shape
7914 // census ([`INTER_BLOCK_SHAPES`]) by
7915 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
7916 // -- every one of them has a row, so this arm names a shape no stream
7917 // has been able to present.
7918 return Err(unsupported(format!(
7919 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
7920 )));
7921 };
7922 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
7923 // screen-content frame ("palette syntax is consumed for square blocks
7924 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
7925 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
7926 // it, while the 2:1 reader inlined further down now codes the same syntax
7927 // itself. A real `--tune-content=screen` inter stream reached this refusal
7928 // on 8x16 / 16x8 strips (gate
7929 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
7930 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
7931 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
7932 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
7933 // luma/chroma transform tables, the per-unit split walk and the strip's
7934 // own neighbour records). The ONLY difference on an inter frame is the
7935 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
7936 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
7937 // this caller already read. `tx_cat` above is the same category those
7938 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
7939 // `decode_block_rect64`), asserted here so a future shape cannot drift.
7940 if bw.max(bh) == 4 * bw.min(bh) {
7941 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
7942 INTRA_IN_INTER_MODE.with(|c| c.set(Some((size_group, skip))));
7943 let res = if bw.max(bh) == 64 {
7944 decode_block_rect64(
7945 dec,
7946 cdfs,
7947 neighbours,
7948 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
7949 bw,
7950 bh,
7951 y,
7952 u,
7953 v,
7954 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
7955 allow_screen_content_tools,
7956 base_q_idx,
7957 TX_SELECT_INTER.with(std::cell::Cell::get),
7958 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
7959 )
7960 } else {
7961 decode_block_rect4(
7962 dec,
7963 cdfs,
7964 neighbours,
7965 (mi_r, mi_c),
7966 bw,
7967 bh,
7968 None,
7969 y,
7970 u,
7971 v,
7972 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
7973 allow_screen_content_tools,
7974 base_q_idx,
7975 TX_SELECT_INTER.with(std::cell::Cell::get),
7976 )
7977 .map(|_| ())
7978 };
7979 INTRA_IN_INTER_MODE.with(|c| c.set(None));
7980 res?;
7981 let shape = match (bw, bh) {
7982 (64, 16) => 0,
7983 (16, 64) => 1,
7984 (32, 8) => 2,
7985 _ => 3,
7986 };
7987 INTRA_RECT4_IN_INTER_HITS.with(|h| {
7988 let mut v = h.get();
7989 v[shape] += 1;
7990 h.set(v);
7991 });
7992 return Ok(());
7993 }
7994 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
7995 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
7996 // own, so a cross-decoder bisection could only see the block's first
7997 // coefficient. Same names/format as [`read_tx_size`]'s rung.
7998 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
7999 if step_trace {
8000 eprintln!(
8001 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
8002 dec.debug_state().0
8003 );
8004 }
8005 if mode >= 13 {
8006 return Err(unsupported(
8007 "an intra mode this decoder does not code (round 2)",
8008 ));
8009 }
8010 // lane-angleinter (merged on main for the square intra-in-inter arm):
8011 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
8012 // directional predictor; this arm refused a nonzero one before the merge.
8013 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
8014 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
8015 } else {
8016 0
8017 };
8018 if angle_delta_y != 0 {
8019 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1));
8020 }
8021 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
8022 // superblock-level strip reads the no-CFL alphabet -- the same split
8023 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
8024 let cfl_allowed = bw.max(bh) <= 32;
8025 let uv_mode = if cfl_allowed {
8026 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
8027 } else {
8028 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
8029 };
8030 if step_trace {
8031 eprintln!(
8032 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
8033 u8::from(cfl_allowed),
8034 dec.debug_state().0
8035 );
8036 }
8037 if (9..=12).contains(&uv_mode) {
8038 SMOOTH_UV_HITS.with(|h| h.set(h.get() + 1));
8039 }
8040 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
8041 Some(read_cfl_alphas(dec, cdfs))
8042 } else {
8043 None
8044 };
8045 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8046 DC_PRED
8047 } else {
8048 uv_mode
8049 };
8050 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
8051 DIRECTIONAL_UV_HITS.with(|h| h.set(h.get() + 1));
8052 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
8053 } else {
8054 0
8055 };
8056 if angle_delta_uv != 0 {
8057 UV_ANGLE_DELTA_HITS.with(|h| h.set(h.get() + 1));
8058 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|h| h.set(h.get() + 1));
8059 }
8060 // `read_palette_mode_info` (spec 5.11.13), in the position
8061 // `read_intra_block_mode_info` writes it: after the chroma mode and
8062 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
8063 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
8064 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
8065 // skipping the syntax here desynced the tile at the strip's own symbol.
8066 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
8067 // context and colour cache at its own mi position, and the two
8068 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
8069 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
8070 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
8071 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
8072 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
8073 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
8074 if allow_screen_content_tools
8075 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
8076 {
8077 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(c.get() + 1));
8078 let use_palette_y =
8079 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
8080 if use_palette_y {
8081 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
8082 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache)));
8083 }
8084 // A 2:1 strip of at least 8x8 is always a chroma reference, so
8085 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
8086 let use_palette_uv =
8087 uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
8088 if crate::envflags::env_flag!("EC_PALSYN") {
8089 eprintln!("EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", use_palette_y as i32, use_palette_uv as i32, dec.debug_state().0);
8090 }
8091 if use_palette_uv {
8092 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
8093 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache);
8094 palette_uv_pending = Some((n, u_colors, v_colors));
8095 }
8096 }
8097 // lane-fiinter (merged on main for the square intra-in-inter arm):
8098 // `read_filter_intra_mode_info` is the tail of
8099 // `read_intra_block_mode_info`, after the palette syntax (refused whole
8100 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
8101 // 2:1 strips with both sides <= 32 -- their own CDF rows
8102 // ([`filter_intra_size_class_rect`]).
8103 let mut filter_intra = None;
8104 if mode == DC_PRED
8105 && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
8106 // `av1_filter_intra_allowed` excludes a palette-Y block.
8107 && palette_y_pending.is_none()
8108 && let Some(class) = filter_intra_size_class_rect(bw, bh)
8109 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
8110 {
8111 FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1));
8112 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1));
8113 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
8114 }
8115 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
8116 let palette_y = palette_y_pending.map(|(n, colors)| {
8117 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
8118 PALETTE_HITS.with(|c| c.set(c.get() + 1));
8119 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
8120 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.set(c.get() + 1));
8121 PaletteY { size: n, colors, map }
8122 });
8123 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
8124 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
8125 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
8126 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
8127 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
8128 PaletteUv { size: n, u_colors, v_colors, map }
8129 });
8130 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
8131 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
8132 // chroma ones -- [`decode_block_rect`]'s own pair.
8133 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
8134 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
8135 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
8136 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
8137 // one exactly as [`decode_leaf8`] already does (class
8138 // context-read-from-one-cell).
8139 let coarse_pair = neighbours.modes_above_left(r, c);
8140 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
8141 if (nb_above_mode, nb_left_mode) != coarse_pair {
8142 EDGE_FILTER_MI_FIX_HITS.with(|c| c.set(c.get() + 1));
8143 }
8144 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
8145 if smooth_neighbor {
8146 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
8147 }
8148 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
8149 let depth = if TX_SELECT_INTER.with(std::cell::Cell::get) {
8150 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
8151 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].
8152 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64));
8153 let d = match tx_cat {
8154 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
8155 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
8156 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
8157 };
8158 if step_trace {
8159 eprintln!(
8160 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
8161 dec.debug_state().0
8162 );
8163 }
8164 d
8165 } else {
8166 0
8167 };
8168 if depth != 0 {
8169 TX_DEPTH_HITS.with(|h| h.set(h.get() + 1));
8170 // lane-intrasplit r1: a split intra strip in an inter frame walks the
8171 // key frame's own per-TU path ([`decode_rect_split`] below); what was
8172 // wrong when this refusal was written was the depth SYMBOL, not the walk.
8173 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
8174 let mut v = h.get();
8175 v[depth.min(2)] += 1;
8176 h.set(v);
8177 });
8178 }
8179 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
8180 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
8181 // the two are indistinguishable when the diagnostic fires on splits alone.
8182 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
8183 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
8184 }
8185 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
8186 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
8187 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
8188 // of an inter frame, intra ones included -- with the skip term 0 it
8189 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
8190 // and `left_txfm_context` to `tx_size_high` over its height. This strip
8191 // wrote neither, so the next block's var-tx `txfm_partition` context read
8192 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
8193 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
8194 // mi(16,0) and desyncing the tile at that symbol.
8195 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
8196 let modes = RectStripModes {
8197 skip,
8198 mode,
8199 angle_delta_y,
8200 uv_predict_mode,
8201 angle_delta_uv,
8202 alpha,
8203 filter_intra,
8204 smooth_neighbor,
8205 smooth_neighbor_uv,
8206 palette_y: palette_y
8207 .as_ref()
8208 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
8209 palette_uv: palette_uv.as_ref().map(|p| {
8210 (
8211 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
8212 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
8213 )
8214 }),
8215 };
8216 decode_rect_split(
8217 dec,
8218 cdfs,
8219 neighbours,
8220 (mi_r, mi_c),
8221 bw,
8222 bh,
8223 tx_w,
8224 tx_h,
8225 &modes,
8226 y,
8227 u,
8228 v,
8229 base_q_idx,
8230 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
8231 )?;
8232 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
8233 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
8234 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
8235 // left column over its height. This arm wrote neither before lane-intrasplit
8236 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
8237 // context across the strip's footprint.
8238 for i in 0..bw / MI {
8239 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
8240 *cell = tx_w as u8;
8241 }
8242 }
8243 for i in 0..bh / MI {
8244 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
8245 *cell = tx_h as u8;
8246 }
8247 }
8248 // The strip's own palette state into the mi-granular neighbour bands, so
8249 // the next block's colour cache and `palette_y_mode` context are libaom's.
8250 record_strip_palette(
8251 neighbours,
8252 (mi_r, mi_c),
8253 bw,
8254 bh,
8255 palette_y.as_ref().map_or(0, |p| p.size),
8256 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
8257 palette_uv.as_ref().map_or(0, |p| p.size),
8258 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
8259 );
8260 let class = match bw.max(bh) {
8261 64 => 0,
8262 32 => 1,
8263 _ => 2,
8264 };
8265 INTRA_RECT_IN_INTER_HITS.with(|h| {
8266 let mut v = h.get();
8267 v[class] += 1;
8268 h.set(v);
8269 });
8270 Ok(())
8271}
8272
8273/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
8274/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
8275/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
8276/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
8277/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
8278/// has no rectangular-transform coefficient reader, and a chroma plane here
8279/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
8280/// with no depth-based square-tiling escape the way luma's own resolved
8281/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
8282/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
8283#[allow(clippy::too_many_arguments)]
8284fn decode_block_rect(
8285 dec: &mut SymbolDecoder,
8286 cdfs: &mut Cdfs,
8287 neighbours: &mut Neighbours,
8288 at: (usize, usize),
8289 bw: usize,
8290 bh: usize,
8291 y: &mut PlaneBuf,
8292 u: &mut PlaneBuf,
8293 v: &mut PlaneBuf,
8294 enable_filter_intra: bool,
8295 allow_screen_content_tools: bool,
8296 base_q_idx: u8,
8297 tx_select: bool,
8298 reduced_tx_set: bool,
8299) -> Result<()> {
8300 let (r, c) = at;
8301 let (px, py) = (c * SUB, r * SUB);
8302 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
8303 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
8304 let palette_uv_cache = neighbours.palette_uv_cache(at);
8305 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
8306 read_intra_mode_rect(
8307 dec,
8308 cdfs,
8309 nb_above_mode,
8310 nb_left_mode,
8311 true,
8312 true,
8313 bw,
8314 bh,
8315 enable_filter_intra,
8316 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
8317 allow_screen_content_tools,
8318 Some((palette_ctx, &palette_cache)),
8319 &palette_uv_cache,
8320 r * (SUB / MI),
8321 c * (SUB / MI),
8322 )?;
8323 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
8324 if smooth_neighbor {
8325 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8326 }
8327 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
8328 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
8329 // `uv_mode`, not the luma one.
8330 let smooth_neighbor_uv =
8331 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
8332 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
8333 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
8334 // rectangle just as happily), so a `use_filter_intra` strip at this level
8335 // predicts instead of refusing. The below-16x16 leaf arm
8336 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
8337 if filter_intra.is_some() {
8338 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
8339 }
8340 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8341 DC_PRED
8342 } else {
8343 uv_mode
8344 };
8345 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8346 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
8347 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
8348 // one did not, so with `--enable-tx-size-search=0` -- which several gate
8349 // recipes use -- the decoder consumed a symbol the encoder never wrote and
8350 // desynced the tile from that point on. That is why both strips of the
8351 // pinned HORZ quadrant were wrong from their very first pixel, and why our
8352 // range after the read equalled the oracle's range for the whole block.
8353 let depth = if tx_select {
8354 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
8355 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
8356 // the 16x4 intra-in-inter strips already do); the key frame's
8357 // deblock-grid approximation is only right where those bands were never
8358 // written. Measured on the 10-bit 1920x792 128-superblock stream,
8359 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
8360 // `tx_size_cat2` row 1 where libaom reads row 2.
8361 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
8362 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
8363 } else {
8364 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
8365 };
8366 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
8367 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
8368 eprintln!(
8369 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
8370 dec.debug_state().0
8371 );
8372 }
8373 d
8374 } else {
8375 0
8376 };
8377 if depth != 0 {
8378 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8379 // lane-rectsplit r1: a split transform is predicted and reconstructed
8380 // per transform unit, each unit taking its edges from the previous
8381 // unit's reconstruction inside this same strip (spec 5.11.36) --
8382 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
8383 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
8384 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
8385 eprintln!(
8386 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
8387 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
8388 angle_y={angle_delta_y}"
8389 );
8390 }
8391 let modes = RectStripModes {
8392 skip,
8393 mode,
8394 angle_delta_y,
8395 uv_predict_mode,
8396 angle_delta_uv,
8397 alpha,
8398 filter_intra,
8399 smooth_neighbor,
8400 smooth_neighbor_uv,
8401 palette_y: palette_y
8402 .as_ref()
8403 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
8404 palette_uv: palette_uv.as_ref().map(|p| {
8405 (
8406 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
8407 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
8408 )
8409 }),
8410 };
8411 if palette_y.is_some() || palette_uv.is_some() {
8412 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8413 }
8414 decode_rect_split(
8415 dec,
8416 cdfs,
8417 neighbours,
8418 (mi_r, mi_c),
8419 bw,
8420 bh,
8421 tx_w,
8422 tx_h,
8423 &modes,
8424 y,
8425 u,
8426 v,
8427 base_q_idx,
8428 reduced_tx_set,
8429 )?;
8430 // This early return skips this fn's own tail, so the palette
8431 // neighbour state has to be stamped HERE too: without it a split-tx
8432 // strip left the above/left palette arrays holding a DEAD block's
8433 // colours, and the next block's colour cache
8434 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
8435 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
8436 // and only those pixels were wrong (lane-palette2 r10).
8437 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8438 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
8439 let (puv_size, puv_colors) =
8440 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8441 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
8442 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
8443 return Ok(());
8444 }
8445 let (tx_w, tx_h) = (bw, bh);
8446 let (cpx, cpy) = (px / 2, py / 2);
8447 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
8448 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8449 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8450 let (rng, _) = dec.debug_state();
8451 eprintln!(
8452 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
8453 skip={} tx={depth} rng={rng}",
8454 skip as i32
8455 );
8456 }
8457 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
8458 // block's prediction is the reconstructed colour-index map, set fresh
8459 // right before each `reconstruct_rect` call below (lane-palette2 r4).
8460 if let Some(ref pyv) = palette_y {
8461 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
8462 set_palette_pred(buf);
8463 }
8464 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
8465 (
8466 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
8467 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
8468 )
8469 });
8470 if skip {
8471 y.reconstruct_rect(
8472 px,
8473 py,
8474 bw,
8475 bh,
8476 mode,
8477 angle_delta_y,
8478 reach,
8479 &vec![0i32; bw * bh],
8480 None,
8481 filter_intra,
8482 smooth_neighbor,
8483 );
8484 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8485 if let Some((ub, _)) = &palette_uv_bufs {
8486 set_palette_pred(ub.clone());
8487 }
8488 u.reconstruct_rect(
8489 cpx,
8490 cpy,
8491 chroma_w,
8492 chroma_h,
8493 uv_predict_mode,
8494 angle_delta_uv,
8495 reach,
8496 &vec![0i32; chroma_w * chroma_h],
8497 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8498 None,
8499 smooth_neighbor_uv,
8500 );
8501 if let Some((_, vb)) = &palette_uv_bufs {
8502 set_palette_pred(vb.clone());
8503 }
8504 v.reconstruct_rect(
8505 cpx,
8506 cpy,
8507 chroma_w,
8508 chroma_h,
8509 uv_predict_mode,
8510 angle_delta_uv,
8511 reach,
8512 &vec![0i32; chroma_w * chroma_h],
8513 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8514 None,
8515 smooth_neighbor_uv,
8516 );
8517 neighbours.record_rect(
8518 at,
8519 bw,
8520 bh,
8521 mode,
8522 uv_predict_mode,
8523 &[
8524 vec![0i32; bw * bh],
8525 vec![0i32; chroma_w * chroma_h],
8526 vec![0i32; chroma_w * chroma_h],
8527 ],
8528 );
8529 } else {
8530 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
8531 // reduces both size pairs to their square-up CDF sets
8532 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
8533 // doc comments); the scan order and 2D context tables are the real
8534 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
8535 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
8536 (&SCAN_32X16, &SCAN_16X8)
8537 } else {
8538 (&SCAN_16X32, &SCAN_8X16)
8539 };
8540 // lane-rectwire r3: real coefficients desync a pixel-exact gate
8541 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
8542 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
8543 // pixel (not a subtle context-table off-by-one), while the sibling
8544 // non-rect quadrants of the same frame match. Range-ladder bisection
8545 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
8546 // but the intra key-frame path has no traced symbol between the
8547 // partition read and the first coefficient block (mode/skip/tx_depth
8548 // reads are all untraced in libaom's decodeframe.c intra path, unlike
8549 // the inter EC_TRACE_MODE this round added), so a same-length range
8550 // comparison wasn't reachable within budget -- see
8551 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
8552 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
8553 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
8554 // libaom and match). lane-rectwire r4: range-ladder against the
8555 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
8556 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
8557 // both confirmed in sync -- rng=58692 on both sides right after
8558 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
8559 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
8560 // immediately after: ours moves rng 58692 -> 43570, which cannot be
8561 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
8562 // its own tx_size read) unless oracle's tx symbol is a near-certainty
8563 // CDF that barely narrows the range -- i.e. this decoder's
8564 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
8565 // a 32x16/16x32 strip is the first diverging symbol, not the
8566 // coefficient-context math r3 already cleared. Not confirmed byte-
8567 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
8568 // `read_tx_size`'s own rng, not attempted this round -- budget), so
8569 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
8570 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
8571 // it unconditionally where both square paths gate on `tx_select`. With
8572 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
8573 // decoder consumed one that was never there.
8574 {
8575 let around = neighbours.around_rect(at, bw, bh);
8576 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
8577 let (luma_levels, luma_tx_type) = read_coeffs_rect(
8578 dec,
8579 &mut luma_coding,
8580 luma_scan,
8581 bw,
8582 bh,
8583 0,
8584 dc_sign_ctx(around[0].2),
8585 TxType::DctDct,
8586 )?;
8587 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8588 let (rng, _) = dec.debug_state();
8589 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
8590 }
8591 let luma_residual = dequant_and_inverse_typed_wh(
8592 &luma_levels,
8593 bw,
8594 bh,
8595 crate::decode::bit_depth(),
8596 block_q_idx(),
8597 plane_q_delta(0).0,
8598 plane_q_delta(0).1,
8599 luma_tx_type,
8600 );
8601 y.reconstruct_rect(
8602 px,
8603 py,
8604 bw,
8605 bh,
8606 mode,
8607 angle_delta_y,
8608 reach,
8609 &luma_residual,
8610 None,
8611 filter_intra,
8612 smooth_neighbor,
8613 );
8614 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8615 if let Some((ub, _)) = &palette_uv_bufs {
8616 set_palette_pred(ub.clone());
8617 }
8618 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
8619 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
8620 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
8621 let (u_levels, u_tx_type) = read_coeffs_rect(
8622 dec,
8623 &mut u_coding,
8624 chroma_scan,
8625 chroma_w,
8626 chroma_h,
8627 u_skip_ctx,
8628 dc_sign_ctx(around[1].2),
8629 u_default_tx,
8630 )?;
8631 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8632 let (rng, _) = dec.debug_state();
8633 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
8634 }
8635 let u_residual = dequant_and_inverse_typed_wh(
8636 &u_levels,
8637 chroma_w,
8638 chroma_h,
8639 crate::decode::bit_depth(),
8640 block_q_idx(),
8641 plane_q_delta(1).0,
8642 plane_q_delta(1).1,
8643 u_tx_type,
8644 );
8645 u.reconstruct_rect(
8646 cpx,
8647 cpy,
8648 chroma_w,
8649 chroma_h,
8650 uv_predict_mode,
8651 angle_delta_uv,
8652 reach,
8653 &u_residual,
8654 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8655 None,
8656 smooth_neighbor_uv,
8657 );
8658 if let Some((_, vb)) = &palette_uv_bufs {
8659 set_palette_pred(vb.clone());
8660 }
8661 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
8662 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
8663 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
8664 let (v_levels, v_tx_type) = read_coeffs_rect(
8665 dec,
8666 &mut v_coding,
8667 chroma_scan,
8668 chroma_w,
8669 chroma_h,
8670 v_skip_ctx,
8671 dc_sign_ctx(around[2].2),
8672 v_default_tx,
8673 )?;
8674 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8675 let (rng, _) = dec.debug_state();
8676 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
8677 }
8678 let v_residual = dequant_and_inverse_typed_wh(
8679 &v_levels,
8680 chroma_w,
8681 chroma_h,
8682 crate::decode::bit_depth(),
8683 block_q_idx(),
8684 plane_q_delta(2).0,
8685 plane_q_delta(2).1,
8686 v_tx_type,
8687 );
8688 v.reconstruct_rect(
8689 cpx,
8690 cpy,
8691 chroma_w,
8692 chroma_h,
8693 uv_predict_mode,
8694 angle_delta_uv,
8695 reach,
8696 &v_residual,
8697 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8698 None,
8699 smooth_neighbor_uv,
8700 );
8701 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
8702 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
8703 }
8704 }
8705 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8706 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
8707 let (puv_size, puv_colors) =
8708 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8709 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
8710 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
8711 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
8712 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
8713 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8714 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
8715 }
8716 Ok(())
8717}
8718
8719/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
8720/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
8721/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
8722/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
8723/// the second strip of a HORZ/VERT split sits offset by half the 16x16
8724/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
8725/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
8726/// previous strip is directly above (same column, `mi_h` rows up) or
8727/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
8728/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
8729/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
8730/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
8731/// this strip's real position, never the coarse `record_rect` (which the
8732/// caller uses once, after both strips, exactly like the `VERT_B` arm next
8733/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
8734/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
8735/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
8736/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
8737#[allow(clippy::too_many_arguments)]
8738fn decode_leaf_rect(
8739 dec: &mut SymbolDecoder,
8740 cdfs: &mut Cdfs,
8741 neighbours: &mut Neighbours,
8742 outer_at: (usize, usize),
8743 leaf_mi: (usize, usize),
8744 bw: usize,
8745 bh: usize,
8746 prev_leaf: Option<((usize, usize), usize)>,
8747 y: &mut PlaneBuf,
8748 u: &mut PlaneBuf,
8749 v: &mut PlaneBuf,
8750 enable_filter_intra: bool,
8751 allow_screen_content_tools: bool,
8752 base_q_idx: u8,
8753 tx_select: bool,
8754 reduced_tx_set: bool,
8755) -> Result<usize> {
8756 let _ = base_q_idx;
8757 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
8758 eprintln!(
8759 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
8760 dec.debug_state().0
8761 );
8762 }
8763 let (r, c) = outer_at;
8764 let mut above_mode = neighbours.above_mode[c];
8765 let mut left_mode = neighbours.left_mode[r];
8766 let (mi_w, mi_h) = (bw / MI, bh / MI);
8767 if let Some(((pr, pc), pmode)) = prev_leaf {
8768 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
8769 above_mode = pmode;
8770 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
8771 left_mode = pmode;
8772 }
8773 }
8774 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
8775 // cannot hold the modes a split (or a pair of strips) leaves behind, so
8776 // when the map holds the block at exactly this strip's above/left mi it
8777 // is the neighbour libaom's `above_mi`/`left_mi` reads.
8778 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
8779 // availability-correct -- four 16x8 strips share one coarse 16x16
8780 // `left_mode` cell too, so the fallback must not stand in for an absent
8781 // tile-edge neighbour.
8782 let (above_mode, left_mode) =
8783 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
8784 let smooth_neighbor =
8785 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
8786 if smooth_neighbor {
8787 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8788 }
8789 // The palette-Y mode CDF row is picked by the neighbours' palette use
8790 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
8791 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
8792 // a palette narrows the wrong interval and desyncs the tile even when the
8793 // decoded bit is the same. The cell is the 16px-SUB cell containing the
8794 // leaf (the palette neighbour arrays have no finer granularity).
8795 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
8796 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
8797 // exclusion and the neighbour palette lookup itself are mi-granular
8798 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
8799 let pal_at = leaf_mi;
8800 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
8801 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
8802 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
8803 read_intra_mode_rect(
8804 dec,
8805 cdfs,
8806 above_mode,
8807 left_mode,
8808 true,
8809 true,
8810 bw,
8811 bh,
8812 enable_filter_intra,
8813 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
8814 allow_screen_content_tools,
8815 Some((palette_ctx, &palette_cache)),
8816 &palette_uv_cache,
8817 leaf_mi.0,
8818 leaf_mi.1,
8819 )?;
8820 // lane-kf900 r4: palette prediction on this shape, the same colour-index
8821 // map -> base colours buffer [`decode_block_rect`] hands each
8822 // `reconstruct_rect` through [`set_palette_pred`].
8823 if palette_y.is_some() || palette_uv.is_some() {
8824 RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1));
8825 }
8826 let palette_y_buf: Option<Vec<u16>> = palette_y
8827 .as_ref()
8828 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
8829 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
8830 (
8831 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
8832 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
8833 )
8834 });
8835 let (pal_y_size, pal_y_colors) =
8836 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8837 let (pal_uv_size, pal_uv_colors) =
8838 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8839 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
8840 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
8841 }
8842 if filter_intra.is_some() {
8843 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
8844 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
8845 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
8846 // below already makes; this refusal was square-only prose.
8847 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
8848 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.set(c.get() + 1));
8849 }
8850 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
8851 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
8852 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
8853 // a constant `false`.
8854 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
8855 let depth = if tx_select {
8856 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
8857 // every other rect reader now does -- a no-op on a key frame.
8858 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
8859 tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh)
8860 } else {
8861 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
8862 };
8863 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
8864 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
8865 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
8866 // count (3), different CDF row: a wrong-table read of a real symbol,
8867 // the class that cost lane-rectsplit r1 its 64x32 depth.
8868 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
8869 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
8870 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
8871 // function also decodes) sit at depth 2, so they read
8872 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
8873 // while `tx_size_cat2` belongs to the 32-level shapes
8874 // ([`decode_block_rect`]). Both tables carry three symbols, so the
8875 // wrong one decodes a plausible depth from the wrong probabilities:
8876 // the range diverges silently at the first such leaf and every later
8877 // symbol in the tile is read from the wrong place (class
8878 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
8879 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
8880 } else {
8881 0
8882 };
8883 if depth != 0 {
8884 // The same per-transform-unit walk the bigger strips take
8885 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
8886 // depth 2), addressed at this leaf's own mi position.
8887 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8888 SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
8889 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
8890 let modes = RectStripModes {
8891 skip,
8892 mode,
8893 angle_delta_y,
8894 uv_predict_mode,
8895 angle_delta_uv,
8896 alpha,
8897 filter_intra,
8898 smooth_neighbor,
8899 // lane-rectsplitx r3: the split arm hard-coded `false` here while
8900 // the unsplit arm below passes the real neighbour answer -- chroma
8901 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
8902 smooth_neighbor_uv,
8903 palette_y: palette_y_buf.clone(),
8904 palette_uv: palette_uv_bufs.clone(),
8905 };
8906 if palette_y.is_some() || palette_uv.is_some() {
8907 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8908 }
8909 decode_rect_split(
8910 dec,
8911 cdfs,
8912 neighbours,
8913 leaf_mi,
8914 bw,
8915 bh,
8916 tx_w,
8917 tx_h,
8918 &modes,
8919 y,
8920 u,
8921 v,
8922 base_q_idx,
8923 reduced_tx_set,
8924 )?;
8925 record_strip_palette(
8926 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
8927 );
8928 return Ok(mode);
8929 }
8930 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8931 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8932 let (cpx, cpy) = (px / 2, py / 2);
8933 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
8934 let (luma_levels, u_levels, v_levels);
8935 if skip {
8936 luma_levels = vec![0i32; bw * bh];
8937 u_levels = vec![0i32; chroma_w * chroma_h];
8938 v_levels = vec![0i32; chroma_w * chroma_h];
8939 if let Some(b) = &palette_y_buf {
8940 set_palette_pred(b.clone());
8941 }
8942 y.reconstruct_rect(
8943 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
8944 smooth_neighbor,
8945 );
8946 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8947 if let Some((ub, _)) = &palette_uv_bufs {
8948 set_palette_pred(ub.clone());
8949 }
8950 u.reconstruct_rect(
8951 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
8952 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
8953 );
8954 if let Some((_, vb)) = &palette_uv_bufs {
8955 set_palette_pred(vb.clone());
8956 }
8957 v.reconstruct_rect(
8958 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
8959 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
8960 );
8961 } else {
8962 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
8963 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
8964 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
8965 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
8966 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
8967 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
8968 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
8969 (&SCAN_16X8, &SCAN_8X4)
8970 } else {
8971 (&SCAN_8X16, &SCAN_4X8)
8972 };
8973 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
8974 let luma_set = if reduced_tx_set {
8975 TxbSet::LumaRect16x8
8976 } else {
8977 TxbSet::LumaRect16x8Set1
8978 };
8979 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
8980 let (l_levels, luma_tx_type) = read_coeffs_rect(
8981 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
8982 )?;
8983 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
8984 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
8985 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
8986 }
8987 luma_levels = l_levels;
8988 let luma_residual = dequant_and_inverse_typed_wh(
8989 &luma_levels, bw, bh, crate::decode::bit_depth(),
8990 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,
8991 );
8992 if let Some(b) = &palette_y_buf {
8993 set_palette_pred(b.clone());
8994 }
8995 y.reconstruct_rect(
8996 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
8997 smooth_neighbor,
8998 );
8999 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9000 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
9001 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
9002 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
9003 let (u_l, u_tx_type) = read_coeffs_rect(
9004 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
9005 dc_sign_ctx(around[1].2), u_default_tx,
9006 )?;
9007 u_levels = u_l;
9008 let u_residual = dequant_and_inverse_typed_wh(
9009 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
9010 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,
9011 );
9012 if let Some((ub, _)) = &palette_uv_bufs {
9013 set_palette_pred(ub.clone());
9014 }
9015 u.reconstruct_rect(
9016 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
9017 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
9018 );
9019 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
9020 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
9021 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
9022 let (v_l, v_tx_type) = read_coeffs_rect(
9023 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
9024 dc_sign_ctx(around[2].2), v_default_tx,
9025 )?;
9026 v_levels = v_l;
9027 let v_residual = dequant_and_inverse_typed_wh(
9028 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
9029 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,
9030 );
9031 if let Some((_, vb)) = &palette_uv_bufs {
9032 set_palette_pred(vb.clone());
9033 }
9034 v.reconstruct_rect(
9035 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
9036 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
9037 );
9038 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
9039 }
9040 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
9041 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
9042 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
9043 // The leaf's own palette state (`0` clears, as this site always did
9044 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
9045 // AXIS only until the pair's closing leaf: the coarse cell holds one
9046 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
9047 // real left neighbour leaf 1 reads (lane-kf900 r4).
9048 record_strip_palette(
9049 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
9050 );
9051 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
9052 // rows -- record the whole span, not one cell.
9053 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
9054 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
9055 Ok(mode)
9056}
9057
9058/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
9059/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
9060/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
9061/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
9062/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
9063/// strip's mode so this one's mode context sees its true above/left
9064/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
9065///
9066/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
9067/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
9068/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
9069/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
9070/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
9071/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
9072/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
9073///
9074/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
9075/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
9076/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
9077/// unexamined.
9078#[allow(clippy::too_many_arguments)]
9079fn decode_block_rect4(
9080 dec: &mut SymbolDecoder,
9081 cdfs: &mut Cdfs,
9082 neighbours: &mut Neighbours,
9083 strip_mi: (usize, usize),
9084 bw: usize,
9085 bh: usize,
9086 prev_strip: Option<((usize, usize), usize)>,
9087 y: &mut PlaneBuf,
9088 u: &mut PlaneBuf,
9089 v: &mut PlaneBuf,
9090 enable_filter_intra: bool,
9091 allow_screen_content_tools: bool,
9092 base_q_idx: u8,
9093 tx_select: bool,
9094) -> Result<(usize, usize)> {
9095 let _ = base_q_idx;
9096 let (mi_r, mi_c) = strip_mi;
9097 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
9098 let (mi_w, mi_h) = (bw / MI, bh / MI);
9099 let mut above_mode = neighbours.above_mode[c];
9100 let mut left_mode = neighbours.left_mode[r];
9101 if let Some(((pr, pc), pmode)) = prev_strip {
9102 if pc == mi_c && mi_r == pr + mi_h {
9103 above_mode = pmode;
9104 } else if pr == mi_r && mi_c == pc + mi_w {
9105 left_mode = pmode;
9106 }
9107 }
9108 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
9109 // availability-correct neighbour modes (see
9110 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
9111 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
9112 let (above_mode, left_mode) =
9113 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
9114 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
9115 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
9116 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
9117 // wrong interval, so a screen-content tile desynced at the first strip
9118 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
9119 let pal_at = (mi_r, mi_c);
9120 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
9121 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
9122 let (
9123 skip,
9124 mode,
9125 angle_delta_y,
9126 uv_mode,
9127 angle_delta_uv,
9128 alpha,
9129 filter_intra,
9130 palette_y,
9131 palette_uv,
9132 ) = read_intra_mode_rect(
9133 dec,
9134 cdfs,
9135 above_mode,
9136 left_mode,
9137 true,
9138 true,
9139 bw,
9140 bh,
9141 enable_filter_intra,
9142 neighbours.skip_txfm_ctx(mi_r, mi_c),
9143 allow_screen_content_tools,
9144 Some((palette_ctx, &palette_cache)),
9145 &palette_uv_cache,
9146 mi_r,
9147 mi_c,
9148 )?;
9149 // lane-kf900 r4: palette prediction on this shape, exactly as
9150 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
9151 // mapped through the base colours IS the prediction (it reads no edge
9152 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
9153 if palette_y.is_some() || palette_uv.is_some() {
9154 RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1));
9155 }
9156 let palette_y_buf: Option<Vec<u16>> = palette_y
9157 .as_ref()
9158 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
9159 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
9160 (
9161 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
9162 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
9163 )
9164 });
9165 let (pal_y_size, pal_y_colors) =
9166 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
9167 let (pal_uv_size, pal_uv_colors) =
9168 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
9169 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
9170 if smooth_neighbor {
9171 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
9172 }
9173 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
9174 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
9175 // `r * (SUB / MI)` names a different mi column and the chroma
9176 // edge-filter strength was read from the wrong neighbour (measured:
9177 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
9178 // with luma bit-exact).
9179 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
9180 if filter_intra.is_some() {
9181 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
9182 if bw > bh {
9183 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1));
9184 } else {
9185 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1));
9186 }
9187 }
9188 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
9189 DC_PRED
9190 } else {
9191 uv_mode
9192 };
9193 let depth = if tx_select {
9194 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
9195 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
9196 // the 16x4 intra-in-inter strips already do); the key frame's
9197 // deblock-grid approximation is only right where those bands were never
9198 // written. Measured on the 10-bit 1920x792 128-superblock stream,
9199 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
9200 // `tx_size_cat2` row 1 where libaom reads row 2.
9201 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
9202 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
9203 } else {
9204 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
9205 };
9206 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
9207 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
9208 eprintln!(
9209 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
9210 dec.debug_state().0
9211 );
9212 }
9213 d
9214 } else {
9215 0
9216 };
9217 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
9218 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
9219 publish_txfm_bands_if_in_inter(
9220 neighbours,
9221 (mi_r, mi_c),
9222 depth_to_tx_wh(bw, bh, depth),
9223 (bw, bh),
9224 );
9225 if depth != 0 {
9226 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
9227 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
9228 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
9229 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
9230 // both interleave in every real stream.
9231 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
9232 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
9233 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
9234 // predicted -- depth 1 fires FIRST in every attempt that splits at
9235 // all, so a depth-2-only lift could never be gated. The r1 mismatch
9236 // was never the rect unit: it was the neighbour MODE the strip reads
9237 // (see `modes_above_left_mi`).
9238 let which = if depth == 1 {
9239 &RECT4_SPLIT_DEPTH1_HITS
9240 } else {
9241 &RECT4_SPLIT_DEPTH2_HITS
9242 };
9243 which.with(|c| c.set(c.get() + 1));
9244 let modes = RectStripModes {
9245 skip,
9246 mode,
9247 angle_delta_y,
9248 uv_predict_mode,
9249 angle_delta_uv,
9250 alpha,
9251 filter_intra,
9252 smooth_neighbor,
9253 smooth_neighbor_uv,
9254 palette_y: palette_y_buf.clone(),
9255 palette_uv: palette_uv_bufs.clone(),
9256 };
9257 if palette_y.is_some() || palette_uv.is_some() {
9258 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
9259 }
9260 decode_rect_split(
9261 dec,
9262 cdfs,
9263 neighbours,
9264 (mi_r, mi_c),
9265 bw,
9266 bh,
9267 tx_w,
9268 tx_h,
9269 &modes,
9270 y,
9271 u,
9272 v,
9273 base_q_idx,
9274 false,
9275 )?;
9276 record_strip_palette(
9277 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
9278 pal_uv_colors,
9279 );
9280 if bw > bh {
9281 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
9282 } else {
9283 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
9284 }
9285 if !skip {
9286 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
9287 }
9288 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
9289 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
9290 // frame, so this 1:4 strip -- which is also the INTER frame's reader
9291 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
9292 // transform size in both TXFM_CONTEXT bands. Without it the next block
9293 // reads the row's stale value.
9294 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
9295 return Ok((mode, uv_predict_mode));
9296 }
9297 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
9298 // that is 8 px tall, so each strip stamps every cell it touches and the
9299 // LAST strip wins -- which is the right answer for the block below/right
9300 // of the 32x32, the only reader outside it. Written after this strip's
9301 // own context read above, never before.
9302 for cell in 0..bw.div_ceil(SUB) {
9303 neighbours.above_mode[c + cell] = mode;
9304 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
9305 neighbours.above_side[c + cell] = bw;
9306 }
9307 for cell in 0..bh.div_ceil(SUB) {
9308 neighbours.left_mode[r + cell] = mode;
9309 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
9310 neighbours.left_side[r + cell] = bh;
9311 }
9312 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
9313 // [`decode_leaf_rect`] does (the split arm above records these through
9314 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
9315 // `sub8_mode_row` holding the previous block, and the next 32x32's
9316 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
9317 // fixture).
9318 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
9319 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
9320 let (px, py) = (mi_c * MI, mi_r * MI);
9321 let (cpx, cpy) = (px / 2, py / 2);
9322 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9323 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9324 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
9325 (&SCAN_32X8, &SCAN_16X4)
9326 } else {
9327 (&SCAN_8X32, &SCAN_4X16)
9328 };
9329 let (luma_levels, u_levels, v_levels) = if skip {
9330 (
9331 vec![0i32; bw * bh],
9332 vec![0i32; chroma_w * chroma_h],
9333 vec![0i32; chroma_w * chroma_h],
9334 )
9335 } else {
9336 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
9337 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
9338 let (luma_levels, luma_tx_type) = read_coeffs_rect(
9339 dec,
9340 &mut luma_coding,
9341 luma_scan,
9342 bw,
9343 bh,
9344 0,
9345 dc_sign_ctx(around[0].2),
9346 TxType::DctDct,
9347 )?;
9348 let mut planes = Vec::with_capacity(2);
9349 for plane in 1..3 {
9350 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
9351 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
9352 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
9353 let (levels, tx_type) = read_coeffs_rect(
9354 dec,
9355 &mut coding,
9356 chroma_scan,
9357 chroma_w,
9358 chroma_h,
9359 skip_ctx,
9360 dc_sign_ctx(around[plane].2),
9361 default_tx,
9362 )?;
9363 planes.push((levels, tx_type));
9364 }
9365 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
9366 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
9367 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
9368 let luma_residual = dequant_and_inverse_typed_wh(
9369 &luma_levels,
9370 bw,
9371 bh,
9372 crate::decode::bit_depth(),
9373 block_q_idx(),
9374 plane_q_delta(0).0,
9375 plane_q_delta(0).1,
9376 luma_tx_type,
9377 );
9378 if let Some(b) = &palette_y_buf {
9379 set_palette_pred(b.clone());
9380 }
9381 y.reconstruct_rect(
9382 px,
9383 py,
9384 bw,
9385 bh,
9386 mode,
9387 angle_delta_y,
9388 reach,
9389 &luma_residual,
9390 None,
9391 filter_intra,
9392 smooth_neighbor,
9393 );
9394 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9395 for (plane, buf, levels, tx_type) in [
9396 (1usize, &mut *u, &u_levels, u_tx_type),
9397 (2, &mut *v, &v_levels, v_tx_type),
9398 ] {
9399 let residual = dequant_and_inverse_typed_wh(
9400 levels,
9401 chroma_w,
9402 chroma_h,
9403 crate::decode::bit_depth(),
9404 block_q_idx(),
9405 plane_q_delta(plane).0,
9406 plane_q_delta(plane).1,
9407 tx_type,
9408 );
9409 if let Some((ub, vb)) = &palette_uv_bufs {
9410 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
9411 }
9412 buf.reconstruct_rect(
9413 cpx,
9414 cpy,
9415 chroma_w,
9416 chroma_h,
9417 uv_predict_mode,
9418 angle_delta_uv,
9419 reach,
9420 &residual,
9421 alpha
9422 .zip(ac.as_deref())
9423 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
9424 None,
9425 smooth_neighbor_uv,
9426 );
9427 }
9428 neighbours.record_mi_rect(
9429 (mi_r, mi_c),
9430 bw,
9431 bh,
9432 &[luma_levels, u_levels, v_levels],
9433 );
9434 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
9435 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
9436 record_strip_palette(
9437 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
9438 pal_uv_colors,
9439 );
9440 if bw > bh {
9441 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
9442 } else {
9443 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
9444 }
9445 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
9446 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
9447 // frame, so this 1:4 strip -- which is also the INTER frame's reader
9448 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
9449 // transform size in both TXFM_CONTEXT bands. Without it the next block
9450 // reads the row's stale value.
9451 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
9452 return Ok((mode, uv_predict_mode));
9453 };
9454 if let Some(b) = &palette_y_buf {
9455 set_palette_pred(b.clone());
9456 }
9457 y.reconstruct_rect(
9458 px,
9459 py,
9460 bw,
9461 bh,
9462 mode,
9463 angle_delta_y,
9464 reach,
9465 &luma_levels,
9466 None,
9467 filter_intra,
9468 smooth_neighbor,
9469 );
9470 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9471 if let Some((ub, _)) = &palette_uv_bufs {
9472 set_palette_pred(ub.clone());
9473 }
9474 u.reconstruct_rect(
9475 cpx,
9476 cpy,
9477 chroma_w,
9478 chroma_h,
9479 uv_predict_mode,
9480 angle_delta_uv,
9481 reach,
9482 &u_levels,
9483 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
9484 None,
9485 smooth_neighbor_uv,
9486 );
9487 if let Some((_, vb)) = &palette_uv_bufs {
9488 set_palette_pred(vb.clone());
9489 }
9490 v.reconstruct_rect(
9491 cpx,
9492 cpy,
9493 chroma_w,
9494 chroma_h,
9495 uv_predict_mode,
9496 angle_delta_uv,
9497 reach,
9498 &v_levels,
9499 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
9500 None,
9501 smooth_neighbor_uv,
9502 );
9503 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
9504 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
9505 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
9506 record_strip_palette(
9507 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
9508 );
9509 if bw > bh {
9510 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
9511 } else {
9512 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
9513 }
9514 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
9515 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
9516 // frame, so this 1:4 strip -- which is also the INTER frame's reader
9517 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
9518 // transform size in both TXFM_CONTEXT bands. Without it the next block
9519 // reads the row's stale value.
9520 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
9521 Ok((mode, uv_predict_mode))
9522}
9523
9524/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
9525/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
9526/// down, and the first shape here whose luma block is a single mi row (or
9527/// column).
9528///
9529/// What is new at this size is CHROMA. `is_chroma_reference`
9530/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
9531/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
9532/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
9533/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
9534/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
9535/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
9536/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
9537///
9538/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
9539/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
9540/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
9541/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
9542/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
9543/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
9544/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
9545/// shape's own CDF row.
9546///
9547/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
9548/// refuses by name rather than guess-decode.
9549#[allow(clippy::too_many_arguments)]
9550fn decode_rect4_16(
9551 dec: &mut SymbolDecoder,
9552 cdfs: &mut Cdfs,
9553 neighbours: &mut Neighbours,
9554 at16: (usize, usize),
9555 horz: bool,
9556 y: &mut PlaneBuf,
9557 u: &mut PlaneBuf,
9558 v: &mut PlaneBuf,
9559 enable_filter_intra: bool,
9560 allow_screen_content_tools: bool,
9561 base_q_idx: u8,
9562 tx_select: bool,
9563 reduced_tx_set: bool,
9564) -> Result<()> {
9565 let (r, c) = at16;
9566 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
9567 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
9568 let (mi_w, mi_h) = (bw / MI, bh / MI);
9569 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
9570 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
9571 let mut prev: Option<((usize, usize), usize)> = None;
9572 let mut last_mode = DC_PRED;
9573 let mut last_uv_mode = DC_PRED;
9574 for i in 0..4usize {
9575 let lmi = if horz {
9576 (mi_row0 + i, mi_col0)
9577 } else {
9578 (mi_row0, mi_col0 + i)
9579 };
9580 let has_chroma = i % 2 == 1;
9581 let (mode, uv, _tx) = decode_rect4_16_strip(
9582 dec,
9583 cdfs,
9584 neighbours,
9585 lmi,
9586 horz,
9587 has_chroma,
9588 prev,
9589 y,
9590 u,
9591 v,
9592 enable_filter_intra,
9593 allow_screen_content_tools,
9594 base_q_idx,
9595 tx_select,
9596 reduced_tx_set,
9597 )?;
9598 if let Some(m) = uv {
9599 last_uv_mode = m;
9600 }
9601 last_mode = mode;
9602 prev = Some((lmi, mode));
9603 }
9604 // The coarse 16-px cell holds one entry for the whole 16x16: the last
9605 // strip is what a block below (right) sees through it, the mi-exact maps
9606 // above answering everything finer.
9607 neighbours.above_mode[c] = last_mode;
9608 neighbours.left_mode[r] = last_mode;
9609 neighbours.above_uv_mode[c] = last_uv_mode;
9610 neighbours.left_uv_mode[r] = last_uv_mode;
9611 neighbours.above_side[c] = bw;
9612 neighbours.left_side[r] = bh;
9613 Ok(())
9614}
9615
9616/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
9617/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
9618/// block path can decode a SINGLE intra strip of a partition whose other
9619/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
9620/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
9621/// every strip publishes its own mi-exact mode). Returns
9622/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
9623#[allow(clippy::too_many_arguments)]
9624fn decode_rect4_16_strip(
9625 dec: &mut SymbolDecoder,
9626 cdfs: &mut Cdfs,
9627 neighbours: &mut Neighbours,
9628 lmi: (usize, usize),
9629 horz: bool,
9630 has_chroma: bool,
9631 prev: Option<((usize, usize), usize)>,
9632 y: &mut PlaneBuf,
9633 u: &mut PlaneBuf,
9634 v: &mut PlaneBuf,
9635 enable_filter_intra: bool,
9636 allow_screen_content_tools: bool,
9637 base_q_idx: u8,
9638 tx_select: bool,
9639 reduced_tx_set: bool,
9640) -> Result<(usize, Option<usize>, (usize, usize))> {
9641 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
9642 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
9643 let (mi_w, mi_h) = (bw / MI, bh / MI);
9644 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
9645 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
9646 let mut last_uv_mode: Option<usize> = None;
9647 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
9648 // aliases all four strips onto one entry, so the mi-exact map wins and
9649 // the previous strip stands in on the split axis.
9650 let mut above_mode = neighbours.above_mode[c];
9651 let mut left_mode = neighbours.left_mode[r];
9652 if let Some(((pr, pc), pmode)) = prev {
9653 if pc == lmi.1 && lmi.0 == pr + mi_h {
9654 above_mode = pmode;
9655 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
9656 left_mode = pmode;
9657 }
9658 }
9659 let (above_mode, left_mode) =
9660 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
9661 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
9662 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
9663 // off CDF row 0 and every cache hit off an empty cache.
9664 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
9665 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
9666 let (
9667 skip,
9668 mode,
9669 angle_delta_y,
9670 uv_mode,
9671 angle_delta_uv,
9672 alpha,
9673 filter_intra,
9674 palette_y,
9675 palette_uv,
9676 ) = read_intra_mode_rect(
9677 dec,
9678 cdfs,
9679 above_mode,
9680 left_mode,
9681 true,
9682 has_chroma,
9683 bw,
9684 bh,
9685 enable_filter_intra,
9686 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
9687 allow_screen_content_tools,
9688 Some((palette_ctx, &palette_cache)),
9689 &palette_uv_cache,
9690 lmi.0,
9691 lmi.1,
9692 )?;
9693 if palette_y.is_some() || palette_uv.is_some() {
9694 RECT4_PALETTE_HITS.with(|h| h.set(h.get() + 1));
9695 }
9696 // The colour-index map through the base colours IS the prediction.
9697 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
9698 // chroma transform this closing strip codes.
9699 let palette_y_buf: Option<Vec<u16>> = palette_y
9700 .as_ref()
9701 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
9702 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
9703 (
9704 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
9705 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
9706 )
9707 });
9708 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
9709 if smooth_neighbor {
9710 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
9711 }
9712 if filter_intra.is_some() {
9713 FILTER_INTRA_RECT_HITS.with(|h| h.set(h.get() + 1));
9714 }
9715 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
9716 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
9717 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
9718 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
9719 let depth = if tx_select {
9720 // lane-intra16x4: on an INTER frame `get_tx_size_context` reads the
9721 // real `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what
9722 // the 2:1 intra-in-inter strip already does); the key frame's
9723 // deblock-grid approximation is only right where those bands were
9724 // never written.
9725 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
9726 tx_size_context_txfm_rect(neighbours, lmi, bw, bh)
9727 } else {
9728 tx_size_context_rect(neighbours, lmi, bw, bh)
9729 };
9730 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
9731 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
9732 eprintln!(
9733 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
9734 lmi.0,
9735 lmi.1,
9736 dec.debug_state().0
9737 );
9738 }
9739 d
9740 } else {
9741 0
9742 };
9743 if depth != 0 {
9744 TX_DEPTH_HITS.with(|h| h.set(h.get() + 1));
9745 RECT4_16_SPLIT_HITS.with(|h| h.set(h.get() + 1));
9746 }
9747 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
9748 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
9749 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9750 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
9751 if depth != 0 {
9752 // [`decode_rect_split`]'s per-unit walk, inlined because the
9753 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
9754 // the strip (that function codes one chroma transform per block).
9755 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
9756 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
9757 // unit predicts off the units before it in raster order.
9758 let rect_unit = tx_w != tx_h;
9759 let zero_tu = vec![0i32; tx_w * tx_h];
9760 for tu_row in 0..bh / tx_h {
9761 for tu_col in 0..bw / tx_w {
9762 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
9763 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
9764 let tu_reach = Reach::of_tu(
9765 bw,
9766 bh,
9767 tu_col * tx_w,
9768 tu_row * tx_h,
9769 tx_w,
9770 tx_h,
9771 reach,
9772 );
9773 if let Some(b) = &palette_y_buf {
9774 let tu_buf: Vec<u16> = (0..tx_h)
9775 .flat_map(|i| {
9776 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
9777 b[base..base + tx_w].iter().copied()
9778 })
9779 .collect();
9780 set_palette_pred(tu_buf);
9781 }
9782 if skip {
9783 y.reconstruct_rect(
9784 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
9785 None, filter_intra, smooth_neighbor,
9786 );
9787 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
9788 } else if rect_unit {
9789 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
9790 // 32 coded positions and the `TX_4X4` `tx_type` row:
9791 // exactly [`TxbSet::LumaRect4x8`].
9792 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9793 let tu_skip_ctx =
9794 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
9795 let set = if reduced_tx_set {
9796 TxbSet::LumaRect4x8
9797 } else {
9798 TxbSet::LumaRect4x8Set1
9799 };
9800 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
9801 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
9802 let (tu_grid, tu_tx_type) = read_coeffs_rect(
9803 dec,
9804 &mut coding,
9805 tu_scan,
9806 tx_w,
9807 tx_h,
9808 tu_skip_ctx,
9809 dc_sign_ctx(tu_around.2),
9810 TxType::DctDct,
9811 )?;
9812 let residual = dequant_and_inverse_typed_wh(
9813 &tu_grid,
9814 tx_w,
9815 tx_h,
9816 crate::decode::bit_depth(),
9817 block_q_idx(),
9818 plane_q_delta(0).0,
9819 plane_q_delta(0).1,
9820 tu_tx_type,
9821 );
9822 y.reconstruct_rect(
9823 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
9824 None, filter_intra, smooth_neighbor,
9825 );
9826 if tu_grid.iter().any(|&l| l != 0) {
9827 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
9828 }
9829 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9830 } else {
9831 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
9832 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
9833 let tu_grid = read_plane(
9834 dec,
9835 cdfs,
9836 txbset_for(tx_w, reduced_tx_set),
9837 &default_scan(tx_w),
9838 0,
9839 tu_around,
9840 mode,
9841 mode,
9842 angle_delta_y,
9843 tu_reach,
9844 y,
9845 tu_px,
9846 tu_py,
9847 tx_w,
9848 tx_w,
9849 base_q_idx,
9850 None,
9851 filter_intra,
9852 Some(tu_skip_ctx),
9853 smooth_neighbor,
9854 )?;
9855 if tu_grid.iter().any(|&l| l != 0) {
9856 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
9857 }
9858 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
9859 }
9860 }
9861 }
9862 } else {
9863 let levels = if skip {
9864 let zeros = vec![0i32; bw * bh];
9865 if let Some(b) = &palette_y_buf {
9866 set_palette_pred(b.clone());
9867 }
9868 y.reconstruct_rect(
9869 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
9870 smooth_neighbor,
9871 );
9872 zeros
9873 } else {
9874 // The strip's luma TU *is* the strip (`plane_bsize ==
9875 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
9876 // `txb_skip_ctx` at 0.
9877 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
9878 let set = if reduced_tx_set {
9879 TxbSet::LumaRect16x4
9880 } else {
9881 TxbSet::LumaRect16x4Set1
9882 };
9883 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
9884 let (levels, tx_type) = read_coeffs_rect(
9885 dec,
9886 &mut coding,
9887 scan,
9888 bw,
9889 bh,
9890 0,
9891 dc_sign_ctx(around.2),
9892 TxType::DctDct,
9893 )?;
9894 let residual = dequant_and_inverse_typed_wh(
9895 &levels,
9896 bw,
9897 bh,
9898 crate::decode::bit_depth(),
9899 block_q_idx(),
9900 plane_q_delta(0).0,
9901 plane_q_delta(0).1,
9902 tx_type,
9903 );
9904 if let Some(b) = &palette_y_buf {
9905 set_palette_pred(b.clone());
9906 }
9907 y.reconstruct_rect(
9908 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
9909 smooth_neighbor,
9910 );
9911 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
9912 levels
9913 };
9914 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
9915 }
9916 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
9917 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0);
9918 // `update_partition_context` writes `partition_context_lookup[
9919 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
9920 // the left (mirrored under VERT_4).
9921 for cell in 0..mi_w {
9922 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
9923 *slot = bw;
9924 }
9925 }
9926 for cell in 0..mi_h {
9927 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
9928 *slot = bh;
9929 }
9930 }
9931 if has_chroma {
9932 RECT4_16_CHROMA_HITS.with(|h| h.set(h.get() + 1));
9933 let pair_mi = if horz {
9934 (lmi.0 - 1, lmi.1)
9935 } else {
9936 (lmi.0, lmi.1 - 1)
9937 };
9938 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
9939 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
9940 let (cpx, cpy) = (ppx / 2, ppy / 2);
9941 let (cw, ch) = (pw / 2, ph / 2);
9942 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
9943 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
9944 RECT4_16_CHROMA_DIR_HITS.with(|h| h.set(h.get() + 1));
9945 }
9946 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height);
9947 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
9948 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
9949 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
9950 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
9951 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
9952 // the pair's top-left luma mi, never this leaf's odd row/column.
9953 // Reading `lmi` here named the leaf directly above (a non-chroma
9954 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
9955 // SMOOTH neighbour: filt_type 0 instead of 1 turned
9956 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
9957 // directional chroma strip, moving 4 samples by 1.
9958 let smooth_neighbor_uv =
9959 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
9960 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
9961 {
9962 RECT4_16_UV_PAIR_FILT_HITS.with(|h| h.set(h.get() + 1));
9963 }
9964 let (u_levels, v_levels) = if skip {
9965 let zeros = vec![0i32; cw * ch];
9966 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
9967 // ~1000) predicts EVERY plane and only guards the residual on
9968 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
9969 // DC + alpha * luma-AC. Dropping the CfL term here left a
9970 // chroma-only bounded box on ReelC's key frames.
9971 let ac = alpha.map(|_| cfl_ac_q3_rect(y, ppx, ppy, pw, ph));
9972 if alpha.is_some() {
9973 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
9974 }
9975 for (buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
9976 if let Some((ub, vb)) = &palette_uv_bufs {
9977 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
9978 }
9979 buf.reconstruct_rect(
9980 cpx,
9981 cpy,
9982 cw,
9983 ch,
9984 uv_predict_mode,
9985 angle_delta_uv,
9986 pair_reach,
9987 &zeros,
9988 alpha
9989 .zip(ac.as_deref())
9990 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
9991 None,
9992 smooth_neighbor_uv,
9993 );
9994 }
9995 (zeros.clone(), zeros)
9996 } else {
9997 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
9998 let mut planes = Vec::with_capacity(2);
9999 for plane in 1..3 {
10000 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
10001 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
10002 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
10003 let (levels, tx_type) = read_coeffs_rect(
10004 dec,
10005 &mut coding,
10006 chroma_scan,
10007 cw,
10008 ch,
10009 skip_ctx,
10010 dc_sign_ctx(around[plane].2),
10011 default_tx,
10012 )?;
10013 planes.push((levels, tx_type));
10014 }
10015 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
10016 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
10017 // CfL averages the luma of the WHOLE pair, the region this one
10018 // chroma transform covers.
10019 let ac = alpha.map(|_| cfl_ac_q3_rect(y, ppx, ppy, pw, ph));
10020 for (plane, buf, levels, tx_type) in [
10021 (1usize, &mut *u, &u_levels, u_tx_type),
10022 (2, &mut *v, &v_levels, v_tx_type),
10023 ] {
10024 let residual = dequant_and_inverse_typed_wh(
10025 levels,
10026 cw,
10027 ch,
10028 crate::decode::bit_depth(),
10029 block_q_idx(),
10030 plane_q_delta(plane).0,
10031 plane_q_delta(plane).1,
10032 tx_type,
10033 );
10034 if let Some((ub, vb)) = &palette_uv_bufs {
10035 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
10036 }
10037 buf.reconstruct_rect(
10038 cpx,
10039 cpy,
10040 cw,
10041 ch,
10042 uv_predict_mode,
10043 angle_delta_uv,
10044 pair_reach,
10045 &residual,
10046 alpha
10047 .zip(ac.as_deref())
10048 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
10049 None,
10050 smooth_neighbor_uv,
10051 );
10052 }
10053 (u_levels, v_levels)
10054 };
10055 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
10056 // The chroma planes' coefficient context, over the PAIR's mi span
10057 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
10058 // the luma one rounded up to its 4x4 unit).
10059 let u_state = neighbour_state(&u_levels);
10060 let v_state = neighbour_state(&v_levels);
10061 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10062 let bound_h = round_up_even(neighbours.mi_rows);
10063 let bound_w = round_up_even(neighbours.mi_cols);
10064 for cell in 0..(ph / MI) {
10065 if pair_mi.0 + cell < bound_h
10066 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
10067 {
10068 slot[1] = u_state;
10069 slot[2] = v_state;
10070 }
10071 }
10072 for cell in 0..(pw / MI) {
10073 if pair_mi.1 + cell < bound_w
10074 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
10075 {
10076 slot[1] = u_state;
10077 slot[2] = v_state;
10078 }
10079 }
10080 last_uv_mode = Some(uv_predict_mode);
10081 }
10082 if horz {
10083 RECT4_16_HORZ_HITS.with(|h| h.set(h.get() + 1));
10084 } else {
10085 RECT4_16_VERT_HITS.with(|h| h.set(h.get() + 1));
10086 }
10087 let (pal_y_size, pal_y_colors) =
10088 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10089 let (pal_uv_size, pal_uv_colors) =
10090 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10091 record_strip_palette(
10092 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
10093 );
10094 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
10095 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
10096 // frame): the above row records `tx_size_wide` over the block's width and
10097 // the left column `tx_size_high` over its height. This 1:4 strip reader is
10098 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
10099 // and it published neither band -- so the block after a 64x16 strip read
10100 // the row's init value 64 as its left transform height and took
10101 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
10102 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
10103 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
10104 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
10105 Ok((mode, last_uv_mode, (tx_w, tx_h)))
10106}
10107
10108
10109/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
10110/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
10111/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
10112/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
10113/// cap, so LUMA needs the same corner truncation [`decode_block`] already
10114/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
10115/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
10116/// this function's own charter/report), so both strips read a real 32x32
10117/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
10118/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
10119/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
10120/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
10121/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
10122/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
10123/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
10124/// that function, only the single-transform-unit (`tx_depth == 0`) case is
10125/// supported: a split transform refuses by name rather than guess-decode.
10126#[allow(clippy::too_many_arguments)]
10127fn decode_block_rect64(
10128 dec: &mut SymbolDecoder,
10129 cdfs: &mut Cdfs,
10130 neighbours: &mut Neighbours,
10131 at: (usize, usize),
10132 bw: usize,
10133 bh: usize,
10134 y: &mut PlaneBuf,
10135 u: &mut PlaneBuf,
10136 v: &mut PlaneBuf,
10137 enable_filter_intra: bool,
10138 allow_screen_content_tools: bool,
10139 base_q_idx: u8,
10140 tx_select: bool,
10141 reduced_tx_set: bool,
10142) -> Result<()> {
10143 let (r, c) = at;
10144 let (px, py) = (c * SUB, r * SUB);
10145 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
10146 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
10147 let palette_uv_cache = neighbours.palette_uv_cache(at);
10148 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10149 read_intra_mode_rect(
10150 dec,
10151 cdfs,
10152 nb_above_mode,
10153 nb_left_mode,
10154 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
10155 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
10156 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
10157 // correct), CFL must never be offered here -- passing `true`
10158 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
10159 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
10160 // from this block's very first symbol (lane-sbpart r3 bisect).
10161 false,
10162 true,
10163 bw,
10164 bh,
10165 enable_filter_intra,
10166 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
10167 allow_screen_content_tools,
10168 Some((palette_ctx, &palette_cache)),
10169 &palette_uv_cache,
10170 r * (SUB / MI),
10171 c * (SUB / MI),
10172 )?;
10173 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
10174 // The luma coefficient path here is the corner-cropped 32x32 real
10175 // transform embedded in a 64x32/32x64 grid ([`decode_block_rect64`]'s
10176 // own doc comment) -- a real (non-skip) palette block's residual
10177 // needs the plain, uncropped rect reader [`decode_block_rect`] already
10178 // has, not this one's truncation. `skip` (no residual at all) is
10179 // still supported below (lane-palette2 r4).
10180 //
10181 // lane-pal8 r1 MEASURED the lift and it is NOT free: dropping this
10182 // refusal decodes `testsrc2` 128x128 10-bit cq55 `--enable-palette=1
10183 // --min-partition-size=8 --tile-columns=1` with a whole-frame pixel
10184 // mismatch (the arm the gate below counts). Something in this shape's
10185 // palette prediction or its corner-cropped residual is wrong, and the
10186 // refusal stays until that is found -- it is counted, never skipped.
10187 PALETTE_SB_STRIP_HITS.with(|c| c.set(c.get() + 1));
10188 return Err(unsupported(
10189 "a palette block with a real transform on a superblock-level HORZ/VERT \
10190 strip (corner-cropped luma coefficients not ported for palette)",
10191 ));
10192 }
10193 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10194 if smooth_neighbor {
10195 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
10196 }
10197 let smooth_neighbor_uv =
10198 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
10199 if filter_intra.is_some() {
10200 // `filter_intra_size_class_rect` already returns `None` for both
10201 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
10202 // 32 on both axes), so this symbol is never read at this level --
10203 // kept only as the same defensive refusal [`decode_block_rect`] has.
10204 return Err(unsupported(
10205 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
10206 av1_filter_intra_allowed_bsize caps at 32x32)",
10207 ));
10208 }
10209 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10210 DC_PRED
10211 } else {
10212 uv_mode
10213 };
10214 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10215 let depth = if tx_select {
10216 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
10217 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
10218 // the 16x4 intra-in-inter strips already do); the key frame's
10219 // deblock-grid approximation is only right where those bands were never
10220 // written. Measured on the 10-bit 1920x792 128-superblock stream,
10221 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
10222 // `tx_size_cat2` row 1 where libaom reads row 2.
10223 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
10224 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
10225 } else {
10226 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
10227 };
10228 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
10229 // counts `sub_tx_size_map` steps from the block's own max rect
10230 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
10231 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
10232 // steps, so this level's category is 3 (the same one a 64x64 square
10233 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
10234 // here was a wrong-table read of a real symbol.
10235 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
10236 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
10237 eprintln!(
10238 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
10239 dec.debug_state().0
10240 );
10241 }
10242 d
10243 } else {
10244 0
10245 };
10246 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
10247 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
10248 publish_txfm_bands_if_in_inter(
10249 neighbours,
10250 (mi_r, mi_c),
10251 depth_to_tx_wh(bw, bh, depth),
10252 (bw, bh),
10253 );
10254 if depth != 0 {
10255 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
10256 // lane-rectsplit r1/r4: the superblock-level strip splits its
10257 // transform through the very same per-unit path as its 32x32-level
10258 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
10259 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
10260 // measured the old square formula mis-tiling exactly that strip).
10261 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10262 if bw.max(bh) / bw.min(bh) == 4 {
10263 let which = if depth == 1 {
10264 &RECT4_SPLIT_DEPTH1_HITS
10265 } else {
10266 &RECT4_SPLIT_DEPTH2_HITS
10267 };
10268 which.with(|c| c.set(c.get() + 1));
10269 }
10270 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
10271 eprintln!(
10272 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
10273 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
10274 angle_y={angle_delta_y}"
10275 );
10276 }
10277 let modes = RectStripModes {
10278 skip,
10279 mode,
10280 angle_delta_y,
10281 uv_predict_mode,
10282 angle_delta_uv,
10283 alpha,
10284 filter_intra,
10285 smooth_neighbor,
10286 smooth_neighbor_uv,
10287 palette_y: palette_y
10288 .as_ref()
10289 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10290 palette_uv: palette_uv.as_ref().map(|p| {
10291 (
10292 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10293 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10294 )
10295 }),
10296 };
10297 if palette_y.is_some() || palette_uv.is_some() {
10298 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
10299 }
10300 decode_rect_split(
10301 dec,
10302 cdfs,
10303 neighbours,
10304 (mi_r, mi_c),
10305 bw,
10306 bh,
10307 tx_w,
10308 tx_h,
10309 &modes,
10310 y,
10311 u,
10312 v,
10313 base_q_idx,
10314 reduced_tx_set,
10315 )?;
10316 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
10317 // (lane-palette2 r10): this return skips the fn's own tail, so a
10318 // split-tx superblock strip would otherwise leave the above/left
10319 // palette arrays holding a dead block's colours.
10320 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10321 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10322 let (puv_size, puv_colors) =
10323 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10324 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10325 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
10326 // return skips the fn's own tail, so a SPLIT superblock-level strip
10327 // published no TXFM_CONTEXT band and the next block read the row's init
10328 // value 64 as its left transform height. Measured on the 10-bit
10329 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
10330 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
10331 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
10332 // bands carry the SPLIT unit's size, not the block's.
10333 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10334 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.set(c.get() + 1));
10335 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
10336 return Ok(());
10337 }
10338 let (tx_w, tx_h) = (bw, bh);
10339 let (cpx, cpy) = (px / 2, py / 2);
10340 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10341 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
10342 if let Some(ref pyv) = palette_y {
10343 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
10344 set_palette_pred(buf);
10345 }
10346 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
10347 (
10348 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
10349 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
10350 )
10351 });
10352 if skip {
10353 y.reconstruct_rect(
10354 px,
10355 py,
10356 bw,
10357 bh,
10358 mode,
10359 angle_delta_y,
10360 reach,
10361 &vec![0i32; bw * bh],
10362 None,
10363 filter_intra,
10364 smooth_neighbor,
10365 );
10366 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
10367 if let Some((ub, _)) = &palette_uv_bufs {
10368 set_palette_pred(ub.clone());
10369 }
10370 u.reconstruct_rect(
10371 cpx,
10372 cpy,
10373 chroma_w,
10374 chroma_h,
10375 uv_predict_mode,
10376 angle_delta_uv,
10377 reach,
10378 &vec![0i32; chroma_w * chroma_h],
10379 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
10380 None,
10381 smooth_neighbor_uv,
10382 );
10383 if let Some((_, vb)) = &palette_uv_bufs {
10384 set_palette_pred(vb.clone());
10385 }
10386 v.reconstruct_rect(
10387 cpx,
10388 cpy,
10389 chroma_w,
10390 chroma_h,
10391 uv_predict_mode,
10392 angle_delta_uv,
10393 reach,
10394 &vec![0i32; chroma_w * chroma_h],
10395 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
10396 None,
10397 smooth_neighbor_uv,
10398 );
10399 neighbours.record_rect(
10400 at,
10401 bw,
10402 bh,
10403 mode,
10404 uv_predict_mode,
10405 &[
10406 vec![0i32; bw * bh],
10407 vec![0i32; chroma_w * chroma_h],
10408 vec![0i32; chroma_w * chroma_h],
10409 ],
10410 );
10411 } else {
10412 let around = neighbours.around_rect(at, bw, bh);
10413 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
10414 // (see this function's own doc comment). A 64-length axis codes only
10415 // its low 32 coefficients, so the corner is `min(bw, 32)` x
10416 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
10417 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
10418 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
10419 let scan32 = default_scan(TX32);
10420 if coeff_trace_on() {
10421 let (rng, _) = dec.debug_state();
10422 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
10423 }
10424 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
10425 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
10426 read_coeffs(
10427 dec,
10428 &mut luma_coding,
10429 &scan32,
10430 0,
10431 dc_sign_ctx(around[0].2),
10432 TxType::DctDct,
10433 Some((bw, bh)),
10434 )?
10435 } else {
10436 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
10437 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
10438 // (`scan.c`) gives both the very same `default_scan_32x16` /
10439 // `default_scan_16x32` the 2:1 sizes use ("Half of the
10440 // coefficients of tx64 at higher frequencies are set to zeros. So
10441 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
10442 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
10443 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
10444 // 512-position eob group) -- BOTH identical to TX_32X16, so the
10445 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
10446 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
10447 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
10448 // what `base_ctx_rect` computes at (32, 16).
10449 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
10450 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
10451 read_coeffs_rect(
10452 dec,
10453 &mut luma_coding,
10454 luma_scan,
10455 luma_cw,
10456 luma_ch,
10457 0,
10458 dc_sign_ctx(around[0].2),
10459 TxType::DctDct,
10460 )?
10461 };
10462 if coeff_trace_on() {
10463 let (rng, _) = dec.debug_state();
10464 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
10465 }
10466 let mut luma_levels = vec![0i32; bw * bh];
10467 for row in 0..luma_ch {
10468 luma_levels[row * bw..][..luma_cw]
10469 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
10470 }
10471 {
10472 let cur = block_q_idx();
10473 if cur != i32::from(base_q_idx) {
10474 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
10475 }
10476 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10477 eprintln!(
10478 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
10479 );
10480 }
10481 }
10482 let luma_residual = dequant_and_inverse_typed_wh(
10483 &luma_levels,
10484 bw,
10485 bh,
10486 crate::decode::bit_depth(),
10487 block_q_idx(),
10488 plane_q_delta(0).0,
10489 plane_q_delta(0).1,
10490 luma_tx_type,
10491 );
10492 y.reconstruct_rect(
10493 px,
10494 py,
10495 bw,
10496 bh,
10497 mode,
10498 angle_delta_y,
10499 reach,
10500 &luma_residual,
10501 None,
10502 filter_intra,
10503 smooth_neighbor,
10504 );
10505 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
10506 let leftcol: Vec<u16> = if px > 0 {
10507 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
10508 } else {
10509 vec![]
10510 };
10511 eprintln!(
10512 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
10513 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
10514 luma_corner.iter().any(|&v| v != 0),
10515 &y.data[py * y.width + px..][..bw],
10516 leftcol,
10517 );
10518 }
10519 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
10520 // corner crop needed (see doc comment).
10521 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
10522 // The chroma plane is never truncated (both axes <= 32 after
10523 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
10524 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
10525 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
10526 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
10527 // set, and only the scan is new (lane-tx64x16).
10528 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
10529 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
10530 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
10531 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
10532 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
10533 };
10534 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
10535 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
10536 if coeff_trace_on() {
10537 let (rng, _) = dec.debug_state();
10538 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
10539 }
10540 let (u_levels, u_tx_type) = read_coeffs_rect(
10541 dec,
10542 &mut u_coding,
10543 chroma_scan,
10544 chroma_w,
10545 chroma_h,
10546 u_skip_ctx,
10547 dc_sign_ctx(around[1].2),
10548 TxType::DctDct,
10549 )?;
10550 if coeff_trace_on() {
10551 let (rng, _) = dec.debug_state();
10552 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
10553 }
10554 {
10555 let cur = block_q_idx();
10556 if cur != i32::from(base_q_idx) {
10557 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
10558 }
10559 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10560 eprintln!(
10561 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
10562 );
10563 }
10564 }
10565 let u_residual = dequant_and_inverse_typed_wh(
10566 &u_levels,
10567 chroma_w,
10568 chroma_h,
10569 crate::decode::bit_depth(),
10570 block_q_idx(),
10571 plane_q_delta(1).0,
10572 plane_q_delta(1).1,
10573 u_tx_type,
10574 );
10575 u.reconstruct_rect(
10576 cpx,
10577 cpy,
10578 chroma_w,
10579 chroma_h,
10580 uv_predict_mode,
10581 angle_delta_uv,
10582 reach,
10583 &u_residual,
10584 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
10585 None,
10586 smooth_neighbor_uv,
10587 );
10588 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
10589 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
10590 if coeff_trace_on() {
10591 let (rng, _) = dec.debug_state();
10592 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
10593 }
10594 let (v_levels, v_tx_type) = read_coeffs_rect(
10595 dec,
10596 &mut v_coding,
10597 chroma_scan,
10598 chroma_w,
10599 chroma_h,
10600 v_skip_ctx,
10601 dc_sign_ctx(around[2].2),
10602 TxType::DctDct,
10603 )?;
10604 if coeff_trace_on() {
10605 let (rng, _) = dec.debug_state();
10606 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
10607 }
10608 {
10609 let cur = block_q_idx();
10610 if cur != i32::from(base_q_idx) {
10611 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
10612 }
10613 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10614 eprintln!(
10615 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
10616 );
10617 }
10618 }
10619 let v_residual = dequant_and_inverse_typed_wh(
10620 &v_levels,
10621 chroma_w,
10622 chroma_h,
10623 crate::decode::bit_depth(),
10624 block_q_idx(),
10625 plane_q_delta(2).0,
10626 plane_q_delta(2).1,
10627 v_tx_type,
10628 );
10629 v.reconstruct_rect(
10630 cpx,
10631 cpy,
10632 chroma_w,
10633 chroma_h,
10634 uv_predict_mode,
10635 angle_delta_uv,
10636 reach,
10637 &v_residual,
10638 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
10639 None,
10640 smooth_neighbor_uv,
10641 );
10642 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
10643 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
10644 }
10645 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10646 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10647 let (puv_size, puv_colors) =
10648 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10649 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10650 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
10651 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
10652 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
10653 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
10654 // frame): the above row records `tx_size_wide` over the block's width and
10655 // the left column `tx_size_high` over its height. This 1:4 strip reader is
10656 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
10657 // and it published neither band -- so the block after a 64x16 strip read
10658 // the row's init value 64 as its left transform height and took
10659 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
10660 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
10661 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
10662 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10663 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
10664 match (bw, bh) {
10665 (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)),
10666 (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)),
10667 _ => {}
10668 }
10669 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10670 let (rng, _) = dec.debug_state();
10671 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
10672 }
10673 Ok(())
10674}
10675
10676/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
10677/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
10678/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
10679/// it lands away from zero, for gate tests to prove a real stream fired one.
10680fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
10681 let symbol = dec.symbol(cdf);
10682 if symbol != ANGLE_DELTA_ZERO {
10683 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
10684 }
10685 symbol as i32 - ANGLE_DELTA_ZERO as i32
10686}
10687
10688#[allow(clippy::too_many_arguments)]
10689fn read_intra_mode(
10690 dec: &mut SymbolDecoder,
10691 cdfs: &mut Cdfs,
10692 above_mode: usize,
10693 left_mode: usize,
10694 cfl: bool,
10695 side: usize,
10696 enable_filter_intra: bool,
10697 skip_ctx: usize,
10698 allow_screen_content_tools: bool,
10699 allow_intrabc: bool,
10700 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
10701 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
10702 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
10703 // `None` at the excluded call sites (the 8x8-leaf path), which still read
10704 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
10705 // decoder reads either way -- but refuse by name the moment it fires,
10706 // exactly the old behaviour.
10707 palette: Option<(usize, &[u16])>,
10708 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
10709 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
10710 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
10711 // `use_palette_y`, not a neighbour lookup).
10712 palette_uv_cache: &[u16],
10713 mi_r: usize,
10714 mi_c: usize,
10715) -> Result<(
10716 bool,
10717 usize,
10718 i32,
10719 usize,
10720 i32,
10721 Option<(i32, i32)>,
10722 Option<usize>,
10723 Option<PaletteY>,
10724 Option<PaletteUv>,
10725)> {
10726 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
10727 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
10728 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
10729 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
10730 // line against the instrumented aomdec, not just `tell()`.
10731 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
10732 if ec_istep {
10733 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
10734 // (decodemv.c:818), printed at the same point: before the first
10735 // mode-info symbol of the block, so a cross-decoder range ladder can
10736 // be keyed on the BLOCK, not just on the symbol sequence.
10737 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
10738 }
10739 macro_rules! istep {
10740 ($name:literal, $val:expr) => {
10741 if ec_istep {
10742 let (rng, _) = dec.debug_state();
10743 eprintln!(
10744 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
10745 $name, $val
10746 );
10747 }
10748 };
10749 }
10750 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
10751 // point every square caller routes through (see `read_intra_mode_rect`).
10752 let cfl = if cfl && side > 32 {
10753 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
10754 false
10755 } else {
10756 cfl
10757 };
10758 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
10759 // `skip` when `SegIdPreSkip`, and after it otherwise.
10760 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
10761 if seg_id_pre_skip() {
10762 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
10763 }
10764 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
10765 if trace {
10766 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
10767 }
10768 istep!("skip", skip as i32);
10769 if !seg_id_pre_skip() {
10770 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
10771 }
10772 // spec order (see the comment below on `read_intrabc_info`): `skip`,
10773 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
10774 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
10775 istep!("cdef", 0);
10776 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
10777 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
10778 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
10779 let whole_sb = side == sb_mi_cur() as usize * 4;
10780 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip);
10781 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip);
10782 istep!("dq", 0);
10783 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
10784 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
10785 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
10786 // intra frame whose header set `allow_intrabc`. Actual intra block copy
10787 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
10788 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
10789 // draws the line at consuming this one flag symbol and refusing by name
10790 // when it fires, so the arithmetic decoder still resyncs for a stream
10791 // that merely allows (but never uses) intrabc.
10792 if allow_intrabc {
10793 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
10794 if trace {
10795 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
10796 }
10797 if use_intrabc {
10798 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
10799 if trace {
10800 eprintln!("TRACE intrabc dv={dv:?}");
10801 }
10802 INTRABC_DV.with(|c| c.set(Some(dv)));
10803 INTRABC_HITS.with(|c| c.set(c.get() + 1));
10804 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
10805 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
10806 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
10807 // `DC_PRED` (which is also what the neighbour mode contexts and
10808 // the loop filter then see).
10809 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
10810 }
10811 }
10812 let above_ctx = INTRA_MODE_CTX[above_mode];
10813 let left_ctx = INTRA_MODE_CTX[left_mode];
10814 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
10815 if trace {
10816 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
10817 }
10818 istep!("mode", mode as i32);
10819 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
10820 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
10821 if trace {
10822 eprintln!(
10823 "TRACE angle_delta value={}",
10824 delta + ANGLE_DELTA_ZERO as i32
10825 );
10826 }
10827 delta
10828 } else {
10829 0
10830 };
10831 istep!("angle_y", angle_delta_y);
10832 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
10833 // here so every `decode_block` caller (64x64 and 128x128 roots included)
10834 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
10835 let cfl = cfl && side <= 32;
10836 let uv_mode = if cfl {
10837 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
10838 } else {
10839 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
10840 };
10841 if trace {
10842 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
10843 }
10844 istep!("uv_mode", uv_mode as i32);
10845 let alpha = if cfl && uv_mode == UV_CFL_PRED {
10846 Some(read_cfl_alphas(dec, cdfs))
10847 } else {
10848 None
10849 };
10850 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
10851 // from this lane's directional chroma: a corner block with neither
10852 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
10853 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
10854 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
10855 // bug in that fallback this lane's own scope does not cover. Keep it
10856 // refused here rather than ship a silently-wrong decode.
10857 if (9..=12).contains(&uv_mode) {
10858 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
10859 }
10860 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
10861 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
10862 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
10863 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
10864 // the `else` branch below and never reads one either way.
10865 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
10866 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
10867 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
10868 } else {
10869 0
10870 };
10871 istep!("angle_uv", angle_delta_uv);
10872 if angle_delta_uv != 0 {
10873 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
10874 }
10875 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
10876 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
10877 // gated by `av1_allow_palette` (blockd.h -- size bound only,
10878 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
10879 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
10880 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
10881 // read the same CDF row whenever every neighbour really is non-palette).
10882 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
10883 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
10884 // neighbour lookup at all), so it is exact even at the excluded call
10885 // sites once Y decodes real syntax there too.
10886 //
10887 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
10888 // inline from `read_palette_mode_info` -- it runs later, from
10889 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
10890 // after the WHOLE mode-info read for the block, including UV palette
10891 // mode_info (`read_palette_mode_info`'s own second half, right below)
10892 // and `read_filter_intra_mode_info`. So this branch now only reads
10893 // mode/size/colours for both planes (deferring the two colour-index-map
10894 // decodes to after `filter_intra`, below) -- r6's range trace pinned
10895 // this exact ordering bug (`compare-range-not-tell`: ranges matched
10896 // bit-for-bit through the Y colours, diverged only at the old inline
10897 // `decode_color_index_map` call).
10898 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
10899 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
10900 if allow_screen_content_tools
10901 && let Some(bsize_ctx) = palette_bsize_ctx(side)
10902 {
10903 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
10904 if mode == DC_PRED {
10905 if trace {
10906 let (rng, _) = dec.debug_state();
10907 eprintln!(
10908 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
10909 );
10910 }
10911 }
10912 let use_palette_y =
10913 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
10914 if mode == DC_PRED && trace {
10915 let (rng, _) = dec.debug_state();
10916 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
10917 }
10918 if use_palette_y {
10919 if palette.is_none() {
10920 return Err(unsupported(
10921 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
10922 ));
10923 }
10924 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
10925 if trace {
10926 let (rng, _) = dec.debug_state();
10927 eprintln!("TRACE palette_y_size n={n} rng={rng}");
10928 }
10929 let colors = read_palette_colors_y(dec, n, cache);
10930 if trace {
10931 let (rng, _) = dec.debug_state();
10932 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
10933 }
10934 palette_y_pending = Some((n, colors));
10935 }
10936 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
10937 // unconditionally at this bit position whenever `uv_mode ==
10938 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
10939 // scope always reconstructs chroma alongside luma (`decode_block`
10940 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
10941 // is always true here and does not need threading in.
10942 let palette_uv_mode_ctx = usize::from(use_palette_y);
10943 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
10944 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
10945 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
10946 palette_uv_pending = Some((n, u_colors, v_colors));
10947 }
10948 }
10949 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
10950 // `use_filter_intra` symbol this decoder never read at all until
10951 // lane-av1real r10 -- silently skipping it left every bit past a
10952 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
10953 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
10954 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
10955 // symbol's bits were never consumed).
10956 let mut filter_intra = None;
10957 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
10958 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
10959 // `use_filter_intra` symbol for a Y-palette block, and reading one here
10960 // desynced every screen-content stream from the first palette block on
10961 // (it surfaced as a bogus "partition below 8x8" refusal further down the
10962 // tile).
10963 if mode == DC_PRED
10964 && enable_filter_intra
10965 && palette_y_pending.is_none()
10966 && let Some(class) = filter_intra_size_class(side)
10967 {
10968 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
10969 if trace {
10970 eprintln!(
10971 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
10972 use_filter_intra as i32
10973 );
10974 }
10975 istep!("use_filter_intra", use_filter_intra as i32);
10976 if use_filter_intra {
10977 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
10978 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
10979 if trace {
10980 eprintln!("TRACE filter_intra_mode value={fi_mode}");
10981 }
10982 istep!("filter_intra_mode", fi_mode as i32);
10983 filter_intra = Some(fi_mode);
10984 }
10985 }
10986 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
10987 // shared U/V map) -- the same order libaom's own loop visits them in.
10988 let palette_y = palette_y_pending.map(|(n, colors)| {
10989 let map = decode_color_index_map(dec, cdfs, n, side, false);
10990 PALETTE_HITS.with(|c| c.set(c.get() + 1));
10991 if trace {
10992 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
10993 }
10994 PaletteY { size: n, colors, map }
10995 });
10996 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
10997 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
10998 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
10999 if trace {
11000 eprintln!(
11001 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
11002 &u_colors[..n],
11003 &v_colors[..n]
11004 );
11005 }
11006 PaletteUv { size: n, u_colors, v_colors, map }
11007 });
11008 Ok((
11009 skip,
11010 mode,
11011 angle_delta_y,
11012 uv_mode,
11013 angle_delta_uv,
11014 alpha,
11015 filter_intra,
11016 palette_y,
11017 palette_uv,
11018 ))
11019}
11020
11021/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
11022/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
11023/// intra modes.
11024const UV_CFL_PRED: usize = 13;
11025
11026/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
11027/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
11028/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
11029/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
11030/// joint sign the same way. Returns each plane's final signed `alpha_q3`
11031/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
11032fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
11033 CFL_BLOCK_HITS.with(|c| c.set(c.get() + 1));
11034 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
11035 let sign_u = ((joint_sign + 1) * 11) >> 5;
11036 let sign_v = (joint_sign + 1) - 3 * sign_u;
11037 let alpha_u = if sign_u == 0 {
11038 0
11039 } else {
11040 let ctx_u = (joint_sign + 1 - 3) as usize;
11041 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
11042 if sign_u == 2 { mag } else { -mag }
11043 };
11044 let alpha_v = if sign_v == 0 {
11045 0
11046 } else {
11047 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
11048 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
11049 if sign_v == 2 { mag } else { -mag }
11050 };
11051 (alpha_u, alpha_v)
11052}
11053
11054/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
11055/// the reconstructed luma samples under a `side`-square block, subsampled
11056/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
11057/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
11058/// to give the AC values [`cfl_scaled`] scales by alpha.
11059fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
11060 let cside = side / 2;
11061 let mut ac = vec![0i32; cside * cside];
11062 let mut sum = 0i32;
11063 for cy in 0..cside {
11064 for cx in 0..cside {
11065 let (lx, ly) = (px + cx * 2, py + cy * 2);
11066 let q3 = (i32::from(y.data[ly * y.width + lx])
11067 + i32::from(y.data[ly * y.width + lx + 1])
11068 + i32::from(y.data[(ly + 1) * y.width + lx])
11069 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
11070 << 1;
11071 ac[cy * cside + cx] = q3;
11072 sum += q3;
11073 }
11074 }
11075 let num_pel = (cside * cside) as i32;
11076 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
11077 ac.iter_mut().for_each(|v| *v -= avg);
11078 ac
11079}
11080
11081/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
11082/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
11083/// ties away from zero on the shifted-out sign).
11084fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
11085 let v = alpha_q3 * ac_q3;
11086 if v >= 0 {
11087 (v + 32) >> 6
11088 } else {
11089 -((-v + 32) >> 6)
11090 }
11091}
11092
11093/// One plane's reconstruction buffer, `width * height` samples, and the
11094/// prediction/residual reads and writes into it — the decode-side twin of
11095/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
11096/// (own-edge and reach clamps both), passing what it gathers straight to
11097/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
11098/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
11099/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
11100/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
11101/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
11102/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
11103/// lane-mc64 r1: the decode-order index the stage dumps below key their file
11104/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
11105/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
11106/// without this every frame overwrote `.f0` and a per-frame bisection silently
11107/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
11108fn stage_dump_idx() -> usize {
11109 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
11110}
11111
11112fn dump_stage16(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, fw: usize, fh: usize) {
11113 use std::io::Write;
11114 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
11115 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
11116 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
11117 // not be read out at all.
11118 if let Ok(path) = crate::envflags::var(var)
11119 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
11120 {
11121 for (p, w, h) in [(y, fw, fh), (u, fw.div_ceil(2), fh.div_ceil(2)), (v, fw.div_ceil(2), fh.div_ceil(2))] {
11122 for row in 0..h {
11123 let mut bytes = Vec::with_capacity(w * 2);
11124 for &s in &p.data[row * p.width..][..w] {
11125 bytes.extend_from_slice(&s.to_le_bytes());
11126 }
11127 let _ = f.write_all(&bytes);
11128 }
11129 }
11130 }
11131}
11132
11133/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
11134/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
11135/// every frame overwrote the previous one and only the LAST frame survived,
11136/// which silently defeats any per-frame filter-stage bisection.
11137fn dump_stage_idx(var: &str) -> usize {
11138 use std::collections::HashMap;
11139 use std::sync::{Mutex, OnceLock};
11140 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
11141 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
11142 let e = m.entry(var.to_string()).or_insert(0);
11143 let i = *e;
11144 *e += 1;
11145 i
11146}
11147
11148fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
11149 use std::io::Write;
11150 if let Ok(path) = crate::envflags::var(var)
11151 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
11152 {
11153 for p in [y, u, v] {
11154 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
11155 let _ = f.write_all(&narrow);
11156 }
11157 }
11158}
11159
11160#[derive(Clone)]
11161struct PlaneBuf {
11162 data: Vec<u16>,
11163 width: usize,
11164 height: usize,
11165 /// The frame's true, decodable extent in this plane's own units — past
11166 /// this, samples are the padded coding surface's invented tail, never a
11167 /// real decoder's edge or reach reads.
11168 true_width: usize,
11169 true_height: usize,
11170 /// This plane's own tile's top-left pixel origin (spec: intra prediction
11171 /// never reaches across a tile boundary even though an earlier-decoded
11172 /// tile's real pixels sit right there in the shared buffer) — set via
11173 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
11174 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
11175 /// is threaded (the two-tile column-split stage 1 fixture's tile always
11176 /// ends at the frame's own right/bottom edge); a non-last tile's own
11177 /// right/bottom reach bound is still open, tracked in the report.
11178 tile_x0: usize,
11179 tile_y0: usize,
11180 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
11181 /// (exclusive) -- a non-last tile column/row's own reach must stop at
11182 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
11183 /// full padded extent) for the single-tile/last-tile case, matching the
11184 /// old unclipped behaviour exactly.
11185 tile_x1: usize,
11186 tile_y1: usize,
11187}
11188
11189/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
11190/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
11191/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
11192/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
11193/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
11194/// `ALTREF2`/`ALTREF`).
11195type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
11196
11197impl PlaneBuf {
11198 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
11199 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
11200 /// are already in this plane's own units (luma pixels for `y`, chroma
11201 /// pixels — halved — for `u`/`v`).
11202 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
11203 self.tile_x0 = x0;
11204 self.tile_y0 = y0;
11205 self.tile_x1 = x1;
11206 self.tile_y1 = y1;
11207 }
11208
11209 fn edges(
11210 &self,
11211 x: usize,
11212 y: usize,
11213 side: usize,
11214 reach: Reach,
11215 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
11216 let own_across = x + side.min(self.true_width.saturating_sub(x));
11217 let across = if reach.above_right {
11218 own_across + side.min(self.true_width.saturating_sub(own_across))
11219 } else {
11220 own_across
11221 }
11222 .min(self.width)
11223 .min(self.tile_x1);
11224 let own_down = y + side.min(self.true_height.saturating_sub(y));
11225 let down = if reach.below_left {
11226 own_down + side.min(self.true_height.saturating_sub(own_down))
11227 } else {
11228 own_down
11229 }
11230 .min(self.height)
11231 .min(self.tile_y1);
11232 let above = (y > self.tile_y0 && across > x)
11233 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
11234 let left = (x > self.tile_x0 && down > y).then(|| {
11235 (y..down)
11236 .map(|row| self.data[row * self.width + x - 1])
11237 .collect::<Vec<_>>()
11238 });
11239 let corner =
11240 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
11241 (above, left, corner)
11242 }
11243
11244 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
11245 /// the above/left reach each extend by their OWN axis (`bw` across,
11246 /// `bh` down), not one shared `side`.
11247 fn edges_rect(
11248 &self,
11249 x: usize,
11250 y: usize,
11251 bw: usize,
11252 bh: usize,
11253 reach: Reach,
11254 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
11255 let own_across = x + bw.min(self.true_width.saturating_sub(x));
11256 let across = if reach.above_right {
11257 own_across + bw.min(self.true_width.saturating_sub(own_across))
11258 } else {
11259 own_across
11260 }
11261 .min(self.width)
11262 .min(self.tile_x1);
11263 let own_down = y + bh.min(self.true_height.saturating_sub(y));
11264 let down = if reach.below_left {
11265 own_down + bh.min(self.true_height.saturating_sub(own_down))
11266 } else {
11267 own_down
11268 }
11269 .min(self.height)
11270 .min(self.tile_y1);
11271 let above = (y > self.tile_y0 && across > x)
11272 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
11273 let left = (x > self.tile_x0 && down > y).then(|| {
11274 (y..down)
11275 .map(|row| self.data[row * self.width + x - 1])
11276 .collect::<Vec<_>>()
11277 });
11278 let corner =
11279 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
11280 if matches!((bw, bh), (16, 8) | (8, 16)) {
11281 RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1));
11282 if across > own_across || down > own_down {
11283 RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1));
11284 }
11285 }
11286 (above, left, corner)
11287 }
11288
11289 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
11290 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
11291 /// already-rect-capable `(bw, bh)` pair.
11292 #[allow(clippy::too_many_arguments)]
11293 #[track_caller]
11294 fn reconstruct_rect(
11295 &mut self,
11296 x: usize,
11297 y: usize,
11298 bw: usize,
11299 bh: usize,
11300 mode: usize,
11301 angle_delta: i32,
11302 reach: Reach,
11303 residual: &[i32],
11304 cfl: Option<(i32, &[i32])>,
11305 filter_intra: Option<usize>,
11306 smooth_neighbor: bool,
11307 ) {
11308 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
11309 // (lane-palette2 r4): a palette block's prediction is the
11310 // reconstructed colour-index map, needing no edge pixels at all.
11311 let prediction = if let Some(buf) = take_palette_pred() {
11312 buf
11313 } else {
11314 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
11315 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
11316 eprintln!(
11317 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
11318 above.as_ref().map(|a| (a.len(), a[0])),
11319 left.as_ref().map(|l| l.len()),
11320 left.as_ref().map(|l| l[0]),
11321 self.tile_x0, self.tile_y0, self.true_width, self.true_height
11322 );
11323 }
11324 let mut prediction = vec![0u16; bw * bh];
11325 if let Some(fi_mode) = filter_intra {
11326 crate::intra::predict_filter_intra(
11327 fi_mode,
11328 above.as_deref(),
11329 left.as_deref(),
11330 corner,
11331 bw,
11332 bh,
11333 &mut prediction,
11334 );
11335 } else {
11336 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
11337 predict(
11338 mode as u8,
11339 angle_delta,
11340 above.as_deref(),
11341 left.as_deref(),
11342 corner,
11343 bw,
11344 bh,
11345 enable_edge_filter,
11346 smooth_neighbor,
11347 &mut prediction,
11348 );
11349 }
11350 prediction
11351 };
11352 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
11353 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
11354 if crate::envflags::env_flag!("EC_PRED") {
11355 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
11356 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
11357 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
11358 eprintln!(
11359 "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor)
11360 );
11361 }
11362 for row in 0..bh {
11363 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
11364 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
11365 // whose padded width is not superblock aligned hangs past it.
11366 if y + row >= self.height {
11367 break;
11368 }
11369 for col in 0..bw {
11370 if x + col >= self.width {
11371 break;
11372 }
11373 let idx = row * bw + col;
11374 let mut base = i32::from(prediction[idx]);
11375 if let Some((alpha_q3, ac_q3)) = cfl {
11376 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
11377 }
11378 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
11379 self.data[(y + row) * self.width + x + col] = sample;
11380 }
11381 }
11382 }
11383
11384 /// Predicts under `mode` then adds `residual` (side*side, raster),
11385 /// writing the clamped reconstruction back into the plane at `(x, y)`.
11386 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
11387 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
11388 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
11389 /// order (cfl.c).
11390 #[track_caller]
11391 fn reconstruct(
11392 &mut self,
11393 x: usize,
11394 y: usize,
11395 side: usize,
11396 mode: usize,
11397 angle_delta: i32,
11398 reach: Reach,
11399 residual: &[i32],
11400 cfl: Option<(i32, &[i32])>,
11401 filter_intra: Option<usize>,
11402 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
11403 // libaom `get_filt_type`): true when the block's above OR left
11404 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
11405 // Callers pass their own plane's neighbour-mode check
11406 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
11407 // callers until a smooth/paeth `uv_mode` can reach this call at all
11408 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
11409 // keeps `false` exact for chroma without this fn needing to know why.
11410 smooth_neighbor: bool,
11411 ) {
11412 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
11413 // takes priority over `predict()`/`predict_filter_intra` entirely --
11414 // palette prediction needs no edge pixels at all.
11415 let prediction = if let Some(buf) = take_palette_pred() {
11416 buf
11417 } else {
11418 let (above, left, corner) = self.edges(x, y, side, reach);
11419 let mut prediction = vec![0u16; side * side];
11420 if let Some(fi_mode) = filter_intra {
11421 crate::intra::predict_filter_intra(
11422 fi_mode,
11423 above.as_deref(),
11424 left.as_deref(),
11425 corner,
11426 side,
11427 side,
11428 &mut prediction,
11429 );
11430 } else {
11431 // `enable_intra_edge_filter` is the sequence header's own flag
11432 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
11433 // call, never per-block) -- threading it through every
11434 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
11435 // dozen sites for a value that never changes mid-decode, so it
11436 // rides a thread-local instead (this decoder is single-threaded
11437 // per stream).
11438 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
11439 predict(
11440 mode as u8,
11441 angle_delta,
11442 above.as_deref(),
11443 left.as_deref(),
11444 corner,
11445 side,
11446 side,
11447 enable_edge_filter,
11448 smooth_neighbor,
11449 &mut prediction,
11450 );
11451 }
11452 prediction
11453 };
11454 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
11455 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
11456 if crate::envflags::env_flag!("EC_PRED") {
11457 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
11458 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
11459 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
11460 eprintln!(
11461 "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor)
11462 );
11463 }
11464 for row in 0..side {
11465 // lane-sb128c r8: libaom's frame buffer is superblock
11466 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
11467 // transform unit of a 128x64 block at the BOTTOM frame edge
11468 // can hang past the last padded row (1920x792: a unit at
11469 // y=768 wants 832 rows of an 800-row buffer, which panicked
11470 // the film's key frames). Those samples are outside the
11471 // frame: never output, and no block below ever references
11472 // them.
11473 if y + row >= self.height {
11474 break;
11475 }
11476 for col in 0..side {
11477 if x + col >= self.width {
11478 break;
11479 }
11480 let idx = row * side + col;
11481 let mut base = i32::from(prediction[idx]);
11482 if let Some((alpha_q3, ac_q3)) = cfl {
11483 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
11484 }
11485 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
11486 self.data[(y + row) * self.width + x + col] = sample;
11487 }
11488 }
11489 }
11490}
11491
11492/// Reads one plane's transform block, reconstructs it into `plane` at
11493/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
11494#[allow(clippy::too_many_arguments)]
11495fn read_plane(
11496 dec: &mut SymbolDecoder,
11497 cdfs: &mut Cdfs,
11498 set: TxbSet,
11499 scan: &[u16],
11500 plane_idx: usize,
11501 around: (bool, bool, i32),
11502 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
11503 // it for every plane's `txb` lookup (it is what an intra transform type's
11504 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
11505 tx_mode: usize,
11506 predict_mode: usize,
11507 angle_delta: i32,
11508 reach: Reach,
11509 plane: &mut PlaneBuf,
11510 x: usize,
11511 y: usize,
11512 side: usize,
11513 tx_side: usize,
11514 base_q_idx: u8,
11515 cfl: Option<(i32, &[i32])>,
11516 filter_intra: Option<usize>,
11517 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
11518 // smaller than its own block (spec `get_txb_ctx_general`'s
11519 // `plane_bsize != tx_size` branch), carrying the already-looked-up
11520 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
11521 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
11522 // formula below.
11523 luma_skip_ctx: Option<usize>,
11524 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
11525 smooth_neighbor: bool,
11526) -> Result<Vec<i32>> {
11527 let skip_ctx = if plane_idx == 0 {
11528 luma_skip_ctx.unwrap_or(0)
11529 } else {
11530 // libaom `get_txb_ctx`: a chroma unit's context is
11531 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
11532 // plane block is bigger than the transform. Our chroma tables hold the
11533 // offset-7 rows first, so the caller adds 3 for the bigger-block case
11534 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
11535 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
11536 };
11537 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
11538 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
11539 // not by the block's ordinary `mode` (which is always DC_PRED whenever
11540 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
11541 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
11542 // filter-intra in AV1).
11543 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
11544 let mut coding = cdfs.txb(set, tx_mode);
11545 // Luma's `default_tx_type` is only a fallback for the sizes whose
11546 // `TxbSet` carries no symbol at all (32-point and up), which the spec
11547 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
11548 // *never* its own coded symbol (`coding.tx_type` is always `None` for
11549 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
11550 // the plane's own predicted mode (`default_intra_tx_type`) -- except
11551 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
11552 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
11553 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
11554 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
11555 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
11556 // narrows there — only `Chroma32` and up do).
11557 let default_tx_type = if plane_idx == 0 || side >= 32 {
11558 TxType::DctDct
11559 } else if let Some(inherited) = INTRABC_CHROMA_TX.with(std::cell::Cell::get) {
11560 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
11561 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
11562 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
11563 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
11564 // [`read_inter_plane`]'s own `side < 32` guard).
11565 inherited
11566 } else {
11567 default_intra_tx_type(predict_mode as u8)
11568 };
11569 let (grid, tx_type) = read_coeffs(
11570 dec,
11571 &mut coding,
11572 scan,
11573 skip_ctx,
11574 dc_sign_ctx(around.2),
11575 default_tx_type,
11576 None,
11577 )?;
11578 note_chroma_class1(plane_idx, tx_type);
11579 if plane_idx == 0 {
11580 LUMA_TX_TYPE.with(|c| c.set(tx_type));
11581 }
11582 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
11583 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
11584 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
11585 // guard also assumes.
11586 let levels = if tx_side == side {
11587 grid
11588 } else {
11589 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
11590 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
11591 // keyed by that true size, not the coded corner's -- so the corner
11592 // goes into the top-left of a `side`-sized grid, not the reverse.
11593 let mut full = vec![0i32; side * side];
11594 for row in 0..tx_side {
11595 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
11596 }
11597 full
11598 };
11599 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
11600 let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
11601 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11602 eprintln!(
11603 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
11604 );
11605 }
11606 plane.reconstruct(
11607 x,
11608 y,
11609 side,
11610 predict_mode,
11611 angle_delta,
11612 reach,
11613 &residual,
11614 cfl,
11615 filter_intra,
11616 smooth_neighbor,
11617 );
11618 Ok(if tx_side == side {
11619 residual_grid_placeholder(&levels, side)
11620 } else {
11621 levels
11622 })
11623}
11624
11625/// `record`'s neighbour state only reads whether *the coded grid* (not the
11626/// residual) has nonzero entries, so the levels this function already built
11627/// are what it wants back; this helper exists only to name that clearly at
11628/// the one call site where `tx_side == side`.
11629fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
11630 levels.to_vec()
11631}
11632
11633/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
11634/// three planes, reconstructing them into `y`/`u`/`v` and updating
11635/// `neighbours`.
11636#[allow(clippy::too_many_arguments)]
11637fn decode_block(
11638 dec: &mut SymbolDecoder,
11639 cdfs: &mut Cdfs,
11640 neighbours: &mut Neighbours,
11641 at: (usize, usize),
11642 side: usize,
11643 luma_set: TxbSet,
11644 chroma_set: TxbSet,
11645 luma_tx: usize,
11646 chroma_tx: usize,
11647 scans: (&[u16], &[u16]),
11648 cfl: bool,
11649 y: &mut PlaneBuf,
11650 u: &mut PlaneBuf,
11651 v: &mut PlaneBuf,
11652 base_q_idx: u8,
11653 enable_filter_intra: bool,
11654 allow_screen_content_tools: bool,
11655 allow_intrabc: bool,
11656 scan32: &[u16],
11657 scan16: &[u16],
11658 scan8: &[u16],
11659 scan4: &[u16],
11660 tx_select: bool,
11661 reduced_tx_set: bool,
11662) -> Result<()> {
11663 let (r, c) = at;
11664 let (px, py) = (c * SUB, r * SUB);
11665 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
11666 let palette_uv_cache = neighbours.palette_uv_cache(at);
11667 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
11668 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
11669 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
11670 read_intra_mode(
11671 dec,
11672 cdfs,
11673 nb_above_mode,
11674 nb_left_mode,
11675 cfl,
11676 side,
11677 enable_filter_intra,
11678 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
11679 allow_screen_content_tools,
11680 allow_intrabc,
11681 Some((palette_ctx, &palette_cache)),
11682 &palette_uv_cache,
11683 r * (SUB / MI),
11684 c * (SUB / MI),
11685 )?;
11686 if at_tile_left && palette_y.is_some() {
11687 PALETTE_TILE_LEFT_HITS.with(|c| c.set(c.get() + 1));
11688 }
11689 let intrabc_dv = INTRABC_DV.with(|c| c.take());
11690 // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
11691 // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
11692 // partition tree (`read_var_tx_size`), a syntax element this decoder has
11693 // nowhere -- reading the intra `tx_depth` symbol instead would desync.
11694 if intrabc_dv.is_some() && tx_select && !skip {
11695 return Err(unsupported(
11696 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
11697 ));
11698 }
11699 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
11700 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
11701 // actual chroma-from-luma correlation, same as this decoder always did.
11702 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11703 DC_PRED
11704 } else {
11705 uv_mode
11706 };
11707 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
11708 if smooth_neighbor {
11709 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
11710 }
11711 let smooth_neighbor_uv =
11712 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
11713 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11714 eprintln!(
11715 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
11716 angle_delta_uv={angle_delta_uv}"
11717 );
11718 }
11719 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
11720 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
11721 // block, skipped or not. `logical_tx` is what the loop filter's edge
11722 // lookup and the next block's own `tx_size_context` want (the *nominal*
11723 // transform size -- 64 even for the 64x64 corner-scanned case, spec
11724 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
11725 // which only differs from it at that one corner case.
11726 let (logical_tx, coeff_tx_side) = if tx_select {
11727 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
11728 (resolved, if resolved == 64 { 32 } else { resolved })
11729 } else {
11730 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
11731 // TX_64X64, so a 128x128 block is always FOUR luma transform units
11732 // even with `tx_select` off -- the TU loop below, never the
11733 // single-unit path.
11734 (side.min(64), luma_tx)
11735 };
11736 if tx_select && logical_tx < side && uv_mode != DC_PRED {
11737 SQ_CHROMA_TX_HITS.with(|c| c.set(c.get() + 1));
11738 }
11739 let luma_set = if tx_select {
11740 txbset_for(logical_tx, reduced_tx_set)
11741 } else {
11742 luma_set
11743 };
11744 let luma_set = if intrabc_dv.is_some() {
11745 txbset_for_inter(logical_tx, reduced_tx_set)
11746 } else {
11747 luma_set
11748 };
11749 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
11750 let reach = Reach::of(side, px, py, y.width, y.height);
11751 let (cpx, cpy) = (px / 2, py / 2);
11752 let chroma_side = side / 2;
11753 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
11754 // frame's own pre-loop-filter reconstruction (all loop filters are off
11755 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
11756 // block vector, with the BILINEAR kernel libaom forces for intrabc --
11757 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
11758 // odd, which is exactly what the bilinear taps then interpolate.
11759 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
11760 let mut yb = vec![0u16; side * side];
11761 mc::predict_with_filter(
11762 &y.data, y.width, y.true_width, y.true_height,
11763 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
11764 side, side, mc::InterpFilterKind::Bilinear, &mut yb,
11765 );
11766 let mut ub = vec![0u16; chroma_side * chroma_side];
11767 mc::predict_with_filter(
11768 &u.data, u.width, u.true_width, u.true_height,
11769 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
11770 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
11771 );
11772 let mut vb = vec![0u16; chroma_side * chroma_side];
11773 mc::predict_with_filter(
11774 &v.data, v.width, v.true_width, v.true_height,
11775 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
11776 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
11777 );
11778 (yb, ub, vb)
11779 });
11780 if let Some((yb, _, _)) = &intrabc_bufs {
11781 set_palette_pred(yb.clone());
11782 }
11783 // A palette-Y block's own prediction is the reconstructed colour-index
11784 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
11785 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
11786 // parameter through this function's dozen `y.reconstruct`/`read_plane`
11787 // sites. A split luma transform (`tx_select && logical_tx != side`)
11788 // would need the map sliced per-TU -- untested against a real
11789 // `--enable-palette=1` stream this round, so refuse by name rather than
11790 // guess at the slicing (charter's own named-acceptable fallback).
11791 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
11792 py.map
11793 .iter()
11794 .map(|&idx| py.colors[idx as usize])
11795 .collect()
11796 });
11797 // With one luma transform unit the whole `side`x`side` map is the
11798 // prediction; with several (`logical_tx != side`) each unit takes its own
11799 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
11800 // below (lane-palette2 r7) -- setting the full-block buffer here would be
11801 // taken by the FIRST unit and indexed at the wrong stride.
11802 if let Some(buf) = &palette_y_buf
11803 && logical_tx == side
11804 {
11805 set_palette_pred(buf.clone());
11806 }
11807 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
11808 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
11809 // plane's own `reconstruct`/`read_plane` call below (never both planes at
11810 // once), since Y's own set-then-take already emptied the slot by the time
11811 // either of these run.
11812 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
11813 (
11814 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
11815 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
11816 )
11817 });
11818 // The chroma half of the intrabc prediction rides the same per-plane
11819 // override slot the UV-palette buffers do (set fresh before each plane's
11820 // own `reconstruct`/`read_plane` call below).
11821 let palette_uv_bufs = match &intrabc_bufs {
11822 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
11823 None => palette_uv_bufs,
11824 };
11825 if skip {
11826 // A skipped block codes no residual syntax at all (spec 5.11.34):
11827 // straight prediction, on every plane.
11828 //
11829 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
11830 // is skipped (only an INTER skip forces the largest transform), and
11831 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
11832 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
11833 // already written left/above of it inside this same block. Predicting
11834 // the whole `side`x`side` at once gives a different (uniformly off by
11835 // ~1) answer, which is exactly the residue this lane was chasing.
11836 // The palette/intrabc override path keeps the single-call shape (its
11837 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
11838 // untested for skip and unreachable in these streams).
11839 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
11840 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
11841 // per-unit prediction is keyed on the transform being smaller than
11842 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
11843 // narrower meaning (a READ split tx depth).
11844 let split_tx_skip =
11845 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
11846 if split_tx_skip {
11847 if tx_select {
11848 SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
11849 }
11850 let n_axis = side / logical_tx;
11851 for tu_row in 0..n_axis {
11852 for tu_col in 0..n_axis {
11853 let tu_px = px + tu_col * logical_tx;
11854 let tu_py = py + tu_row * logical_tx;
11855 if tu_px >= y.true_width || tu_py >= y.true_height {
11856 continue;
11857 }
11858 let tu_reach = tu_reach(
11859 side,
11860 side,
11861 tu_col * logical_tx,
11862 tu_row * logical_tx,
11863 logical_tx,
11864 reach,
11865 px,
11866 py,
11867 y.width,
11868 y.height,
11869 );
11870 y.reconstruct(
11871 tu_px,
11872 tu_py,
11873 logical_tx,
11874 mode,
11875 angle_delta_y,
11876 tu_reach,
11877 &vec![0i32; logical_tx * logical_tx],
11878 None,
11879 filter_intra,
11880 smooth_neighbor,
11881 );
11882 }
11883 }
11884 } else {
11885 y.reconstruct(
11886 px,
11887 py,
11888 side,
11889 mode,
11890 angle_delta_y,
11891 reach,
11892 &vec![0i32; side * side],
11893 None,
11894 filter_intra,
11895 smooth_neighbor,
11896 );
11897 }
11898 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
11899 let cn = (chroma_side / chroma_tx).max(1);
11900 for cu_row in 0..cn {
11901 for cu_col in 0..cn {
11902 let luma_span = chroma_tx * 2;
11903 let cu_r = if cn == 1 {
11904 reach
11905 } else {
11906 tu_reach(
11907 side, side,
11908 cu_col * luma_span, cu_row * luma_span, luma_span,
11909 reach, px, py, y.width, y.height,
11910 )
11911 };
11912 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
11913 if let Some((ub, _)) = &palette_uv_bufs {
11914 set_palette_pred(ub.clone());
11915 }
11916 u.reconstruct(
11917 cu_x,
11918 cu_y,
11919 chroma_tx,
11920 uv_predict_mode,
11921 angle_delta_uv,
11922 cu_r,
11923 &vec![0i32; chroma_tx * chroma_tx],
11924 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
11925 None,
11926 smooth_neighbor_uv,
11927 );
11928 if let Some((_, vb)) = &palette_uv_bufs {
11929 set_palette_pred(vb.clone());
11930 }
11931 v.reconstruct(
11932 cu_x,
11933 cu_y,
11934 chroma_tx,
11935 uv_predict_mode,
11936 angle_delta_uv,
11937 cu_r,
11938 &vec![0i32; chroma_tx * chroma_tx],
11939 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
11940 None,
11941 smooth_neighbor_uv,
11942 );
11943 }
11944 }
11945 let luma_grid = vec![0i32; side * side];
11946 let u_grid = vec![0i32; chroma_side * chroma_side];
11947 let v_grid = vec![0i32; chroma_side * chroma_side];
11948 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
11949 } else if logical_tx == side {
11950 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
11951 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
11952 // that arm was redundant -- and wrong at 128, where
11953 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
11954 // block is four units whether or not `tx_select` is on.
11955 // A single luma transform unit -- the old path, unchanged (including
11956 // the 64x64 corner case, `logical_tx == side == 64` with
11957 // `coeff_tx_side == 32`).
11958 let around = neighbours.around(at, side);
11959 let luma_grid = read_plane(
11960 dec,
11961 cdfs,
11962 luma_set,
11963 luma_scan,
11964 0,
11965 around[0],
11966 mode,
11967 mode,
11968 angle_delta_y,
11969 reach,
11970 y,
11971 px,
11972 py,
11973 side,
11974 coeff_tx_side,
11975 base_q_idx,
11976 None,
11977 filter_intra,
11978 None,
11979 smooth_neighbor,
11980 )?;
11981 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
11982 // Armed for exactly this block's two chroma reads (see
11983 // [`INTRABC_CHROMA_TX`]); the luma call above just set
11984 // [`LUMA_TX_TYPE`] to the type it coded.
11985 if intrabc_dv.is_some() {
11986 INTRABC_CHROMA_TX.with(|c| c.set(Some(LUMA_TX_TYPE.with(std::cell::Cell::get))));
11987 }
11988 if let Some((ub, _)) = &palette_uv_bufs {
11989 set_palette_pred(ub.clone());
11990 }
11991 let u_grid = read_plane(
11992 dec,
11993 cdfs,
11994 chroma_set,
11995 scans.1,
11996 1,
11997 around[1],
11998 mode,
11999 uv_predict_mode,
12000 angle_delta_uv,
12001 reach,
12002 u,
12003 cpx,
12004 cpy,
12005 chroma_side,
12006 chroma_tx,
12007 base_q_idx,
12008 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
12009 None,
12010 None,
12011 smooth_neighbor_uv,
12012 )?;
12013 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12014 eprintln!(
12015 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
12016 &u.data[cpy * u.width + cpx..][..chroma_side]
12017 );
12018 }
12019 if let Some((_, vb)) = &palette_uv_bufs {
12020 set_palette_pred(vb.clone());
12021 }
12022 let v_grid = read_plane(
12023 dec,
12024 cdfs,
12025 chroma_set,
12026 scans.1,
12027 2,
12028 around[2],
12029 mode,
12030 uv_predict_mode,
12031 angle_delta_uv,
12032 reach,
12033 v,
12034 cpx,
12035 cpy,
12036 chroma_side,
12037 chroma_tx,
12038 base_q_idx,
12039 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
12040 None,
12041 None,
12042 smooth_neighbor_uv,
12043 )?;
12044 INTRABC_CHROMA_TX.with(|c| c.set(None));
12045 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
12046 } else {
12047 // Several luma transform units, raster order (spec
12048 // `transform_block`'s loop): the block's resolved transform is
12049 // genuinely smaller than its own side, so each tile of it predicts
12050 // and codes independently, its own context read fresh off whatever
12051 // the earlier tiles in this same block already wrote -- the same
12052 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
12053 let n_axis = side / logical_tx;
12054 let cn = (chroma_side / chroma_tx).max(1);
12055 // libaom's transform-block loop is over 64x64 luma "mu" chunks
12056 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
12057 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
12058 // before moving to the next one. Below 128 a block is a single chunk,
12059 // so this is byte-for-byte the all-luma-then-all-chroma order that has
12060 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
12061 // and reading all four luma units first desyncs the tile at the second
12062 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
12063 let nchunk = (side / 64).max(1);
12064 // `cn > 1` means the uv plane block is larger than the uv transform,
12065 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
12066 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
12067 let tpc = (n_axis / nchunk).max(1);
12068 let cpc = (cn / nchunk).max(1);
12069 let mut last_grids = [Vec::new(), Vec::new()];
12070 let mut units: Vec<((usize, usize), usize, Vec<i32>, Vec<i32>)> = Vec::new();
12071 for ch_row in 0..nchunk {
12072 for ch_col in 0..nchunk {
12073 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
12074 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
12075 let tu_mi = (
12076 mi_r + tu_row * (logical_tx / MI),
12077 mi_c + tu_col * (logical_tx / MI),
12078 );
12079 let tu_px = px + tu_col * logical_tx;
12080 let tu_py = py + tu_row * logical_tx;
12081 // Same libaom clip as `decode_rect_split`'s loop above; a
12082 // square block only hangs off the frame when the frame's mi
12083 // dimensions are odd at the block's own level.
12084 if tu_px >= y.true_width || tu_py >= y.true_height {
12085 continue;
12086 }
12087 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
12088 // A transform unit inside a block is NOT a block at that
12089 // position (lane-palette2 r12): `Reach::of` granted the
12090 // top-right 8x8 unit of a 16x16 D203 block bottom-left
12091 // pixels libaom refuses outright (`col_off > 0`), which is
12092 // the diagonal wedge seed 46 reconstructed wrong.
12093 let tu_reach = tu_reach(
12094 side,
12095 side,
12096 tu_col * logical_tx,
12097 tu_row * logical_tx,
12098 logical_tx,
12099 reach,
12100 px,
12101 py,
12102 y.width,
12103 y.height,
12104 );
12105 // This transform unit's own bsize (`logical_tx`) is smaller
12106 // than the block it sits in (`side`), so `txb_skip_ctx` is
12107 // the neighbour-magnitude table, not the lone-TU 0 (spec
12108 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
12109 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
12110 if let Some(buf) = &palette_y_buf {
12111 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12112 let mut window = vec![0u16; logical_tx * logical_tx];
12113 for row in 0..logical_tx {
12114 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
12115 window[row * logical_tx..][..logical_tx]
12116 .copy_from_slice(&buf[src..][..logical_tx]);
12117 }
12118 set_palette_pred(window);
12119 }
12120 let tu_grid = read_plane(
12121 dec,
12122 cdfs,
12123 luma_set,
12124 luma_scan,
12125 0,
12126 tu_around,
12127 mode,
12128 mode,
12129 angle_delta_y,
12130 tu_reach,
12131 y,
12132 tu_px,
12133 tu_py,
12134 logical_tx,
12135 // The unit's own COEFFICIENT grid, half its side at
12136 // TX_64X64 (a 64-point transform codes nothing past 32);
12137 // identical to `logical_tx` at every smaller size
12138 // (lane-sb128b r1).
12139 coeff_tx_side,
12140 base_q_idx,
12141 None,
12142 filter_intra,
12143 Some(tu_skip_ctx),
12144 smooth_neighbor,
12145 )?;
12146 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12147 eprintln!(
12148 "TRACE tu_bitpos mi=({},{}) tell={}",
12149 tu_mi.0,
12150 tu_mi.1,
12151 dec.debug_bitpos()
12152 );
12153 }
12154 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
12155 }
12156 }
12157 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
12158 // this still runs after every luma unit of the block.
12159 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
12160 // The block's uv plane block is `chroma_side` across but its uv
12161 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
12162 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
12163 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
12164 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
12165 // FOUR units (lane-sb128b r2) -- one per mu chunk.
12166 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
12167 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
12168 // The chroma context arrays are indexed in LUMA mi, so this
12169 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
12170 // pixels span `2 * chroma_tx` luma ones.
12171 let luma_span = chroma_tx * 2;
12172 let cu_mi = (
12173 mi_r + cu_row * (luma_span / MI),
12174 mi_c + cu_col * (luma_span / MI),
12175 );
12176 let cu_around = neighbours.around_mi(cu_mi, luma_span);
12177 let cu_reach = if cn == 1 {
12178 reach
12179 } else {
12180 tu_reach(
12181 side, side,
12182 cu_col * luma_span, cu_row * luma_span, luma_span,
12183 reach, px, py, y.width, y.height,
12184 )
12185 };
12186 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
12187 if let Some((ub, _)) = &palette_uv_bufs {
12188 set_palette_pred(ub.clone());
12189 }
12190 let u_grid = read_plane(
12191 dec, cdfs, chroma_set, scans.1, 1, cu_around[1], mode,
12192 uv_predict_mode, angle_delta_uv, cu_reach, u, cu_x, cu_y,
12193 chroma_tx, chroma_tx, base_q_idx,
12194 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
12195 None, chroma_ctx_offset, smooth_neighbor_uv,
12196 )?;
12197 if let Some((_, vb)) = &palette_uv_bufs {
12198 set_palette_pred(vb.clone());
12199 }
12200 let v_grid = read_plane(
12201 dec, cdfs, chroma_set, scans.1, 2, cu_around[2], mode,
12202 uv_predict_mode, angle_delta_uv, cu_reach, v, cu_x, cu_y,
12203 chroma_tx, chroma_tx, base_q_idx,
12204 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
12205 None, chroma_ctx_offset, smooth_neighbor_uv,
12206 )?;
12207 if cn > 1 {
12208 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12209 // Immediately, so the NEXT unit of this same block reads
12210 // this one's coefficient context (libaom's chroma
12211 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
12212 // 1 from this left neighbour -- measured against aomdec).
12213 // The same writes are replayed after `record_split_luma`
12214 // below, which would otherwise clobber them whole-block.
12215 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
12216 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
12217 units.push((cu_mi, luma_span, u_grid.clone(), v_grid.clone()));
12218 }
12219 last_grids = [u_grid, v_grid];
12220 }
12221 }
12222 }
12223 }
12224 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
12225 // context write; at `cn > 1` the per-unit writes above are what the
12226 // next block reads, so they run after this (last writer wins).
12227 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
12228 for (cu_mi, luma_span, u_grid, v_grid) in &units {
12229 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
12230 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
12231 }
12232 }
12233 // Unconditional, `size == 0` for a non-palette block: clears any stale
12234 // neighbour palette state the same way [`Neighbours::record`] always
12235 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
12236 // (the split-luma-TU branch above always refuses before reaching here
12237 // when `palette_y` is `Some`, so it is never live for that branch).
12238 let (py_size, py_colors) = palette_y
12239 .as_ref()
12240 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12241 neighbours.record_palette_y(at, side, py_size, py_colors);
12242 let (puv_size, puv_colors) = palette_uv
12243 .as_ref()
12244 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12245 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
12246 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
12247 neighbours.fill_lf_grid(
12248 (r * (SUB / MI), c * (SUB / MI)),
12249 side / MI,
12250 logical_tx as u8,
12251 0,
12252 );
12253 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
12254 Ok(())
12255}
12256
12257thread_local! {
12258 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
12259 /// root's HORZ arm, and 64x128 ones at its VERT arm.
12260 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
12261 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
12262 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
12263 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
12264 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
12265 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
12266 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
12267 /// inter frame) -- (128x64, 64x128).
12268 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
12269 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
12270 /// handed back var-tx leaves, so the per-transform-unit luma publication
12271 /// loop never ran and the block has to clear its own luma coefficient
12272 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
12273 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
12274 /// non-vacuous.
12275 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
12276}
12277
12278/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
12279pub fn skip_vartx_luma_reset_hits() -> usize {
12280 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
12281}
12282
12283/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
12284pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
12285 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
12286}
12287
12288/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
12289/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
12290pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
12291 (
12292 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
12293 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
12294 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
12295 )
12296}
12297
12298/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
12299/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
12300/// `decode_inter_block`'s own rect path).
12301///
12302/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
12303/// transform unit, with the 128-specific geometry:
12304/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
12305/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
12306/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
12307/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
12308/// same CDF a 64x64 square block reads).
12309/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
12310/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
12311/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
12312/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
12313/// a chunk before moving to the next (the interleave lane-sb128b r3
12314/// measured at the 128x128 NONE root).
12315/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
12316/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
12317/// No CfL, no filter intra (both cap at 32x32) and no palette
12318/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
12319/// reader's own size gates already say so, and the guard below is defensive.
12320#[allow(clippy::too_many_arguments)]
12321fn decode_block_128rect(
12322 dec: &mut SymbolDecoder,
12323 cdfs: &mut Cdfs,
12324 neighbours: &mut Neighbours,
12325 at: (usize, usize),
12326 bw: usize,
12327 bh: usize,
12328 y: &mut PlaneBuf,
12329 u: &mut PlaneBuf,
12330 v: &mut PlaneBuf,
12331 base_q_idx: u8,
12332 enable_filter_intra: bool,
12333 allow_screen_content_tools: bool,
12334 tx_select: bool,
12335 reduced_tx_set: bool,
12336) -> Result<()> {
12337 let (r, c) = at;
12338 let (px, py) = (c * SUB, r * SUB);
12339 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
12340 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
12341 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
12342 let palette_uv_cache = neighbours.palette_uv_cache(at);
12343 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
12344 read_intra_mode_rect(
12345 dec,
12346 cdfs,
12347 nb_above_mode,
12348 nb_left_mode,
12349 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
12350 // 13-symbol no-CFL CDF here, never the 14-symbol one.
12351 false,
12352 true,
12353 bw,
12354 bh,
12355 enable_filter_intra,
12356 neighbours.skip_txfm_ctx(mi_r, mi_c),
12357 allow_screen_content_tools,
12358 Some((palette_ctx, &palette_cache)),
12359 &palette_uv_cache,
12360 mi_r,
12361 mi_c,
12362 )?;
12363 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
12364 return Err(unsupported(
12365 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
12366 their size gates caps at 64x64 or below, so none of these symbols exists there)",
12367 ));
12368 }
12369 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
12370 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
12371 if smooth_neighbor {
12372 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
12373 }
12374 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
12375 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
12376 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
12377 let in_inter = INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some();
12378 let depth = if tx_select {
12379 // lane-inter128intra r1: on an INTER frame `get_tx_size_context` reads
12380 // the real `TXFM_CONTEXT` bands, and compares them against
12381 // `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- TX_64X64 for
12382 // every 128-axis block, hence the `min(64)`.
12383 let ctx = if in_inter {
12384 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64))
12385 } else {
12386 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
12387 };
12388 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
12389 } else {
12390 0
12391 };
12392 if depth != 0 {
12393 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
12394 }
12395 INTRA_SB128_DEPTH_HITS.with(|c| {
12396 let mut h = c.get();
12397 h[depth.min(2)] += 1;
12398 c.set(h);
12399 });
12400 let logical_tx = 64 >> depth;
12401 // A 64-point transform codes nothing past its low 32 coefficients.
12402 let coeff_tx_side = logical_tx.min(32);
12403 let luma_set = txbset_for(logical_tx, reduced_tx_set);
12404 let luma_scan = default_scan(coeff_tx_side);
12405 let chroma_tx = 32;
12406 let chroma_scan = default_scan(chroma_tx);
12407 let (cpx, cpy) = (px / 2, py / 2);
12408 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
12409 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
12410 let (nch_x, nch_y) = (bw / 64, bh / 64);
12411 // One 32x32 chroma unit per mu chunk, per plane.
12412 debug_assert_eq!((chroma_w / chroma_tx, chroma_h / chroma_tx), (nch_x, nch_y));
12413 let tpc = 64 / logical_tx;
12414 let zero_tu = vec![0i32; logical_tx * logical_tx];
12415 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
12416 let mut last_grids = [Vec::new(), Vec::new()];
12417 let mut units: Vec<((usize, usize), Vec<i32>, Vec<i32>)> = Vec::new();
12418 for ch_row in 0..nch_y {
12419 for ch_col in 0..nch_x {
12420 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
12421 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
12422 let tu_mi = (
12423 mi_r + tu_row * (logical_tx / MI),
12424 mi_c + tu_col * (logical_tx / MI),
12425 );
12426 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
12427 // libaom clips the transform loop to
12428 // `max_blocks_wide/high`: a unit whose top-left sample is
12429 // outside the frame is never coded.
12430 if tu_px >= y.true_width || tu_py >= y.true_height {
12431 continue;
12432 }
12433 // Edge availability of a unit INSIDE a block, with the
12434 // 128 geometry -- `has_top_right` is false for a block
12435 // whose largest side is > 64, which [`Reach::of_rect`]
12436 // already answered for the block and [`tu_reach`] carries
12437 // down to the units on its own top row.
12438 let tu_r = tu_reach(
12439 bw,
12440 bh,
12441 tu_col * logical_tx,
12442 tu_row * logical_tx,
12443 logical_tx,
12444 reach,
12445 px,
12446 py,
12447 y.width,
12448 y.height,
12449 );
12450 if skip {
12451 y.reconstruct(
12452 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
12453 None, smooth_neighbor,
12454 );
12455 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
12456 continue;
12457 }
12458 // The unit is smaller than its block, so `txb_skip_ctx`
12459 // is the neighbour-magnitude table, never the lone-TU 0.
12460 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
12461 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
12462 let tu_grid = read_plane(
12463 dec,
12464 cdfs,
12465 luma_set,
12466 &luma_scan,
12467 0,
12468 tu_around,
12469 mode,
12470 mode,
12471 angle_delta_y,
12472 tu_r,
12473 y,
12474 tu_px,
12475 tu_py,
12476 logical_tx,
12477 coeff_tx_side,
12478 base_q_idx,
12479 None,
12480 None,
12481 Some(tu_skip_ctx),
12482 smooth_neighbor,
12483 )?;
12484 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
12485 }
12486 }
12487 // The chroma context arrays are indexed in LUMA mi, so this
12488 // unit's anchor is its own 64x64 mu chunk.
12489 let luma_span = chroma_tx * 2;
12490 let cu_mi = (
12491 mi_r + ch_row * (luma_span / MI),
12492 mi_c + ch_col * (luma_span / MI),
12493 );
12494 let cu_r = tu_reach(
12495 bw,
12496 bh,
12497 ch_col * luma_span,
12498 ch_row * luma_span,
12499 luma_span,
12500 reach,
12501 px,
12502 py,
12503 y.width,
12504 y.height,
12505 );
12506 let (cu_x, cu_y) = (cpx + ch_col * chroma_tx, cpy + ch_row * chroma_tx);
12507 if skip {
12508 u.reconstruct(
12509 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
12510 None, smooth_neighbor_uv,
12511 );
12512 v.reconstruct(
12513 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
12514 None, smooth_neighbor_uv,
12515 );
12516 continue;
12517 }
12518 let cu_around = neighbours.around_mi(cu_mi, luma_span);
12519 let u_grid = read_plane(
12520 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 1, cu_around[1], mode, uv_predict_mode,
12521 angle_delta_uv, cu_r, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
12522 Some(3), smooth_neighbor_uv,
12523 )?;
12524 let v_grid = read_plane(
12525 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 2, cu_around[2], mode, uv_predict_mode,
12526 angle_delta_uv, cu_r, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
12527 Some(3), smooth_neighbor_uv,
12528 )?;
12529 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12530 // Immediately, so the NEXT unit of this same block reads this
12531 // one's coefficient context; replayed after `record_split_luma_rect`
12532 // below, which would otherwise clobber them whole-block.
12533 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
12534 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
12535 units.push((cu_mi, u_grid.clone(), v_grid.clone()));
12536 last_grids = [u_grid, v_grid];
12537 }
12538 }
12539 if skip {
12540 neighbours.record_rect(
12541 at,
12542 bw,
12543 bh,
12544 mode,
12545 uv_predict_mode,
12546 &[
12547 vec![0i32; bw * bh],
12548 vec![0i32; chroma_w * chroma_h],
12549 vec![0i32; chroma_w * chroma_h],
12550 ],
12551 );
12552 } else {
12553 neighbours.record_split_luma_rect(
12554 at,
12555 bw,
12556 bh,
12557 mode,
12558 uv_predict_mode,
12559 [&last_grids[0], &last_grids[1]],
12560 );
12561 for (cu_mi, u_grid, v_grid) in &units {
12562 neighbours.record_mi_chroma(*cu_mi, 64, 64, 1, u_grid);
12563 neighbours.record_mi_chroma(*cu_mi, 64, 64, 2, v_grid);
12564 }
12565 }
12566 // No palette exists at this size; the unconditional stamp clears any
12567 // stale neighbour palette state, as every other block path does.
12568 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
12569 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
12570 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12571 neighbours.fill_lf_grid_rect(
12572 (mi_r, mi_c),
12573 bw / MI,
12574 bh / MI,
12575 logical_tx as u8,
12576 logical_tx as u8,
12577 0,
12578 );
12579 if in_inter {
12580 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
12581 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
12582 // inter frame, intra ones included: an intra block stamps its
12583 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
12584 // A key frame has no var-tx tree and its readers use the deblock grid,
12585 // so this is the inter path's alone.
12586 txfm_partition_update_rect(
12587 neighbours,
12588 (mi_r, mi_c),
12589 (logical_tx, logical_tx),
12590 (bw, bh),
12591 );
12592 INTRA128_IN_INTER_HITS.with(|c| {
12593 let mut h = c.get();
12594 h[usize::from(bw < bh)] += 1;
12595 c.set(h);
12596 });
12597 } else if bw > bh {
12598 INTRA_SB128_HORZ_HITS.with(|c| c.set(c.get() + 1));
12599 } else {
12600 INTRA_SB128_VERT_HITS.with(|c| c.set(c.get() + 1));
12601 }
12602 Ok(())
12603}
12604
12605
12606/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
12607/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
12608/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
12609/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
12610/// just-decoded mode, not the enclosing slot's stale one, is the true
12611/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
12612/// units, which is what its coefficient context (finer than [`SUB`]) is read
12613/// at. Returns the mode this leaf decoded, for the caller's own
12614/// `prev_leaf`/final mode-writeback bookkeeping.
12615#[allow(clippy::too_many_arguments)]
12616/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
12617/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
12618/// `above_mode[col]`, and its true above neighbour is the mi directly above
12619/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
12620/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
12621/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
12622/// (bottom-right) into both, as this path did, is right only when all four
12623/// leaves happen to share a mode. `done` may be short at the true frame edge
12624/// (the straddle caller filters positions off the frame), so each side falls
12625/// back to the last leaf actually decoded.
12626fn write_back_split_modes(
12627 neighbours: &mut Neighbours,
12628 done: &[((usize, usize), usize)],
12629 parent_mi: (usize, usize),
12630 slot: (usize, usize),
12631) {
12632 let (sr, sc) = slot;
12633 let Some(&(_, last)) = done.last() else {
12634 return;
12635 };
12636 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
12637 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
12638 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
12639}
12640
12641fn decode_leaf8(
12642 dec: &mut SymbolDecoder,
12643 cdfs: &mut Cdfs,
12644 neighbours: &mut Neighbours,
12645 outer_at: (usize, usize),
12646 leaf_mi: (usize, usize),
12647 scans: (&[u16], &[u16]),
12648 prev_leaf: Option<((usize, usize), usize)>,
12649 y: &mut PlaneBuf,
12650 u: &mut PlaneBuf,
12651 v: &mut PlaneBuf,
12652 base_q_idx: u8,
12653 enable_filter_intra: bool,
12654 allow_screen_content_tools: bool,
12655 allow_intrabc: bool,
12656 tx_select: bool,
12657 reduced_tx_set: bool,
12658) -> Result<usize> {
12659 let (r, c) = outer_at;
12660 // lane-modectx r1: the group's own availability-correct fallback pair, not
12661 // the raw coarse bands (which leak across a tile edge -- see
12662 // `modes_above_left`).
12663 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
12664 if let Some(((pr, pc), pmode)) = prev_leaf {
12665 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
12666 above_mode = pmode;
12667 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
12668 left_mode = pmode;
12669 }
12670 }
12671 // The mi-exact neighbour wins over both the coarse 16x16 slot and
12672 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
12673 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
12674 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
12675 // lane-rectsplitx r2 swept this arm into
12676 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
12677 // "no neighbour" at a tile edge, where the coarse cell holds the block
12678 // above/left of it inside the same 16x16.
12679 let (above_mode, left_mode) =
12680 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
12681 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
12682 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
12683 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
12684 // this leaf's `smooth_neighbor` is built from -- passing `false` here
12685 // filtered a directional chroma block's edge at the wrong strength
12686 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
12687 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
12688 // with the coarse [`SUB`] slot as the fallback when no block recorded
12689 // that exact mi cell.
12690 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
12691 if smooth_neighbor {
12692 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
12693 }
12694 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
12695 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
12696 // `decode_block` caller at 16x16 and up.
12697 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
12698 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
12699 // `read_palette_mode_info`), at its REAL mi position -- passing
12700 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
12701 // moment a real 8x8 palette block fired, which is where every 8-bit
12702 // `--tune-content=screen --min-partition-size=8` stream stopped.
12703 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
12704 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
12705 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
12706 read_intra_mode(
12707 dec,
12708 cdfs,
12709 above_mode,
12710 left_mode,
12711 true,
12712 8,
12713 enable_filter_intra,
12714 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
12715 allow_screen_content_tools,
12716 allow_intrabc,
12717 Some((palette_ctx, &palette_cache)),
12718 &palette_uv_cache,
12719 leaf_mi.0,
12720 leaf_mi.1,
12721 )?;
12722 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
12723 // `read_intra_mode` and then decoded the block as if it were ordinary
12724 // intra. libaom's `is_inter_block` counts an intrabc block
12725 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
12726 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
12727 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
12728 // same value with a different interval, so the tile desynced at the very
12729 // next symbol (class `wrong-alphabet-same-value`). Everything below
12730 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
12731 let intrabc_dv = INTRABC_DV.with(|c| c.take());
12732 if intrabc_dv.is_some() {
12733 LEAF8_INTRABC_HITS.with(|c| c.set(c.get() + 1));
12734 }
12735 if intrabc_dv.is_some() && tx_select && !skip {
12736 return Err(unsupported(
12737 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
12738 ));
12739 }
12740 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
12741 // index map, mapped through the base colours, IS the block's prediction --
12742 // carried to the next `reconstruct`/`read_plane` through the same
12743 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
12744 let palette_y_buf: Option<Vec<u16>> = palette_y
12745 .as_ref()
12746 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
12747 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
12748 (
12749 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12750 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12751 )
12752 });
12753 let (pal_y_size, pal_y_colors) =
12754 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12755 let (pal_uv_size, pal_uv_colors) =
12756 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12757 if palette_y.is_some() || palette_uv.is_some() {
12758 PALETTE_LEAF8_HITS.with(|c| c.set(c.get() + 1));
12759 }
12760 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12761 DC_PRED
12762 } else {
12763 uv_mode
12764 };
12765 neighbours.above_uv_mode[c] = uv_predict_mode;
12766 neighbours.left_uv_mode[r] = uv_predict_mode;
12767 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
12768 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
12769 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
12770 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
12771 // transform units, same raster-order per-TU pattern `decode_block`'s
12772 // multi-TU branch runs).
12773 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: under
12774 // `TX_MODE_SELECT` a skipped inter block takes the largest transform
12775 // (`read_tx_size(.., is_inter=1, ..)`), and the unskipped case is refused
12776 // above.
12777 let resolved = if tx_select && intrabc_dv.is_none() {
12778 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
12779 } else {
12780 8
12781 };
12782 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
12783 let reach = Reach::of(8, px, py, y.width, y.height);
12784 let (cpx, cpy) = (px / 2, py / 2);
12785 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
12786 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
12787 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
12788 // the full-pel block vector, with the BILINEAR kernel libaom forces.
12789 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
12790 let mut yb = vec![0u16; 8 * 8];
12791 mc::predict_with_filter(
12792 &y.data, y.width, y.true_width, y.true_height,
12793 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
12794 8, 8, mc::InterpFilterKind::Bilinear, &mut yb,
12795 );
12796 let mut ub = vec![0u16; 4 * 4];
12797 mc::predict_with_filter(
12798 &u.data, u.width, u.true_width, u.true_height,
12799 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
12800 4, 4, mc::InterpFilterKind::Bilinear, &mut ub,
12801 );
12802 let mut vb = vec![0u16; 4 * 4];
12803 mc::predict_with_filter(
12804 &v.data, v.width, v.true_width, v.true_height,
12805 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
12806 4, 4, mc::InterpFilterKind::Bilinear, &mut vb,
12807 );
12808 (yb, ub, vb)
12809 });
12810 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
12811 // `decode_block` uses: set fresh right before each plane's own
12812 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
12813 if let Some((yb, _, _)) = &intrabc_bufs {
12814 set_palette_pred(yb.clone());
12815 }
12816 let (luma_grid, u_grid, v_grid);
12817 if skip {
12818 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
12819 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
12820 // transform units, each off the units already written left/above of
12821 // it inside this same leaf -- an intra block's transform size is read
12822 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
12823 // A palette block's prediction is the whole-block index map, never
12824 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
12825 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
12826 // even when `tx_depth` resolved to TX_4X4.
12827 if resolved == 4 && palette_y_buf.is_none() {
12828 SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12829 for tu_row in 0..2 {
12830 for tu_col in 0..2 {
12831 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
12832 if tu_px >= y.true_width || tu_py >= y.true_height {
12833 continue;
12834 }
12835 let tu_reach = tu_reach(
12836 8,
12837 8,
12838 tu_col * 4,
12839 tu_row * 4,
12840 4,
12841 reach,
12842 px,
12843 py,
12844 y.width,
12845 y.height,
12846 );
12847 y.reconstruct(
12848 tu_px,
12849 tu_py,
12850 4,
12851 mode,
12852 angle_delta_y,
12853 tu_reach,
12854 &vec![0i32; 16],
12855 None,
12856 filter_intra,
12857 smooth_neighbor,
12858 );
12859 }
12860 }
12861 } else {
12862 if let Some(buf) = &palette_y_buf {
12863 set_palette_pred(buf.clone());
12864 }
12865 y.reconstruct(
12866 px,
12867 py,
12868 8,
12869 mode,
12870 angle_delta_y,
12871 reach,
12872 &vec![0i32; 64],
12873 None,
12874 filter_intra,
12875 smooth_neighbor,
12876 );
12877 }
12878 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
12879 if let Some((_, ub, _)) = &intrabc_bufs {
12880 set_palette_pred(ub.clone());
12881 } else if let Some((ub, _)) = &palette_uv_bufs {
12882 set_palette_pred(ub.clone());
12883 }
12884 u.reconstruct(
12885 cpx,
12886 cpy,
12887 4,
12888 uv_predict_mode,
12889 angle_delta_uv,
12890 reach,
12891 &vec![0i32; 16],
12892 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
12893 None,
12894 smooth_neighbor_uv,
12895 );
12896 if let Some((_, _, vb)) = &intrabc_bufs {
12897 set_palette_pred(vb.clone());
12898 } else if let Some((_, vb)) = &palette_uv_bufs {
12899 set_palette_pred(vb.clone());
12900 }
12901 v.reconstruct(
12902 cpx,
12903 cpy,
12904 4,
12905 uv_predict_mode,
12906 angle_delta_uv,
12907 reach,
12908 &vec![0i32; 16],
12909 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
12910 None,
12911 smooth_neighbor_uv,
12912 );
12913 luma_grid = vec![0i32; 64];
12914 u_grid = vec![0i32; 16];
12915 v_grid = vec![0i32; 16];
12916 } else if resolved != 4 {
12917 let around = neighbours.around_mi(leaf_mi, 8);
12918 if let Some(buf) = &palette_y_buf {
12919 set_palette_pred(buf.clone());
12920 }
12921 luma_grid = read_plane(
12922 dec,
12923 cdfs,
12924 if intrabc_dv.is_some() {
12925 txbset_for_inter(8, reduced_tx_set)
12926 } else if reduced_tx_set {
12927 TxbSet::Luma8
12928 } else {
12929 TxbSet::Luma8Set1
12930 },
12931 scans.0,
12932 0,
12933 around[0],
12934 mode,
12935 mode,
12936 angle_delta_y,
12937 reach,
12938 y,
12939 px,
12940 py,
12941 8,
12942 TX8,
12943 base_q_idx,
12944 None,
12945 filter_intra,
12946 None,
12947 smooth_neighbor,
12948 )?;
12949 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
12950 // an intrabc block's chroma tx_type is the colocated LUMA transform's
12951 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
12952 if intrabc_dv.is_some() {
12953 INTRABC_CHROMA_TX.with(|c| c.set(Some(LUMA_TX_TYPE.with(std::cell::Cell::get))));
12954 }
12955 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
12956 if let Some((_, ub, _)) = &intrabc_bufs {
12957 set_palette_pred(ub.clone());
12958 } else if let Some((ub, _)) = &palette_uv_bufs {
12959 set_palette_pred(ub.clone());
12960 }
12961 u_grid = read_plane(
12962 dec,
12963 cdfs,
12964 TxbSet::Chroma4,
12965 scans.1,
12966 1,
12967 around[1],
12968 mode,
12969 uv_predict_mode,
12970 angle_delta_uv,
12971 reach,
12972 u,
12973 cpx,
12974 cpy,
12975 4,
12976 TX4,
12977 base_q_idx,
12978 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
12979 None,
12980 None,
12981 smooth_neighbor_uv,
12982 )?;
12983 if let Some((_, _, vb)) = &intrabc_bufs {
12984 set_palette_pred(vb.clone());
12985 } else if let Some((_, vb)) = &palette_uv_bufs {
12986 set_palette_pred(vb.clone());
12987 }
12988 v_grid = read_plane(
12989 dec,
12990 cdfs,
12991 TxbSet::Chroma4,
12992 scans.1,
12993 2,
12994 around[2],
12995 mode,
12996 uv_predict_mode,
12997 angle_delta_uv,
12998 reach,
12999 v,
13000 cpx,
13001 cpy,
13002 4,
13003 TX4,
13004 base_q_idx,
13005 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
13006 None,
13007 None,
13008 smooth_neighbor_uv,
13009 )?;
13010 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
13011 // two chroma reads (`decode_block`'s own tail does the same) -- left
13012 // set, every later chroma block would inherit this luma tx_type,
13013 // which picks the scan and the inverse transform.
13014 INTRABC_CHROMA_TX.with(|c| c.set(None));
13015 } else {
13016 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
13017 // grid of 4x4 transform units, each predicted from the leaf's own
13018 // 8x8 `mode` and reading its own fresh context off the earlier
13019 // units in this same leaf (the same per-TU pattern `decode_block`'s
13020 // multi-TU branch runs at bigger blocks).
13021 luma_grid = vec![0i32; 64];
13022 for tu_row in 0..2 {
13023 for tu_col in 0..2 {
13024 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
13025 let tu_px = px + tu_col * 4;
13026 let tu_py = py + tu_row * 4;
13027 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
13028 if crate::encode::Reach::in_vert_ab() {
13029 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));
13030 }
13031 let tu_reach = tu_reach(
13032 8,
13033 8,
13034 tu_col * 4,
13035 tu_row * 4,
13036 4,
13037 reach,
13038 px,
13039 py,
13040 y.width,
13041 y.height,
13042 );
13043 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
13044 // Each 4x4 unit predicts from its own window of the block's
13045 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
13046 // 16x16 and up) -- the whole-block buffer would be taken by
13047 // the FIRST unit and indexed at the wrong stride.
13048 if let Some(buf) = &palette_y_buf {
13049 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
13050 let mut window = vec![0u16; 16];
13051 for row in 0..4 {
13052 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
13053 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
13054 }
13055 set_palette_pred(window);
13056 }
13057 let tu_grid = read_plane(
13058 dec,
13059 cdfs,
13060 if reduced_tx_set {
13061 TxbSet::Luma4
13062 } else {
13063 TxbSet::Luma4Set1
13064 },
13065 scans.1,
13066 0,
13067 tu_around,
13068 mode,
13069 mode,
13070 angle_delta_y,
13071 tu_reach,
13072 y,
13073 tu_px,
13074 tu_py,
13075 4,
13076 4,
13077 base_q_idx,
13078 None,
13079 filter_intra,
13080 Some(tu_skip_ctx),
13081 smooth_neighbor,
13082 )?;
13083 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13084 eprintln!(
13085 "TRACE tu_bitpos mi=({},{}) tell={}",
13086 tu_mi.0,
13087 tu_mi.1,
13088 dec.debug_bitpos()
13089 );
13090 }
13091 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
13092 }
13093 }
13094 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
13095 let chroma_around = neighbours.around_mi(leaf_mi, 8);
13096 if let Some((ub, _)) = &palette_uv_bufs {
13097 set_palette_pred(ub.clone());
13098 }
13099 u_grid = read_plane(
13100 dec,
13101 cdfs,
13102 TxbSet::Chroma4,
13103 scans.1,
13104 1,
13105 chroma_around[1],
13106 mode,
13107 uv_predict_mode,
13108 angle_delta_uv,
13109 reach,
13110 u,
13111 cpx,
13112 cpy,
13113 4,
13114 TX4,
13115 base_q_idx,
13116 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
13117 None,
13118 None,
13119 smooth_neighbor_uv,
13120 )?;
13121 if let Some((_, vb)) = &palette_uv_bufs {
13122 set_palette_pred(vb.clone());
13123 }
13124 v_grid = read_plane(
13125 dec,
13126 cdfs,
13127 TxbSet::Chroma4,
13128 scans.1,
13129 2,
13130 chroma_around[2],
13131 mode,
13132 uv_predict_mode,
13133 angle_delta_uv,
13134 reach,
13135 v,
13136 cpx,
13137 cpy,
13138 4,
13139 TX4,
13140 base_q_idx,
13141 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
13142 None,
13143 None,
13144 smooth_neighbor_uv,
13145 )?;
13146 // `record_split_luma` expects a `record`-style `(r, c)` position in
13147 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
13148 // already in mi units, so calling it here double-scaled the
13149 // position. Plane 0 is already correct per-TU from the
13150 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
13151 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
13152 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
13153 // leaf's own 8x8 side over `MI`).
13154 let side_mi = 2;
13155 for cell in 0..side_mi {
13156 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
13157 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
13158 }
13159 let round_up_even = |n: usize| n.div_ceil(2) * 2;
13160 let bound_h = round_up_even(neighbours.mi_rows);
13161 let bound_w = round_up_even(neighbours.mi_cols);
13162 let u_state = neighbour_state(&u_grid);
13163 let v_state = neighbour_state(&v_grid);
13164 for cell in 0..side_mi {
13165 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
13166 neighbours.left[leaf_mi.0 + cell][1] = u_state;
13167 neighbours.left[leaf_mi.0 + cell][2] = v_state;
13168 }
13169 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
13170 neighbours.above[leaf_mi.1 + cell][1] = u_state;
13171 neighbours.above[leaf_mi.1 + cell][2] = v_state;
13172 }
13173 }
13174 // This leaf's own palette state into the mi-granular above/left bands
13175 // (sizes 0 when it used none, which is what clears a previous block's
13176 // palette out of the next block's ctx and colour cache).
13177 {
13178 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
13179 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
13180 }
13181 neighbours.fill_skip_grid(leaf_mi, 2, skip);
13182 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
13183 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
13184 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv);
13185 return Ok(mode);
13186 }
13187 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
13188 // This leaf's own palette state into the mi-granular above/left bands
13189 // (sizes 0 when it used none, which is what clears a previous block's
13190 // palette out of the next block's ctx and colour cache).
13191 {
13192 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
13193 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
13194 }
13195 INTER8_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1));
13196 neighbours.fill_skip_grid(leaf_mi, 2, skip);
13197 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
13198 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
13199 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
13200 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
13201 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
13202 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
13203 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
13204 // wrong CDF row, so the msac range diverged mid-frame with no refusal
13205 // (class `wrong-alphabet-same-value`; the ReelB key frame at
13206 // -ss 900, first bad luma sample row 186 col 1803).
13207 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0);
13208 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
13209 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
13210 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
13211 // publish its own cells exactly like `decode_block` does.
13212 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv);
13213 Ok(mode)
13214}
13215
13216/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
13217/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
13218/// bottom, where no partition symbol is read at all -- `decode_block` runs
13219/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
13220/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
13221/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
13222/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
13223/// of the 2x2 4x4 group carries chroma syntax at all.
13224#[allow(clippy::too_many_arguments)]
13225fn read_intra_mode_sub8(
13226 dec: &mut SymbolDecoder,
13227 cdfs: &mut Cdfs,
13228 above_mode: usize,
13229 left_mode: usize,
13230 has_chroma: bool,
13231 enable_filter_intra: bool,
13232 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
13233 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
13234 // from the wrong row is the same VALUE with a different interval, so it
13235 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
13236 fi_class: usize,
13237 skip_ctx: usize,
13238 allow_intrabc: bool,
13239 mi_r: usize,
13240 mi_c: usize,
13241) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
13242 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
13243 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
13244 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
13245 }
13246 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
13247 if trace {
13248 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
13249 }
13250 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
13251 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
13252 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
13253 if allow_intrabc {
13254 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
13255 if use_intrabc {
13256 return Err(unsupported(
13257 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
13258 ));
13259 }
13260 }
13261 let above_ctx = INTRA_MODE_CTX[above_mode];
13262 let left_ctx = INTRA_MODE_CTX[left_mode];
13263 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
13264 if trace {
13265 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
13266 }
13267 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
13268 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
13269 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
13270 // symbol. Reading one consumed a symbol the encoder never wrote and
13271 // desynced the tile at the very next element.
13272 let angle_delta_y = 0;
13273 let chroma = if has_chroma {
13274 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
13275 if trace {
13276 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
13277 }
13278 if (9..=12).contains(&uv_mode) {
13279 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
13280 }
13281 let alpha = if uv_mode == UV_CFL_PRED {
13282 Some(read_cfl_alphas(dec, cdfs))
13283 } else {
13284 None
13285 };
13286 if (V_PRED..=D67_PRED).contains(&uv_mode) {
13287 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
13288 }
13289 // See the luma comment above: no angle delta below 8x8.
13290 let angle_delta_uv = 0;
13291 Some((uv_mode, angle_delta_uv, alpha))
13292 } else {
13293 None
13294 };
13295 let mut filter_intra = None;
13296 if mode == DC_PRED && enable_filter_intra {
13297 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
13298 if trace {
13299 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
13300 }
13301 if use_filter_intra {
13302 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
13303 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
13304 filter_intra = Some(fi_mode);
13305 }
13306 }
13307 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
13308}
13309
13310/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
13311/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
13312/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
13313/// bookkeeping needs no change. Each leaf reads its own luma mode info,
13314/// neighboured off the *previously decoded leaf in this same group* on
13315/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
13316/// pattern, one level deeper); chroma is read and reconstructed exactly
13317/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
13318/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
13319/// derivation.
13320#[allow(clippy::too_many_arguments)]
13321fn decode_leaf_split4(
13322 dec: &mut SymbolDecoder,
13323 cdfs: &mut Cdfs,
13324 neighbours: &mut Neighbours,
13325 outer_at: (usize, usize),
13326 leaf_mi: (usize, usize),
13327 scan4: &[u16],
13328 prev_leaf: Option<((usize, usize), usize)>,
13329 y: &mut PlaneBuf,
13330 u: &mut PlaneBuf,
13331 v: &mut PlaneBuf,
13332 base_q_idx: u8,
13333 enable_filter_intra: bool,
13334 allow_intrabc: bool,
13335 reduced_tx_set: bool,
13336 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
13337 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
13338 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1)).
13339) -> Result<(usize, usize)> {
13340 SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1));
13341 let (r, c) = outer_at;
13342 let mut above_mode = neighbours.above_mode[c];
13343 let mut left_mode = neighbours.left_mode[r];
13344 if let Some(((pr, pc), pmode)) = prev_leaf {
13345 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
13346 above_mode = pmode;
13347 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
13348 left_mode = pmode;
13349 }
13350 }
13351 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
13352 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
13353 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
13354 let mut leaf_modes = [0usize; 4];
13355 let mut leaf_skips = [false; 4];
13356 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
13357 for i in 0..4usize {
13358 let (dr, dc) = (i / 2, i % 2);
13359 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
13360 // Neighbour modes at real mi granularity: inside the group the
13361 // sibling leaf, outside it the split-leaf map when the adjacent mi
13362 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
13363 // `sub8_mode_col`'s doc).
13364 let leaf_above = if dr == 0 {
13365 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
13366 } else {
13367 leaf_modes[i - 2]
13368 };
13369 let leaf_left = if dc == 0 {
13370 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
13371 } else {
13372 leaf_modes[i - 1]
13373 };
13374 let has_chroma = i == 3;
13375 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
13376 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
13377 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
13378 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
13379 skip_ctx, allow_intrabc, lmi.0, lmi.1,
13380 )?;
13381 leaf_modes[i] = mode;
13382 leaf_skips[i] = skip;
13383 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
13384 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
13385 if smooth_neighbor {
13386 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
13387 }
13388 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
13389 let reach = Reach::of(4, px, py, y.width, y.height);
13390 if skip {
13391 y.reconstruct(px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor);
13392 neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]);
13393 } else {
13394 let tu_around = neighbours.around_mi(lmi, 4)[0];
13395 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
13396 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
13397 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
13398 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
13399 // off the wrong CDF on the very first leaf and desynced the tile.
13400 let tu_grid = read_plane(
13401 dec,
13402 cdfs,
13403 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
13404 scan4,
13405 0,
13406 tu_around,
13407 mode,
13408 mode,
13409 angle_delta_y,
13410 reach,
13411 y,
13412 px,
13413 py,
13414 4,
13415 4,
13416 base_q_idx,
13417 None,
13418 filter_intra,
13419 None,
13420 smooth_neighbor,
13421 )?;
13422 neighbours.record_mi_luma(lmi, 4, &tu_grid);
13423 }
13424 neighbours.fill_skip_grid(lmi, 1, skip);
13425 neighbours.fill_lf_grid(lmi, 1, 4, 0);
13426 if has_chroma {
13427 last_uv = chroma;
13428 }
13429 }
13430 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
13431 let (cpx, cpy) = (gpx / 2, gpy / 2);
13432 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
13433 let (uv_mode, angle_delta_uv, alpha) =
13434 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
13435 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
13436 neighbours.above_uv_mode[c] = uv_predict_mode;
13437 neighbours.left_uv_mode[r] = uv_predict_mode;
13438 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
13439 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[3] {
13440 // A skipped chroma block still gets its CfL contribution: libaom's
13441 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
13442 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
13443 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
13444 // added -- `skip_txfm` only drops the residual, never the alpha.
13445 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
13446 // merge keeps one fix and feeds both lanes' counters so neither of
13447 // their gates goes vacuous.
13448 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
13449 if alpha.is_some() {
13450 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
13451 SKIP_CFL_HITS.with(|c| c.set(c.get() + 1));
13452 }
13453 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv);
13454 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv);
13455 (vec![0i32; 16], vec![0i32; 16])
13456 } else {
13457 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
13458 let chroma_around = neighbours.around_mi(leaf_mi, 8);
13459 let ug = read_plane(
13460 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
13461 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
13462 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
13463 )?;
13464 let vg = read_plane(
13465 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
13466 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
13467 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
13468 )?;
13469 (ug, vg)
13470 };
13471 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
13472 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
13473 // rescaling is wrong for an already-mi-unit position, so this inlines
13474 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
13475 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
13476 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
13477 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
13478 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
13479 // bottom). libaom's `update_ext_partition_context` writes
13480 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
13481 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
13482 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
13483 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
13484 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
13485 // round's bug) makes the very next sibling 8x8's `partition_w8` read
13486 // with the wrong context and desync immediately.
13487 let side_mi = 2;
13488 for cell in 0..side_mi {
13489 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
13490 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
13491 }
13492 let round_up_even = |n: usize| n.div_ceil(2) * 2;
13493 let bound_h = round_up_even(neighbours.mi_rows);
13494 let bound_w = round_up_even(neighbours.mi_cols);
13495 let u_state = neighbour_state(&u_grid);
13496 let v_state = neighbour_state(&v_grid);
13497 for cell in 0..side_mi {
13498 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
13499 neighbours.left[leaf_mi.0 + cell][1] = u_state;
13500 neighbours.left[leaf_mi.0 + cell][2] = v_state;
13501 }
13502 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
13503 neighbours.above[leaf_mi.1 + cell][1] = u_state;
13504 neighbours.above[leaf_mi.1 + cell][2] = v_state;
13505 }
13506 }
13507 Ok((leaf_modes[2], leaf_modes[1]))
13508}
13509
13510/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
13511/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
13512/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
13513/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
13514/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
13515/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
13516/// every sub-block one mi wide or high but the last) -- differing only where
13517/// the shape does:
13518///
13519/// * the transform is a true `TX_4X8`/`TX_8X4`
13520/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
13521/// `av1_inv_txfm_shift_ls` row already cover this size pair);
13522/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
13523/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
13524/// row -- see that variant's doc comment;
13525/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
13526/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
13527/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
13528/// ([`Reach::of_rect`]);
13529/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
13530/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
13531/// `BLOCK_4X4` split writes.
13532///
13533/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
13534/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
13535/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
13536/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
13537/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
13538/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
13539#[allow(clippy::too_many_arguments)]
13540fn decode_leaf_rect8(
13541 dec: &mut SymbolDecoder,
13542 cdfs: &mut Cdfs,
13543 neighbours: &mut Neighbours,
13544 outer_at: (usize, usize),
13545 leaf_mi: (usize, usize),
13546 vert: bool,
13547 scan4: &[u16],
13548 y: &mut PlaneBuf,
13549 u: &mut PlaneBuf,
13550 v: &mut PlaneBuf,
13551 base_q_idx: u8,
13552 enable_filter_intra: bool,
13553 allow_intrabc: bool,
13554 tx_select: bool,
13555 reduced_tx_set: bool,
13556) -> Result<(usize, usize)> {
13557 let (r, c) = outer_at;
13558 // lane-modectx r1: availability-correct fallback pair (see
13559 // `modes_above_left`), not the raw coarse bands.
13560 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
13561 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
13562 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
13563 let (w_mi, h_mi) = (bw / MI, bh / MI);
13564 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
13565 let mut leaf_modes = [0usize; 2];
13566 let mut leaf_skips = [false; 2];
13567 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
13568 for i in 0..2usize {
13569 let lmi = if vert {
13570 (leaf_mi.0, leaf_mi.1 + i)
13571 } else {
13572 (leaf_mi.0 + i, leaf_mi.1)
13573 };
13574 // Inside the pair the sibling is the neighbour on the split axis;
13575 // outside it the mi-granular map, else the coarse 16x16 slot.
13576 let leaf_above = if !vert && i == 1 {
13577 leaf_modes[0]
13578 } else {
13579 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
13580 };
13581 let leaf_left = if vert && i == 1 {
13582 leaf_modes[0]
13583 } else {
13584 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
13585 };
13586 let has_chroma = i == 1;
13587 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
13588 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
13589 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
13590 filter_intra_size_class_rect(bw, bh)
13591 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
13592 skip_ctx, allow_intrabc, lmi.0, lmi.1,
13593 )?;
13594 if filter_intra.is_some() {
13595 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
13596 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
13597 // same `reconstruct_rect`/`reconstruct` calls below -- and under
13598 // a split transform, per 4x4 unit with that unit's own edge,
13599 // which is exactly what the depth-1 loop already does.
13600 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
13601 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.set(c.get() + 1));
13602 }
13603 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
13604 // leaf too, and is read for every intra block, skipped or not. Its
13605 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
13606 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
13607 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
13608 // `tx_size_cat2` the 32x16 strips read -- with the rect context
13609 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
13610 // Missing this read consumed one symbol fewer than the encoder wrote
13611 // and desynced the tile at the very first rect leaf (class
13612 // `symbol-consumption-gap`).
13613 let depth = if tx_select {
13614 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band
13615 // read every other rect reader now does -- a no-op on a key frame.
13616 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
13617 tx_size_context_txfm_rect(neighbours, lmi, bw, bh)
13618 } else {
13619 tx_size_context_rect(neighbours, lmi, bw, bh)
13620 };
13621 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
13622 } else {
13623 0
13624 };
13625 if depth != 0 {
13626 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
13627 RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
13628 }
13629 leaf_modes[i] = mode;
13630 leaf_skips[i] = skip;
13631 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
13632 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
13633 if smooth_neighbor {
13634 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
13635 }
13636 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
13637 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
13638 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
13639 // two 4x4 transform units along its long axis, each predicted from
13640 // the previous unit's reconstruction and reading its own `txb_skip`
13641 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
13642 // four. The per-TU path writes its own neighbour state, so the
13643 // block-level write below is skipped for it.
13644 let split = depth != 0;
13645 if split {
13646 let mut done = 0usize;
13647 for tu in 0..2usize {
13648 let tu_mi = if vert {
13649 (lmi.0 + tu, lmi.1)
13650 } else {
13651 (lmi.0, lmi.1 + tu)
13652 };
13653 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
13654 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
13655 // Same per-TU rule as every other split-transform site
13656 // (lane-palette2 r12): a transform unit inside a block is not
13657 // a block at that position, so its reach comes from the
13658 // block's own row, offset by the unit's position.
13659 let tu_reach = tu_reach(
13660 bw,
13661 bh,
13662 tu_px - px,
13663 tu_py - py,
13664 4,
13665 reach,
13666 px,
13667 py,
13668 y.width,
13669 y.height,
13670 );
13671 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
13672 if skip {
13673 // A skipped leaf still predicts per transform unit: the
13674 // second 4x4 takes its above/left edge from the first
13675 // one's reconstruction, which is NOT what a single 4x8
13676 // prediction of the same mode produces.
13677 let zeros = vec![0i32; 16];
13678 y.reconstruct(
13679 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
13680 filter_intra, smooth_neighbor,
13681 );
13682 neighbours.record_mi_luma(tu_mi, 4, &zeros);
13683 continue;
13684 }
13685 let tu_grid = read_plane(
13686 dec,
13687 cdfs,
13688 if reduced_tx_set {
13689 TxbSet::Luma4
13690 } else {
13691 TxbSet::Luma4Set1
13692 },
13693 scan4,
13694 0,
13695 tu_around,
13696 mode,
13697 mode,
13698 angle_delta_y,
13699 tu_reach,
13700 y,
13701 tu_px,
13702 tu_py,
13703 4,
13704 TX4,
13705 base_q_idx,
13706 None,
13707 filter_intra,
13708 Some(tu_skip_ctx),
13709 smooth_neighbor,
13710 )?;
13711 if tu_grid.iter().any(|&l| l != 0) {
13712 done += 1;
13713 }
13714 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
13715 }
13716 if done > 0 {
13717 if vert {
13718 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
13719 } else {
13720 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
13721 }
13722 }
13723 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
13724 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0);
13725 if has_chroma {
13726 last_uv = chroma;
13727 }
13728 continue;
13729 }
13730 let grid = if skip {
13731 let zeros = vec![0i32; bw * bh];
13732 y.reconstruct_rect(
13733 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
13734 smooth_neighbor,
13735 );
13736 zeros
13737 } else {
13738 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
13739 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
13740 // at 0 -- see `decode_leaf_split4`'s own note.
13741 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
13742 let set = if reduced_tx_set {
13743 TxbSet::LumaRect4x8
13744 } else {
13745 TxbSet::LumaRect4x8Set1
13746 };
13747 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
13748 let (levels, tx_type) = read_coeffs_rect(
13749 dec,
13750 &mut coding,
13751 scan,
13752 bw,
13753 bh,
13754 0,
13755 dc_sign_ctx(around.2),
13756 TxType::DctDct,
13757 )?;
13758 if levels.iter().any(|&l| l != 0) {
13759 if vert {
13760 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
13761 } else {
13762 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
13763 }
13764 }
13765 let residual = dequant_and_inverse_typed_wh(
13766 &levels,
13767 bw,
13768 bh,
13769 crate::decode::bit_depth(),
13770 CURRENT_Q_IDX.with(|q| q.get()),
13771 plane_q_delta(0).0,
13772 plane_q_delta(0).1,
13773 tx_type,
13774 );
13775 y.reconstruct_rect(
13776 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
13777 smooth_neighbor,
13778 );
13779 levels
13780 };
13781 // Plane 0's per-TU coefficient context over this leaf's own mi span
13782 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
13783 // for the whole 8x8 group below).
13784 let state = neighbour_state(&grid);
13785 for cell in 0..h_mi {
13786 if lmi.0 + cell < neighbours.mi_rows {
13787 neighbours.left[lmi.0 + cell][0] = state;
13788 }
13789 }
13790 for cell in 0..w_mi {
13791 if lmi.1 + cell < neighbours.mi_cols {
13792 neighbours.above[lmi.1 + cell][0] = state;
13793 }
13794 }
13795 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
13796 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
13797 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0);
13798 if has_chroma {
13799 last_uv = chroma;
13800 }
13801 }
13802 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
13803 let (cpx, cpy) = (gpx / 2, gpy / 2);
13804 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
13805 let (uv_mode, angle_delta_uv, alpha) =
13806 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
13807 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
13808 neighbours.above_uv_mode[c] = uv_predict_mode;
13809 neighbours.left_uv_mode[r] = uv_predict_mode;
13810 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
13811 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[1] {
13812 // A skipped chroma block still gets its CfL contribution: libaom's
13813 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
13814 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
13815 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
13816 // added -- `skip_txfm` only drops the residual, never the alpha.
13817 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
13818 // merge keeps one fix and feeds both lanes' counters so neither of
13819 // their gates goes vacuous.
13820 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
13821 if alpha.is_some() {
13822 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
13823 SKIP_CFL_HITS.with(|c| c.set(c.get() + 1));
13824 }
13825 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv);
13826 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv);
13827 (vec![0i32; 16], vec![0i32; 16])
13828 } else {
13829 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
13830 let chroma_around = neighbours.around_mi(leaf_mi, 8);
13831 let ug = read_plane(
13832 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
13833 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
13834 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
13835 )?;
13836 let vg = read_plane(
13837 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
13838 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
13839 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
13840 )?;
13841 (ug, vg)
13842 };
13843 // `update_partition_context` at the 8x8 level writes
13844 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
13845 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
13846 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
13847 // `partition_ctx_mi` reads back off these side values.
13848 for cell in 0..2 {
13849 neighbours.above_side_mi[leaf_mi.1 + cell] = bw;
13850 neighbours.left_side_mi[leaf_mi.0 + cell] = bh;
13851 }
13852 let round_up_even = |n: usize| n.div_ceil(2) * 2;
13853 let bound_h = round_up_even(neighbours.mi_rows);
13854 let bound_w = round_up_even(neighbours.mi_cols);
13855 let u_state = neighbour_state(&u_grid);
13856 let v_state = neighbour_state(&v_grid);
13857 for cell in 0..2usize {
13858 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
13859 neighbours.left[leaf_mi.0 + cell][1] = u_state;
13860 neighbours.left[leaf_mi.0 + cell][2] = v_state;
13861 }
13862 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
13863 neighbours.above[leaf_mi.1 + cell][1] = u_state;
13864 neighbours.above[leaf_mi.1 + cell][2] = v_state;
13865 }
13866 }
13867 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
13868 // bottom one (the second under HORZ, the left one under VERT), the one a
13869 // neighbour to the right sees is the top-right (the second under VERT).
13870 Ok(if vert {
13871 (leaf_modes[0], leaf_modes[1])
13872 } else {
13873 (leaf_modes[1], leaf_modes[0])
13874 })
13875}
13876
13877/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
13878/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
13879/// (mod 8) reuse the same table.
13880const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
13881 [(-1, 1), (-2, 2)],
13882 [(0, 1), (-1, 2)],
13883 [(0, 1), (0, 2)],
13884 [(0, 1), (1, 2)],
13885 [(1, 1), (2, 2)],
13886 [(1, 0), (2, 1)],
13887 [(1, 0), (2, 0)],
13888 [(1, 0), (2, -1)],
13889];
13890/// A neighbour tap outside the frame's true extent -- `constrain` reads this
13891/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
13892const CDEF_VERY_LARGE: i32 = 0x4000;
13893const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
13894const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
13895
13896fn cdef_msb(x: i32) -> i32 {
13897 31 - x.leading_zeros() as i32
13898}
13899
13900/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
13901/// centre sample a filter tap is allowed to contribute.
13902fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
13903 if threshold == 0 {
13904 return 0;
13905 }
13906 let shift = (damping - cdef_msb(threshold)).max(0);
13907 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
13908}
13909
13910/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
13911/// direction of an 8x8 luma window and the variance gap between it and its
13912/// orthogonal, `sample(row, col)` reading that window's own pixels.
13913fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
13914 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
13915 let mut partial = [[0i64; 15]; 8];
13916 for i in 0..8i64 {
13917 for j in 0..8i64 {
13918 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
13919 // accumulating, same as `constrain`'s threshold shift below.
13920 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
13921 partial[0][(i + j) as usize] += x;
13922 partial[1][(i + j / 2) as usize] += x;
13923 partial[2][i as usize] += x;
13924 partial[3][(3 + i - j / 2) as usize] += x;
13925 partial[4][(7 + i - j) as usize] += x;
13926 partial[5][(3 - i / 2 + j) as usize] += x;
13927 partial[6][j as usize] += x;
13928 partial[7][(i / 2 + j) as usize] += x;
13929 }
13930 }
13931 let mut cost = [0i64; 8];
13932 for i in 0..8usize {
13933 cost[2] += partial[2][i] * partial[2][i];
13934 cost[6] += partial[6][i] * partial[6][i];
13935 }
13936 cost[2] *= DIV_TABLE[8];
13937 cost[6] *= DIV_TABLE[8];
13938 for i in 0..7usize {
13939 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
13940 * DIV_TABLE[i + 1];
13941 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
13942 * DIV_TABLE[i + 1];
13943 }
13944 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
13945 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
13946 for i in (1..8).step_by(2) {
13947 for j in 0..5usize {
13948 cost[i] += partial[i][3 + j] * partial[i][3 + j];
13949 }
13950 cost[i] *= DIV_TABLE[8];
13951 for j in 0..3usize {
13952 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
13953 * DIV_TABLE[2 * j + 2];
13954 }
13955 }
13956 let mut best_cost = 0i64;
13957 let mut best_dir = 0usize;
13958 for (i, &c) in cost.iter().enumerate() {
13959 if c > best_cost {
13960 best_cost = c;
13961 best_dir = i;
13962 }
13963 }
13964 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
13965 (best_dir, var as i32)
13966}
13967
13968/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
13969/// (high variance gap) gets more deringing than a flat or non-directional
13970/// one, only ever applied to the luma primary strength.
13971fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
13972 if var == 0 {
13973 return 0;
13974 }
13975 let i = if var >> 6 != 0 {
13976 cdef_msb(var >> 6).min(12)
13977 } else {
13978 0
13979 };
13980 (strength * (4 + i) + 8) >> 4
13981}
13982
13983/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
13984/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
13985/// previously-filtered neighbour must never feed this block's own sum).
13986#[allow(clippy::too_many_arguments)]
13987fn cdef_filter_block(
13988 sample: impl Fn(i32, i32) -> i32,
13989 dst: &mut PlaneBuf,
13990 ox: usize,
13991 oy: usize,
13992 bw: usize,
13993 bh: usize,
13994 pri_strength: i32,
13995 sec_strength: i32,
13996 dir: usize,
13997 pri_damping: i32,
13998 sec_damping: i32,
13999 enable_primary: bool,
14000 enable_secondary: bool,
14001 coeff_shift: i32,
14002) {
14003 let clipping_required = enable_primary && enable_secondary;
14004 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
14005 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
14006 // derivative) carries the bit-depth shift, so the tap-set parity bit
14007 // must be read back above that shift, not off the raw low bit.
14008 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
14009 for i in 0..bh {
14010 for j in 0..bw {
14011 let x = sample(i as i32, j as i32);
14012 let mut sum = 0i32;
14013 let mut max = x;
14014 let mut min = x;
14015 for k in 0..2usize {
14016 if enable_primary {
14017 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
14018 let p0 = sample(i as i32 + tr, j as i32 + tc);
14019 let p1 = sample(i as i32 - tr, j as i32 - tc);
14020 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
14021 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
14022 if clipping_required {
14023 if p0 != CDEF_VERY_LARGE {
14024 max = max.max(p0);
14025 }
14026 if p1 != CDEF_VERY_LARGE {
14027 max = max.max(p1);
14028 }
14029 min = min.min(p0).min(p1);
14030 }
14031 }
14032 if enable_secondary {
14033 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
14034 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
14035 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
14036 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
14037 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
14038 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
14039 if clipping_required {
14040 for s in [s0, s1, s2, s3] {
14041 if s != CDEF_VERY_LARGE {
14042 max = max.max(s);
14043 }
14044 }
14045 min = min.min(s0).min(s1).min(s2).min(s3);
14046 }
14047 sum += CDEF_SEC_TAPS[k]
14048 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
14049 + cdef_constrain(s1 - x, sec_strength, sec_damping)
14050 + cdef_constrain(s2 - x, sec_strength, sec_damping)
14051 + cdef_constrain(s3 - x, sec_strength, sec_damping));
14052 }
14053 }
14054 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
14055 if clipping_required {
14056 y = y.clamp(min, max);
14057 }
14058 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, sample_max()) as u16;
14059 }
14060 }
14061}
14062
14063/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
14064/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
14065/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
14066/// every block's level comes from [`LoopFilterParams::level`] plus the
14067/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
14068/// `get_filter_level`, precomputed per-block here rather than cached in a
14069/// table the way libaom's `av1_loop_filter_frame_init` does).
14070///
14071/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
14072/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
14073fn apply_deblock(
14074 y: &mut PlaneBuf,
14075 u: &mut PlaneBuf,
14076 v: &mut PlaneBuf,
14077 lf: &LoopFilterParams,
14078 n: &Neighbours,
14079 frame_width: usize,
14080 frame_height: usize,
14081) {
14082 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
14083 // mismatch between the raw reconstruction and post-filter output.
14084 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
14085 return;
14086 }
14087 if lf.level[0] != 0 || lf.level[1] != 0 {
14088 deblock_plane(y, 0, lf, n, frame_width, frame_height);
14089 }
14090 if lf.level[2] != 0 {
14091 deblock_plane(u, 1, lf, n, frame_width, frame_height);
14092 }
14093 if lf.level[3] != 0 {
14094 deblock_plane(v, 2, lf, n, frame_width, frame_height);
14095 }
14096}
14097
14098/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
14099/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
14100/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
14101/// mi unit under this decoder's assumed 4:2:0 subsampling).
14102fn plane_to_mi(chroma: bool, coord: usize) -> usize {
14103 if chroma { coord / 2 } else { coord / 4 }
14104}
14105
14106/// This plane's own transform width in pixels at the covering block, spec
14107/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
14108/// width directly; chroma halves it (this decoder's UV transform is always
14109/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
14110/// under 4:2:0 and a block that never splits its own transform).
14111fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
14112 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
14113 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
14114}
14115
14116/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
14117/// edges step and gate by transform height, which differs from width only
14118/// on rect partition strips.
14119fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
14120 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
14121 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
14122}
14123
14124/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
14125/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
14126/// present only when its neighbour exists inside the true frame -- whether
14127/// the block immediately above (at this block's own leftmost mi column) or
14128/// to the left (at its own topmost mi row) coded a transform at least as wide
14129/// as `own_side`.
14130fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
14131 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
14132 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
14133 usize::from(above) + usize::from(left)
14134}
14135
14136/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
14137/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
14138/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
14139/// inter path maintains), except that an *inter* neighbour contributes its
14140/// own BLOCK size rather than its transform size -- the two differ the moment
14141/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
14142/// approximation coincides with this only while every neighbour codes one
14143/// whole-block transform, which is exactly what `TxMode::Select` ends.
14144/// [`tx_size_context_txfm`] with the block's own width and height (lane-intrasplit
14145/// r1): `get_tx_size_context` compares the neighbour ABOVE against
14146/// `tx_size_wide[max_txsize_rect_lookup[bsize]]` and the neighbour to the LEFT
14147/// against `tx_size_high[...]` (libaom `pred_common.h:342`), which for a 2:1
14148/// strip are two different numbers. The intra strip inside an inter frame read
14149/// this through [`tx_size_context_rect`] -- the key frame's deblock-grid
14150/// approximation -- so once `TxMode::Select` made the depth symbol exist, it was
14151/// read off the wrong CDF row whenever a neighbour's var-tx tree had split.
14152fn tx_size_context_txfm_rect(
14153 n: &Neighbours,
14154 (mi_r, mi_c): (usize, usize),
14155 own_w: usize,
14156 own_h: usize,
14157) -> usize {
14158 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.set(c.get() + 1));
14159 let has_above = mi_r > n.tile_row0_mi;
14160 let has_left = mi_c > n.tile_col0_mi;
14161 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
14162 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
14163 if has_above && n.above_inter[mi_c] {
14164 above = n.above_side_mi[mi_c] >= own_w;
14165 }
14166 if has_left && n.left_inter[mi_r] {
14167 left = n.left_side_mi[mi_r] >= own_h;
14168 }
14169 if crate::envflags::env_flag!("EC_TXCTX") {
14170 eprintln!(
14171 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
14172 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
14173 above={above} left={left}",
14174 n.above_txfm[mi_c],
14175 n.left_txfm[mi_r],
14176 n.above_inter[mi_c],
14177 n.left_inter[mi_r],
14178 n.above_side_mi[mi_c],
14179 n.left_side_mi[mi_r],
14180 );
14181 }
14182 let ctx = match (has_above, has_left) {
14183 (true, true) => usize::from(above) + usize::from(left),
14184 (true, false) => usize::from(above),
14185 (false, true) => usize::from(left),
14186 (false, false) => 0,
14187 };
14188 // lane-midcut r3: count only the blocks the KEY FRAME deblock-grid
14189 // approximation ([`tx_size_context_rect`]) would have read off a DIFFERENT
14190 // CDF row, i.e. exactly the blocks this band read fixes -- a plain "rect
14191 // intra in an inter frame" tally is green on the buggy code too (class
14192 // gate-blind-to-feature).
14193 if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
14194 let (cw, ch) = (own_w.min(64), own_h.min(64));
14195 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= cw)
14196 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= ch);
14197 if ctx != stale {
14198 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(|c| c.set(c.get() + 1));
14199 }
14200 }
14201 ctx
14202}
14203
14204/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
14205/// are written and read everywhere else with a raw mi index); the SUB-cell
14206/// division this pair used read a cell four blocks away, so the inter-neighbour
14207/// override above fired on the wrong neighbour -- the first divergence of the
14208/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
14209/// at the intra block right of an inter one).
14210fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
14211 let has_above = mi_r > n.tile_row0_mi;
14212 let has_left = mi_c > n.tile_col0_mi;
14213 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
14214 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
14215 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
14216 // `above_inter`/`left_inter` bands are written per MI unit
14217 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
14218 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
14219 // block whenever the neighbour column/row is not the cell's first. A
14220 // 16x16 intra block whose left neighbour is an inter block at mi row 4
14221 // then missed libaom's "an inter neighbour contributes its BLOCK size"
14222 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
14223 if has_above && n.above_inter[mi_c] {
14224 above = n.above_side_mi[mi_c] >= side;
14225 }
14226 if has_left && n.left_inter[mi_r] {
14227 left = n.left_side_mi[mi_r] >= side;
14228 }
14229 if crate::envflags::env_flag!("EC_TXCTX") {
14230 eprintln!(
14231 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
14232 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
14233 above={above} left={left}",
14234 n.above_txfm[mi_c],
14235 n.left_txfm[mi_r],
14236 n.above_inter[mi_c],
14237 n.left_inter[mi_r],
14238 n.above_side_mi[mi_c],
14239 n.left_side_mi[mi_r],
14240 );
14241 }
14242 match (has_above, has_left) {
14243 (true, true) => usize::from(above) + usize::from(left),
14244 (true, false) => usize::from(above),
14245 (false, true) => usize::from(left),
14246 (false, false) => 0,
14247 }
14248}
14249
14250/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
14251/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
14252/// the transform's own side in pixels (`side >> depth`) -- this decoder's
14253/// four square categories (8/16/32/64) each halve at most twice, matching
14254/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
14255fn read_tx_size(
14256 dec: &mut SymbolDecoder,
14257 cdfs: &mut Cdfs,
14258 n: &Neighbours,
14259 at_mi: (usize, usize),
14260 side: usize,
14261 // lane-txselect: `get_tx_size_context`'s real context, for the callers
14262 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
14263 // key-frame path's own deblock-grid approximation.
14264 ctx_override: Option<usize>,
14265) -> usize {
14266 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
14267 // `get_tx_size_context`): a block wider than 64 still tops out at
14268 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
14269 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
14270 // never against its own 128 side (lane-sb128b r1).
14271 let max_tx = side.min(64);
14272 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
14273 let depth = match max_tx {
14274 8 => {
14275 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
14276 }
14277 16 => {
14278 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
14279 }
14280 32 => {
14281 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
14282 }
14283 64 => {
14284 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
14285 }
14286 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
14287 };
14288 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14289 let (rng, _) = dec.debug_state();
14290 let (mi_r, mi_c) = at_mi;
14291 eprintln!(
14292 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
14293 );
14294 }
14295 if depth != 0 {
14296 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
14297 }
14298 max_tx >> depth
14299}
14300
14301/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
14302/// `txfm_split` context -- a category from the block's own largest square
14303/// transform and whether this unit already sits below it, times three, plus
14304/// the two neighbour terms (whether the transform last written above/left of
14305/// this unit is narrower/shorter than the unit itself).
14306fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
14307 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
14308}
14309
14310/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
14311/// libaom's `txfm_partition_context` compares the above context against
14312/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
14313/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
14314/// side for a square transform, which is why the square form above is a
14315/// special case of this one.
14316fn txfm_partition_ctx_rect(
14317 above_px: u8,
14318 left_px: u8,
14319 blk_max_px: usize,
14320 tx_w: usize,
14321 tx_h: usize,
14322) -> usize {
14323 let above = usize::from(usize::from(above_px) < tx_w);
14324 let left = usize::from(usize::from(left_px) < tx_h);
14325 let tx_px = tx_w.max(tx_h);
14326 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
14327 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
14328 // `log2(px) - 2`.
14329 let max_tx = blk_max_px.min(64);
14330 let max_idx = max_tx.trailing_zeros() as usize - 2;
14331 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
14332 category * 3 + above + left
14333}
14334
14335/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
14336/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
14337/// resolved transform's own size.
14338fn txfm_partition_update(
14339 n: &mut Neighbours,
14340 at_mi: (usize, usize),
14341 tx_px: usize,
14342 txb_px: usize,
14343) {
14344 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
14345}
14346
14347/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
14348/// the left column records `tx_size_high` over the parent's own height and
14349/// the above row records `tx_size_wide` over its width.
14350/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
14351/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
14352/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
14353/// key frame writes neither (its readers use the deblock grid), so the
14354/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
14355/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
14356/// at the call site (the transform size comes back to them); the 1:4 arms
14357/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
14358/// so they call this where their own depth resolves. A no-op on a key frame
14359/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
14360///
14361/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
14362/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
14363/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
14364/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
14365/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
14366/// / early-return-skips-tail).
14367fn publish_txfm_bands_if_in_inter(
14368 n: &mut Neighbours,
14369 at_mi: (usize, usize),
14370 (tx_w, tx_h): (usize, usize),
14371 (bw, bh): (usize, usize),
14372) {
14373 if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_none() {
14374 return;
14375 }
14376 let (mi_r, mi_c) = at_mi;
14377 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
14378 for i in 0..bw / MI {
14379 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
14380 *cell = tx_w as u8;
14381 }
14382 }
14383 for i in 0..bh / MI {
14384 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
14385 *cell = tx_h as u8;
14386 }
14387 }
14388}
14389
14390fn txfm_partition_update_rect(
14391 n: &mut Neighbours,
14392 (mi_r, mi_c): (usize, usize),
14393 (tx_w, tx_h): (usize, usize),
14394 (txb_w, txb_h): (usize, usize),
14395) {
14396 if crate::envflags::env_flag!("EC_TXUPD") {
14397 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
14398 }
14399 for i in 0..txb_h / MI {
14400 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
14401 *cell = tx_h as u8;
14402 }
14403 }
14404 for i in 0..txb_w / MI {
14405 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
14406 *cell = tx_w as u8;
14407 }
14408 }
14409}
14410
14411/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
14412/// same contexts -- a skipped *inter* block records its own block size rather
14413/// than its transform size.
14414fn set_txfm_ctxs(
14415 n: &mut Neighbours,
14416 (mi_r, mi_c): (usize, usize),
14417 tx_px: usize,
14418 w_mi: usize,
14419 h_mi: usize,
14420 skip_inter: bool,
14421) {
14422 if crate::envflags::env_flag!("EC_TXUPD") {
14423 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
14424 }
14425 let bw = if skip_inter { w_mi * MI } else { tx_px };
14426 let bh = if skip_inter { h_mi * MI } else { tx_px };
14427 for i in 0..w_mi {
14428 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
14429 *cell = bw as u8;
14430 }
14431 }
14432 for i in 0..h_mi {
14433 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
14434 *cell = bh as u8;
14435 }
14436 }
14437}
14438
14439/// The value libaom initialises both transform contexts to -- NOT zero:
14440/// `av1_zero_above_context` memsets the txfm row to
14441/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
14442/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
14443/// pixels, so an unwritten neighbour reads as the *widest* possible
14444/// transform, not the narrowest.
14445const TXFM_CTX_INIT: u8 = 64;
14446
14447/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
14448/// twice below its own largest transform.
14449const MAX_VARTX_DEPTH: usize = 2;
14450
14451/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
14452/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
14453/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
14454/// small ones, square everywhere else.
14455fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
14456 match (tx_w, tx_h) {
14457 (4, 4) => (4, 4),
14458 (8, 8) => (4, 4),
14459 (16, 16) => (8, 8),
14460 (32, 32) => (16, 16),
14461 (64, 64) => (32, 32),
14462 (4, 8) | (8, 4) => (4, 4),
14463 (8, 16) | (16, 8) => (8, 8),
14464 (16, 32) | (32, 16) => (16, 16),
14465 (32, 64) | (64, 32) => (32, 32),
14466 (4, 16) => (4, 8),
14467 (16, 4) => (8, 4),
14468 (8, 32) => (8, 16),
14469 (32, 8) => (16, 8),
14470 (16, 64) => (16, 32),
14471 (64, 16) => (32, 16),
14472 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
14473 }
14474}
14475
14476#[test]
14477fn sub_tx_size_map_matches_libaom() {
14478 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
14479 const TABLE: [((usize, usize), (usize, usize)); 19] = [
14480 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
14481 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
14482 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
14483 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
14484 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
14485 ];
14486 for (tx, want) in TABLE {
14487 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
14488 }
14489}
14490
14491/// The domain of var-tx leaf sizes, enumerated against the two refusals that
14492/// name a leaf "larger than 32x32" / "larger than 64x64".
14493///
14494/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
14495/// either the unit it was entered with or a `sub_tx_size_map` step below it:
14496/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
14497/// return. So the leaf set reachable from an entry unit is that unit plus the
14498/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
14499/// which this test enumerates, and over which no leaf is ever larger than the
14500/// entry.
14501///
14502/// That closes both refusals:
14503///
14504/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
14505/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
14506/// 64x64" names a leaf the tree cannot produce;
14507/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
14508/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
14509/// reached only when `side == 64`, and then the block is ONE unit whose only
14510/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
14511/// case the refusal is guarded by.
14512#[test]
14513fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
14514 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
14515 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
14516 out.push((depth, entry.0, entry.1));
14517 if depth == MAX_VARTX_DEPTH {
14518 return;
14519 }
14520 let sub = sub_tx_size_map(entry.0, entry.1);
14521 if sub == (4, 4) {
14522 out.push((depth + 1, 4, 4));
14523 return;
14524 }
14525 reachable(sub, depth + 1, out);
14526 }
14527
14528 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
14529 let mut leaves = Vec::new();
14530 reachable(entry, 0, &mut leaves);
14531 for (depth, w, h) in &leaves {
14532 assert!(
14533 w.max(h) <= &entry.0.max(entry.1),
14534 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
14535 entry.0,
14536 entry.1
14537 );
14538 }
14539 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
14540 if entry == (64, 64) {
14541 let above: Vec<&(usize, usize, usize)> =
14542 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
14543 assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32");
14544 }
14545 }
14546
14547 // The entry size and ceiling each caller uses, over the block sides that
14548 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
14549 // enters at a fixed 64).
14550 for side in [8usize, 16, 32, 64, 128] {
14551 let max_tx = side.min(64);
14552 let ceiling = if side > 64 { 64 } else { 32 };
14553 let units = (side / max_tx) * (side / max_tx);
14554 if max_tx <= ceiling {
14555 continue;
14556 }
14557 assert_eq!(
14558 (side, units),
14559 (64, 1),
14560 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
14561 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
14562 );
14563 }
14564}
14565
14566/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
14567/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
14568/// max-transform-sized unit of an inter block, collecting the resolved leaf
14569/// transform units into `out` as `(row offset, col offset, side)` in mi units
14570/// -- exactly the order `decode_reconstruct_tx` later reads their
14571/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
14572/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
14573/// `max_block_high`).
14574#[allow(clippy::too_many_arguments)]
14575fn read_var_tx_size(
14576 dec: &mut SymbolDecoder,
14577 cdfs: &mut Cdfs,
14578 n: &mut Neighbours,
14579 at_mi: (usize, usize),
14580 blk_max_px: usize,
14581 (max_w_mi, max_h_mi): (usize, usize),
14582 (tx_w, tx_h): (usize, usize),
14583 depth: usize,
14584 blk_row: usize,
14585 blk_col: usize,
14586 out: &mut Vec<(usize, usize, usize, usize)>,
14587) {
14588 if blk_row >= max_h_mi || blk_col >= max_w_mi {
14589 return;
14590 }
14591 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
14592 if depth == MAX_VARTX_DEPTH {
14593 out.push((blk_row, blk_col, tx_w, tx_h));
14594 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
14595 return;
14596 }
14597 let ctx = txfm_partition_ctx_rect(
14598 n.above_txfm[unit.1],
14599 n.left_txfm[unit.0],
14600 blk_max_px,
14601 tx_w,
14602 tx_h,
14603 );
14604 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
14605 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
14606 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14607 let (rng, _) = dec.debug_state();
14608 eprintln!(
14609 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
14610 unit.0,
14611 unit.1,
14612 u8::from(split)
14613 );
14614 }
14615 if !split {
14616 out.push((blk_row, blk_col, tx_w, tx_h));
14617 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
14618 return;
14619 }
14620 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
14621 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
14622 if (sub_w, sub_h) == (4, 4) {
14623 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
14624 // unit is marked 4x4 (raster order) without recursing.
14625 for row in 0..tx_h / MI {
14626 for col in 0..tx_w / MI {
14627 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
14628 out.push((blk_row + row, blk_col + col, 4, 4));
14629 }
14630 }
14631 }
14632 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
14633 return;
14634 }
14635 for row in (0..tx_h / MI).step_by(sub_h / MI) {
14636 for col in (0..tx_w / MI).step_by(sub_w / MI) {
14637 read_var_tx_size(
14638 dec,
14639 cdfs,
14640 n,
14641 at_mi,
14642 blk_max_px,
14643 (max_w_mi, max_h_mi),
14644 (sub_w, sub_h),
14645 depth + 1,
14646 blk_row + row,
14647 blk_col + col,
14648 out,
14649 );
14650 }
14651 }
14652}
14653
14654/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
14655/// branch): every block of a `TxMode::Select` inter frame codes its transform
14656/// size right after its own mode info -- an inter non-skip block through the
14657/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
14658/// every other block through the intra `tx_depth` symbol (a skipped inter
14659/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
14660/// block's own resolved transform side and the leaf list, the latter only
14661/// when the tree resolved to more than one transform unit.
14662#[allow(clippy::too_many_arguments)]
14663fn read_block_tx_size(
14664 dec: &mut SymbolDecoder,
14665 cdfs: &mut Cdfs,
14666 n: &mut Neighbours,
14667 at_mi: (usize, usize),
14668 side: usize,
14669 (mi_cols, mi_rows): (usize, usize),
14670 is_inter: bool,
14671 skip: bool,
14672) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
14673 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
14674 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
14675 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
14676 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
14677 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
14678 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
14679 if side > 64 {
14680 let step = 64 / MI;
14681 let mut leaves = Vec::new();
14682 for row in (0..side / MI).step_by(step) {
14683 for col in (0..side / MI).step_by(step) {
14684 leaves.push((row, col, 64, 64));
14685 }
14686 }
14687 return Ok((64, Some(leaves)));
14688 }
14689 return Ok((side, None));
14690 }
14691 let side_mi = side / MI;
14692 if is_inter && !skip {
14693 let max_tx = side.min(64);
14694 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
14695 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
14696 let mut leaves = Vec::new();
14697 let step = max_tx / MI;
14698 for row in (0..side_mi).step_by(step) {
14699 for col in (0..side_mi).step_by(step) {
14700 read_var_tx_size(
14701 dec,
14702 cdfs,
14703 n,
14704 at_mi,
14705 side,
14706 (max_w_mi, max_h_mi),
14707 (max_tx, max_tx),
14708 0,
14709 row,
14710 col,
14711 &mut leaves,
14712 );
14713 }
14714 }
14715 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
14716 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
14717 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
14718 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
14719 // which the mu-chunk reader above codes as their 32x32 coded corner.
14720 let leaf_ceiling = if side > 64 { 64 } else { 32 };
14721 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
14722 // Only a block wider than a superblock's own 64x64 max transform
14723 // reaches here; this crate has no 64-point *inter* coefficient
14724 // table set ([`inter_txbset_for`] stops at 32).
14725 return Err(unsupported(
14726 "an inter var-tx tree with a leaf transform larger than 32x32",
14727 ));
14728 }
14729 let resolved = leaves.last().map_or(side, |l| l.2);
14730 return Ok((resolved, (!single).then_some(leaves)));
14731 }
14732 let tx = if is_inter {
14733 side.min(64)
14734 } else {
14735 read_tx_size(
14736 dec,
14737 cdfs,
14738 n,
14739 at_mi,
14740 side,
14741 // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm
14742 // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`,
14743 // which is 64 for BLOCK_128X128 -- never the block's own 128 side.
14744 Some(tx_size_context_txfm(n, at_mi, side.min(64))),
14745 )
14746 };
14747 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
14748 if !is_inter && tx != side {
14749 // lane-intrainter r1: an intra block inside an inter frame whose
14750 // `tx_depth` split its luma transform codes exactly the key-frame
14751 // split path's transform units (`decode_block`'s multi-TU loop),
14752 // raster order over the block. Handed back in the same leaf shape the
14753 // inter var-tx tree uses, so the caller's per-TU luma loop, the
14754 // `record_split_luma` neighbour write-back and the per-TU deblock
14755 // edges are the ones it already runs for a var-tx inter block. A
14756 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
14757 // seeing `Some` here.
14758 let step = tx / MI;
14759 let mut leaves = Vec::new();
14760 for row in (0..side_mi).step_by(step) {
14761 for col in (0..side_mi).step_by(step) {
14762 leaves.push((row, col, tx, tx));
14763 }
14764 }
14765 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
14766 let mut h = c.get();
14767 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
14768 c.set(h);
14769 });
14770 return Ok((tx, Some(leaves)));
14771 }
14772 Ok((tx, None))
14773}
14774
14775/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
14776/// decoder codes -- a 2:1 strip whose own max rect transform
14777/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
14778/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
14779/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
14780/// 64-point rect transform, and 16x8/8x16 needs
14781/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
14782/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
14783/// rect transform), neither of which exists yet -- both stay refused by name.
14784pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
14785 matches!(
14786 (w, h),
14787 // 2:1 strips whose transform is coded in full (lane-inter4).
14788 (32, 16) | (16, 32) | (16, 8) | (8, 16)
14789 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
14790 // codes all 64 of its positions, and its chroma pair is an 8x4 /
14791 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
14792 | (16, 4) | (4, 16)
14793 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
14794 // only the low 32 coefficients of a 64-length axis, so these read
14795 // exactly the truncated corner the INTRA superblock-strip path
14796 // already reads (`read_intra_mode_rect`), through
14797 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
14798 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
14799 // `tx_type` symbol is coded at all.
14800 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
14801 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
14802 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
14803 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
14804 // refused earlier ("an inter partition below 8x8").
14805 | (8, 4) | (4, 8)
14806 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
14807 // one rectangular transform -- `max_txsize_rect_lookup
14808 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
14809 // TX_64X64 units read through the mu-chunk loop, same as the
14810 // 128x128 NONE block's four.
14811 | (128, 64) | (64, 128)
14812 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
14813 // 10-bit film cuts and every measured 1080p offset stop on
14814 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
14815 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
14816 // positions, and its chroma pair is a 16x4 / 4x16 unit
14817 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
14818 | (32, 8) | (8, 32)
14819 )
14820}
14821
14822// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
14823// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
14824// the "rectangular ... has no ... here" refusals. `side` is the square context
14825// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
14826// `inter_piece!` derives `reject_residual` from exactly that inequality, so
14827// these triples are what decides whether those refusals can fire at all. Bit
14828// 31 is "a triple this table does not list", which is what makes the gate a
14829// census rather than a restatement of its own table.
14830pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
14831 (16, 16, 16),
14832 (32, 32, 32),
14833 (32, 16, 32),
14834 (32, 32, 16),
14835 (16, 8, 16),
14836 (16, 16, 8),
14837 (32, 8, 32),
14838 (64, 64, 64),
14839 (32, 32, 8),
14840 (64, 16, 64),
14841 (128, 128, 128),
14842 (64, 32, 64),
14843 (64, 64, 32),
14844 (16, 4, 16),
14845 (64, 64, 16),
14846 (16, 16, 4),
14847 (128, 128, 64),
14848 (128, 64, 128),
14849];
14850
14851/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
14852/// outside [`INTER_BLOCK_SHAPES`].
14853pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
14854
14855thread_local! {
14856 static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
14857}
14858
14859/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
14860/// gate reading it sees only the streams it decoded itself).
14861pub fn inter_block_shape_mask() -> u32 {
14862 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
14863}
14864
14865/// Records one block's shape. The table is ordered by measured frequency over
14866/// the three witnesses the census gate decodes, so the common square shapes
14867/// leave the scan on their first comparison.
14868fn census_inter_block_shape(side: usize, w: usize, h: usize) {
14869 let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) {
14870 Some(i) => 1u32 << i,
14871 None => INTER_BLOCK_SHAPE_UNLISTED,
14872 };
14873 let seen = inter_block_shape_mask();
14874 if seen & bit == 0 {
14875 INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit));
14876 }
14877}
14878
14879/// The luma coefficient/`tx_type` table set of a whole-block rectangular
14880/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
14881/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
14882/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
14883/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
14884/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
14885/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
14886/// row (`txsize_sqr_map`), never the 16x16 one.
14887fn rect_inter_luma_set(w: usize, h: usize) -> Result<TxbSet> {
14888 Ok(match (w, h) {
14889 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
14890 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
14891 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
14892 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
14893 // ALL16 otherwise -- both at the TX_4X4 row.
14894 (8, 4) | (4, 8) => {
14895 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
14896 TxbSet::LumaRect8x4Inter
14897 } else {
14898 TxbSet::LumaRect8x4InterSet1
14899 }
14900 }
14901 (16, 4) | (4, 16) => {
14902 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
14903 TxbSet::LumaRect16x4Inter
14904 } else {
14905 TxbSet::LumaRect16x4Inter1
14906 }
14907 }
14908 (16, 8) | (8, 16) => {
14909 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
14910 TxbSet::LumaRect16x8Inter
14911 } else {
14912 TxbSet::LumaRect16x8InterSet1
14913 }
14914 }
14915 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
14916 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
14917 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
14918 // adjusted size, so the existing sets are bit-exact. Neither carries a
14919 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
14920 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
14921 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
14922 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
14923 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
14924 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
14925 (64, 32) | (32, 64) => TxbSet::Luma64,
14926 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
14927 _ => {
14928 return Err(unsupported(
14929 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
14930 ));
14931 }
14932 })
14933}
14934
14935/// The chroma table set of the same block's single rectangular chroma unit
14936/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
14937/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
14938/// the luma unit's.
14939fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
14940 Ok(match (w, h) {
14941 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
14942 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
14943 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
14944 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
14945 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
14946 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
14947 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
14948 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
14949 (32, 8) | (8, 32) => TxbSet::Chroma16,
14950 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
14951 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
14952 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
14953 (16, 4) | (4, 16) => TxbSet::Chroma8,
14954 _ => {
14955 return Err(unsupported(
14956 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
14957 ));
14958 }
14959 })
14960}
14961
14962/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
14963/// inter path reaches, from the block's TRUE footprint rather than the
14964/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
14965/// everything 32 and above -> 3.
14966fn size_group_wh(w: usize, h: usize) -> usize {
14967 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
14968 // `common_data.h:60`) is 0 for every block with a 4-px side
14969 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
14970 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
14971 match w.min(h) {
14972 0..=4 => 0,
14973 8 => 1,
14974 16 => 2,
14975 _ => 3,
14976 }
14977}
14978
14979#[test]
14980fn size_group_wh_matches_libaom_size_group_lookup() {
14981 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
14982 // transcribed values (common_data.h:60-62).
14983 const TABLE: [((usize, usize), usize); 22] = [
14984 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
14985 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
14986 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
14987 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
14988 ];
14989 for ((w, h), want) in TABLE {
14990 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
14991 }
14992}
14993
14994/// The default (2D) coefficient scan of a rectangular transform.
14995fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
14996 Ok(match (w, h) {
14997 (32, 16) => &SCAN_32X16,
14998 (16, 32) => &SCAN_16X32,
14999 (16, 8) => &SCAN_16X8,
15000 (8, 16) => &SCAN_8X16,
15001 (16, 4) => &SCAN_16X4,
15002 (4, 16) => &SCAN_4X16,
15003 (8, 4) => &SCAN_8X4,
15004 (4, 8) => &SCAN_4X8,
15005 (32, 8) => &SCAN_32X8,
15006 (8, 32) => &SCAN_8X32,
15007 _ => {
15008 return Err(unsupported(
15009 "a rectangular transform unit whose shape has no coefficient scan table here",
15010 ));
15011 }
15012 })
15013}
15014
15015/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
15016/// transform unit whose shape has no coefficient table set here" / "a
15017/// rectangular transform unit whose shape has no coefficient scan table here"
15018/// arms, enumerated against the MEASURED domain of the inter block path
15019/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
15020/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
15021///
15022/// What each helper is actually handed:
15023///
15024/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
15025/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
15026/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
15027/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
15028/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
15029/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
15030/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
15031/// unit, and only when that corner is not 32x32 (a square corner goes
15032/// through the square reader with `rect_shape = Some((w, h))`).
15033///
15034/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
15035/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
15036/// loop, which is why they are skipped below.
15037#[test]
15038fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
15039 let corner_scan = |w: usize, h: usize| {
15040 let (cw, ch) = (w.min(32), h.min(32));
15041 if (cw, ch) == (32, 32) {
15042 return; // the square coefficient reader, not `rect_scan`
15043 }
15044 assert!(
15045 rect_scan(cw, ch).is_ok(),
15046 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
15047 );
15048 };
15049 let mut checked = 0;
15050 for &(side, w, h) in &INTER_BLOCK_SHAPES {
15051 if (w, h) == (side, side) || w.max(h) > 64 {
15052 continue;
15053 }
15054 assert!(
15055 rect_inter_luma_set(w, h).is_ok(),
15056 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
15057 );
15058 corner_scan(w, h);
15059 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
15060 // footprint for every other shape.
15061 let (cw, ch) = match (w, h) {
15062 (16, 4) => (8, 4),
15063 (4, 16) => (4, 8),
15064 _ => (w / 2, h / 2),
15065 };
15066 assert!(
15067 rect_inter_chroma_set(cw, ch).is_ok(),
15068 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
15069 );
15070 corner_scan(cw, ch);
15071 checked += 1;
15072 }
15073 assert_eq!(
15074 checked, 12,
15075 "the block-shape census changed: {checked} rect shapes reach the rect transform \
15076 tables, not the 12 this claim was measured over"
15077 );
15078 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
15079 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
15080 for (w, h) in [(8usize, 4usize), (4, 8)] {
15081 assert!(
15082 rect_inter_luma_set(w, h).is_ok(),
15083 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
15084 );
15085 corner_scan(w, h);
15086 }
15087}
15088
15089/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
15090/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
15091/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
15092/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
15093/// own width/height; a `0` leaves one whole-block rect transform unit
15094/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
15095/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
15096/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
15097/// every leaf of a split rect block is square and the existing square leaf
15098/// loop reconstructs it unchanged.
15099#[allow(clippy::too_many_arguments)]
15100fn read_block_tx_size_rect(
15101 dec: &mut SymbolDecoder,
15102 cdfs: &mut Cdfs,
15103 n: &mut Neighbours,
15104 at_mi: (usize, usize),
15105 (bw, bh): (usize, usize),
15106 (mi_cols, mi_rows): (usize, usize),
15107 skip: bool,
15108) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
15109 if skip {
15110 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
15111 // its own BLOCK size -- width above, height left -- not a transform.
15112 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
15113 return Ok(None);
15114 }
15115 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
15116 // `rect_inter_residual_supported` has already excluded everything above 32.
15117 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
15118 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
15119 // is TWO square top-level transform units side by side and a 64x128 one is
15120 // two stacked -- exactly what libaom `read_block_tx_size`
15121 // (decodeframe.c:1140) codes with its `idy/idx` loop over
15122 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
15123 // own `txfm_partition` symbol at depth 0.
15124 if bw.max(bh) > 64 {
15125 let tx = 64usize;
15126 let (max_w_mi, max_h_mi) = (
15127 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
15128 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
15129 );
15130 let mut leaves = Vec::new();
15131 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
15132 for row in (0..bh / MI).step_by(tx / MI) {
15133 for col in (0..bw / MI).step_by(tx / MI) {
15134 leaves.push((row, col, tx, tx));
15135 }
15136 }
15137 for &(row, col, tw, th) in &leaves {
15138 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
15139 }
15140 return Ok(Some(leaves));
15141 }
15142 for row in (0..bh / MI).step_by(tx / MI) {
15143 for col in (0..bw / MI).step_by(tx / MI) {
15144 read_var_tx_size(
15145 dec,
15146 cdfs,
15147 n,
15148 at_mi,
15149 bw.max(bh),
15150 (max_w_mi, max_h_mi),
15151 (tx, tx),
15152 0,
15153 row,
15154 col,
15155 &mut leaves,
15156 );
15157 }
15158 }
15159 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
15160 return Err(unsupported(
15161 "an inter var-tx tree with a leaf transform larger than 64x64",
15162 ));
15163 }
15164 return Ok(Some(leaves));
15165 }
15166 let (tx_w, tx_h) = (bw, bh);
15167 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
15168 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
15169 // transform, and `set_txfm_ctxs` records exactly what
15170 // `txfm_partition_update` would for that same unit.
15171 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
15172 RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
15173 return Ok(None);
15174 }
15175 let ctx = txfm_partition_ctx_rect(
15176 n.above_txfm[at_mi.1],
15177 n.left_txfm[at_mi.0],
15178 bw.max(bh),
15179 tx_w,
15180 tx_h,
15181 );
15182 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
15183 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
15184 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15185 let (rng, _) = dec.debug_state();
15186 eprintln!(
15187 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
15188 at_mi.0,
15189 at_mi.1,
15190 u8::from(split)
15191 );
15192 }
15193 if !split {
15194 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
15195 RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
15196 return Ok(None);
15197 }
15198 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
15199 RECT_INTER_TXSPLIT_HITS.with(|c| c.set(c.get() + 1));
15200 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
15201 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
15202 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
15203 // rect one and its leaves carry their own width and height.
15204 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
15205 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
15206 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
15207 let mut leaves = Vec::new();
15208 for row in (0..bh / MI).step_by(sub_h / MI) {
15209 for col in (0..bw / MI).step_by(sub_w / MI) {
15210 read_var_tx_size(
15211 dec,
15212 cdfs,
15213 n,
15214 at_mi,
15215 bw.max(bh),
15216 (max_w_mi, max_h_mi),
15217 (sub_w, sub_h),
15218 1,
15219 row,
15220 col,
15221 &mut leaves,
15222 );
15223 }
15224 }
15225 Ok(Some(leaves))
15226}
15227
15228/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
15229/// the coefficients are read with the rect coefficient machinery
15230/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
15231/// types), inverted with the rect inverse transform
15232/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
15233/// and added onto the top-left `w x h` of the block's own square-strided
15234/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
15235/// and the coded `tx_type`.
15236///
15237/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
15238/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
15239#[allow(clippy::too_many_arguments)]
15240fn read_inter_plane_rect(
15241 dec: &mut SymbolDecoder,
15242 cdfs: &mut Cdfs,
15243 set: TxbSet,
15244 (w, h): (usize, usize),
15245 stride: usize,
15246 plane_idx: usize,
15247 around: (bool, bool, i32),
15248 tx_mode: usize,
15249 plane: &mut PlaneBuf,
15250 x: usize,
15251 y: usize,
15252 prediction: &[u16],
15253 inherited_luma_tx_type: Option<TxType>,
15254 luma_skip_ctx: Option<usize>,
15255) -> Result<(Vec<i32>, TxType)> {
15256 let skip_ctx = if plane_idx == 0 {
15257 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
15258 // block; a var-tx leaf passes its own neighbour-table context.
15259 luma_skip_ctx.unwrap_or(0)
15260 } else {
15261 usize::from(around.0) + usize::from(around.1)
15262 };
15263 let mut coding = cdfs.txb(set, tx_mode);
15264 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
15265 // the *longer* side of this rect transform.
15266 let default_tx_type = match inherited_luma_tx_type {
15267 Some(t) => reduce_inherited_chroma_tx_type(t, w, h),
15268 None => TxType::DctDct,
15269 };
15270 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
15271 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
15272 // corner, zero-extended into the true `w x h` grid before the inverse
15273 // transform -- exactly what the intra superblock-strip path does. A
15274 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
15275 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
15276 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
15277 // rectangular shape (lane-sbpart r8).
15278 let (cw, ch) = (w.min(32), h.min(32));
15279 if plane_idx == 0 && w.max(h) == 64 {
15280 RECT64_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
15281 }
15282 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
15283 RECT32X8_INTER_TU_HITS.with(|c| {
15284 let mut v = c.get();
15285 v[usize::from(w == 8)] += 1;
15286 c.set(v);
15287 });
15288 }
15289 let (corner, tx_type) = if (cw, ch) == (32, 32) {
15290 let scan32 = default_scan(TX32);
15291 read_coeffs(
15292 dec,
15293 &mut coding,
15294 &scan32,
15295 skip_ctx,
15296 dc_sign_ctx(around.2),
15297 default_tx_type,
15298 Some((w, h)),
15299 )?
15300 } else {
15301 read_coeffs_rect(
15302 dec,
15303 &mut coding,
15304 rect_scan(cw, ch)?,
15305 cw,
15306 ch,
15307 skip_ctx,
15308 dc_sign_ctx(around.2),
15309 default_tx_type,
15310 )?
15311 };
15312 let grid = if (cw, ch) == (w, h) {
15313 corner
15314 } else {
15315 let mut full = vec![0i32; w * h];
15316 for row in 0..ch {
15317 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
15318 }
15319 full
15320 };
15321 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
15322 let residual = dequant_and_inverse_typed_wh(
15323 &grid,
15324 w,
15325 h,
15326 bit_depth(),
15327 block_q_idx(),
15328 dc_delta,
15329 ac_delta,
15330 tx_type,
15331 );
15332 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
15333 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
15334 }
15335 // `reconstruct_mc_rect` reads both buffers at the square prediction
15336 // stride, so the dense `w x h` residual is re-laid at that stride first.
15337 let mut strided = vec![0i32; stride * stride];
15338 for row in 0..h {
15339 strided[row * stride..][..w].copy_from_slice(&residual[row * w..][..w]);
15340 }
15341 plane.reconstruct_mc_rect(x, y, stride, w, h, prediction, &strided);
15342 Ok((grid, tx_type))
15343}
15344
15345/// A rect coefficient grid re-laid into the square `stride x stride` grid the
15346/// neighbour/deblock stamps downstream of the residual expect.
15347fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
15348 let mut full = vec![0i32; stride * stride];
15349 for row in 0..h {
15350 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
15351 }
15352 full
15353}
15354
15355/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
15356/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
15357/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
15358/// raster order, each reading its own coefficient context off the units
15359/// already decoded before it. Returns the block's luma grid (all-zero in the
15360/// split case, whose reconstruction has already happened unit by unit) and
15361/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
15362/// which for a split block lands on the top-left unit.
15363#[allow(clippy::too_many_arguments)]
15364fn read_inter_luma8(
15365 dec: &mut SymbolDecoder,
15366 cdfs: &mut Cdfs,
15367 neighbours: &mut Neighbours,
15368 leaf_mi: (usize, usize),
15369 y: &mut PlaneBuf,
15370 px: usize,
15371 py: usize,
15372 pred_y: &[u16],
15373 mode_for_tx: usize,
15374 base_q_idx: u8,
15375 scan8: &[u16],
15376 scan4: &[u16],
15377 reduced_tx_set: bool,
15378 split: bool,
15379) -> Result<(Vec<i32>, TxType)> {
15380 if !split {
15381 return read_inter_plane(
15382 dec,
15383 cdfs,
15384 if reduced_tx_set {
15385 TxbSet::Luma8Inter
15386 } else {
15387 TxbSet::Luma8InterSet1
15388 },
15389 scan8,
15390 0,
15391 neighbours.around_mi(leaf_mi, 8)[0],
15392 mode_for_tx,
15393 y,
15394 px,
15395 py,
15396 8,
15397 base_q_idx,
15398 pred_y,
15399 None,
15400 None,
15401 );
15402 }
15403 let mut first = TxType::DctDct;
15404 for tu_row in 0..2 {
15405 for tu_col in 0..2 {
15406 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
15407 let mut tu_pred = Vec::with_capacity(16);
15408 for rr in 0..4 {
15409 let start = (tu_row * 4 + rr) * 8 + tu_col * 4;
15410 tu_pred.extend_from_slice(&pred_y[start..start + 4]);
15411 }
15412 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
15413 let (tu_grid, tu_tx_type) = read_inter_plane(
15414 dec,
15415 cdfs,
15416 if reduced_tx_set {
15417 TxbSet::Luma4Inter
15418 } else {
15419 TxbSet::Luma4InterSet1
15420 },
15421 scan4,
15422 0,
15423 neighbours.around_mi(tu_mi, 4)[0],
15424 mode_for_tx,
15425 y,
15426 px + tu_col * 4,
15427 py + tu_row * 4,
15428 4,
15429 base_q_idx,
15430 &tu_pred,
15431 None,
15432 Some(tu_skip_ctx),
15433 )?;
15434 if tu_row == 0 && tu_col == 0 {
15435 first = tu_tx_type;
15436 }
15437 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
15438 }
15439 }
15440 Ok((vec![0i32; 64], first))
15441}
15442
15443/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
15444/// coefficient tables from -- the inter counterpart of [`txbset_for`].
15445/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
15446/// an inter block's chroma transform inherits the *colocated luma* unit's
15447/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
15448/// of the extended set the CHROMA transform size selects
15449/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
15450/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
15451/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
15452/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
15453/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
15454/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
15455/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
15456/// sync and only corrupted the inverse transform (one 64x64 superblock of
15457/// high-frequency chroma noise, luma bit-exact).
15458fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize) -> TxType {
15459 use TxType::*;
15460 let sqr_up = w.max(h);
15461 let sqr = w.min(h);
15462 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
15463 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
15464 let allowed: &[TxType] = if sqr_up > 32 {
15465 // EXT_TX_SET_DCTONLY
15466 &[DctDct]
15467 } else if sqr_up == 32 || reduced {
15468 // EXT_TX_SET_DCT_IDTX
15469 &[DctDct, Idtx]
15470 } else if sqr == 16 {
15471 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
15472 // the four 1D ADST/FLIPADST types.
15473 &[
15474 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
15475 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
15476 ]
15477 } else {
15478 // EXT_TX_SET_ALL16
15479 return t;
15480 };
15481 if allowed.contains(&t) { t } else { DctDct }
15482}
15483
15484fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
15485 match tx_px {
15486 // lane-sb128c r1: a 128x128 inter block's own luma unit
15487 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
15488 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
15489 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
15490 // coincide -- exactly the set the whole-64x64 inter block already uses.
15491 64 => TxbSet::Luma64,
15492 32 => TxbSet::Luma32Inter,
15493 16 if reduced_tx_set => TxbSet::Luma16Inter,
15494 16 => TxbSet::Luma16InterSet1,
15495 8 if reduced_tx_set => TxbSet::Luma8Inter,
15496 8 => TxbSet::Luma8InterSet1,
15497 4 if reduced_tx_set => TxbSet::Luma4Inter,
15498 4 => TxbSet::Luma4InterSet1,
15499 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
15500 }
15501}
15502
15503/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
15504/// the only four sizes a `TxMode::Select` block's coded coefficient grid
15505/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
15506fn scan_for<'a>(
15507 tx_px: usize,
15508 scan32: &'a [u16],
15509 scan16: &'a [u16],
15510 scan8: &'a [u16],
15511 scan4: &'a [u16],
15512) -> &'a [u16] {
15513 match tx_px {
15514 32 => scan32,
15515 16 => scan16,
15516 8 => scan8,
15517 4 => scan4,
15518 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
15519 }
15520}
15521
15522/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
15523/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
15524/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
15525/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
15526/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
15527/// regardless of the flag (`av1_get_ext_tx_set_type`'s
15528/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
15529/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
15530/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
15531/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
15532/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
15533/// inter `ext_tx` sets, never the mode-indexed intra ones.
15534fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
15535 match tx_px {
15536 64 => TxbSet::Luma64,
15537 32 => TxbSet::Luma32Inter,
15538 16 if reduced_tx_set => TxbSet::Luma16Inter,
15539 16 => TxbSet::Luma16InterSet1,
15540 8 if reduced_tx_set => TxbSet::Luma8Inter,
15541 8 => TxbSet::Luma8InterSet1,
15542 _ => TxbSet::Luma64,
15543 }
15544}
15545
15546fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
15547 match tx_px {
15548 64 => TxbSet::Luma64,
15549 32 => TxbSet::Luma32,
15550 16 => TxbSet::Luma16,
15551 8 if reduced_tx_set => TxbSet::Luma8,
15552 8 => TxbSet::Luma8Set1,
15553 4 if reduced_tx_set => TxbSet::Luma4,
15554 4 => TxbSet::Luma4Set1,
15555 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
15556 }
15557}
15558
15559/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
15560/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
15561fn unit_log2(px: u32) -> i32 {
15562 if px == 0 {
15563 0
15564 } else {
15565 px.trailing_zeros() as i32 - 2
15566 }
15567}
15568
15569/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
15570/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
15571/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
15572/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
15573/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
15574/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
15575/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
15576/// block anywhere aborted the whole stream's decode before comparison).
15577fn lf_level(
15578 lf: &LoopFilterParams,
15579 plane_idx: usize,
15580 dir: usize,
15581 ref_frame: i8,
15582 delta_lf: i32,
15583 segment_id: u8,
15584) -> i32 {
15585 let base = i32::from(if plane_idx == 0 {
15586 lf.level[dir]
15587 } else if plane_idx == 1 {
15588 lf.level[2]
15589 } else {
15590 lf.level[3]
15591 });
15592 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
15593 // ref/mode delta scaling below, and regardless of `delta_enabled`
15594 // (that flag only gates `ref_deltas`/`mode_deltas`).
15595 let base = (base + delta_lf).clamp(0, 63);
15596 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
15597 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
15598 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
15599 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
15600 // for chroma.
15601 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
15602 let base = match seg_feature(usize::from(segment_id), feature) {
15603 Some(data) => (base + data).clamp(0, 63),
15604 None => base,
15605 };
15606 if !lf.delta_enabled {
15607 return base;
15608 }
15609 let scale = 1i32 << (base >> 5);
15610 let is_inter = ref_frame != 0;
15611 let is_globalmv = ref_frame < 0;
15612 let ref_idx = ref_frame.unsigned_abs() as usize;
15613 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
15614 if is_inter {
15615 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
15616 }
15617 lvl.clamp(0, 63)
15618}
15619
15620/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
15621/// no-segmentation, no-delta-LF path and to this decoder's own invariant
15622/// that a coded block's transform is always its own full size -- so a TU
15623/// edge is always also a PU edge, and the "both sides skipped, not a PU
15624/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
15625/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
15626/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
15627fn edge_params(
15628 lf: &LoopFilterParams,
15629 n: &Neighbours,
15630 plane_idx: usize,
15631 dir: usize,
15632 chroma: bool,
15633 x0: usize,
15634 y0: usize,
15635) -> Option<(u8, i32)> {
15636 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
15637 let cur_tx = if dir == 0 {
15638 tx_px_at(n, chroma, mi_r, mi_c)
15639 } else {
15640 tx_h_px_at(n, chroma, mi_r, mi_c)
15641 };
15642 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
15643 return None;
15644 }
15645 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
15646 let (pv_mi_r, pv_mi_c) = if dir == 0 {
15647 (mi_r, mi_c - 1)
15648 } else {
15649 (mi_r - 1, mi_c)
15650 };
15651 let pv_tx = if dir == 0 {
15652 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
15653 } else {
15654 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
15655 };
15656 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
15657 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
15658 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
15659 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
15660
15661 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
15662 // SKIPPED INTER blocks is filtered only when it is also a prediction
15663 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
15664 // omission of this term (on the stale invariant "a coded block's transform
15665 // is always its own full size", which var-tx broke) had us filtering an
15666 // interior 8-px lattice the reference never touches: on the pinned 192x68
15667 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
15668 let cur_org = n.blk_org_grid[mi_r * n.skip_grid_cols_mi + mi_c];
15669 let pu_edge = if dir == 0 {
15670 mi_c == usize::from(cur_org[1])
15671 } else {
15672 mi_r == usize::from(cur_org[0])
15673 };
15674 if !pu_edge
15675 && cur_ref != 0
15676 && pv_ref != 0
15677 && n.skip_at(mi_r, mi_c)
15678 && n.skip_at(pv_mi_r, pv_mi_c)
15679 {
15680 return None;
15681 }
15682 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
15683 let pv_level = lf_level(
15684 lf,
15685 plane_idx,
15686 dir,
15687 pv_ref,
15688 pv_delta_lf,
15689 segment_id_at(pv_mi_r, pv_mi_c),
15690 );
15691 if cur_level == 0 && pv_level == 0 {
15692 return None;
15693 }
15694 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
15695 let len: u8 = if chroma {
15696 if dim == 0 { 4 } else { 6 }
15697 } else {
15698 [4, 8, 14, 14, 14][dim]
15699 };
15700 let level = if cur_level != 0 { cur_level } else { pv_level };
15701 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
15702 Some((len, level))
15703}
15704
15705/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
15706fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
15707 let sharpness = i32::from(sharpness);
15708 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
15709 let mut lim = level >> shift;
15710 if sharpness > 0 {
15711 lim = lim.min(9 - sharpness);
15712 }
15713 lim = lim.max(1);
15714 (2 * (level + 2) + lim, lim, level >> 4)
15715}
15716
15717fn sclamp(v: i32) -> i32 {
15718 // libaom's `signed_char_clamp_high`: the clamp range scales with
15719 // `128 << (bit_depth - 8)` alongside the centering constant below.
15720 let scale = 1i32 << (bit_depth() - 8);
15721 v.clamp(-128 * scale, 128 * scale - 1)
15722}
15723
15724fn round_pow2(v: i32, n: u32) -> i32 {
15725 (v + (1 << (n - 1))) >> n
15726}
15727
15728/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
15729/// fallback.
15730fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
15731 if !mask {
15732 return [p1, p0, q0, q1];
15733 }
15734 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
15735 let centre = 128i32 << (bit_depth() - 8);
15736 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
15737 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
15738 let filter = sclamp(outer + 3 * (qs0 - ps0));
15739 let filter1 = sclamp(filter + 4) >> 3;
15740 let filter2 = sclamp(filter + 3) >> 3;
15741 let oq0 = sclamp(qs0 - filter1) + centre;
15742 let op0 = sclamp(ps0 + filter2) + centre;
15743 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
15744 let oq1 = sclamp(qs1 - tap) + centre;
15745 let op1 = sclamp(ps1 + tap) + centre;
15746 [op1, op0, oq0, oq1]
15747}
15748
15749/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
15750/// `filter4`'s narrow taps.
15751#[allow(clippy::too_many_arguments)]
15752fn filter6(
15753 mask: bool,
15754 thresh: i32,
15755 flat: bool,
15756 p2: i32,
15757 p1: i32,
15758 p0: i32,
15759 q0: i32,
15760 q1: i32,
15761 q2: i32,
15762) -> [i32; 4] {
15763 if flat && mask {
15764 [
15765 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
15766 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
15767 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
15768 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
15769 ]
15770 } else {
15771 filter4(mask, thresh, p1, p0, q0, q1)
15772 }
15773}
15774
15775/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
15776#[allow(clippy::too_many_arguments)]
15777fn filter8(
15778 mask: bool,
15779 thresh: i32,
15780 flat: bool,
15781 p3: i32,
15782 p2: i32,
15783 p1: i32,
15784 p0: i32,
15785 q0: i32,
15786 q1: i32,
15787 q2: i32,
15788 q3: i32,
15789) -> [i32; 6] {
15790 if flat && mask {
15791 [
15792 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
15793 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
15794 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
15795 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
15796 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
15797 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
15798 ]
15799 } else {
15800 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
15801 [p2, op1, op0, oq0, oq1, q2]
15802 }
15803}
15804
15805/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
15806/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
15807/// way -- they are only ever taps here, never written).
15808#[allow(clippy::too_many_arguments)]
15809fn filter14(
15810 mask: bool,
15811 thresh: i32,
15812 flat: bool,
15813 flat2: bool,
15814 p6: i32,
15815 p5: i32,
15816 p4: i32,
15817 p3: i32,
15818 p2: i32,
15819 p1: i32,
15820 p0: i32,
15821 q0: i32,
15822 q1: i32,
15823 q2: i32,
15824 q3: i32,
15825 q4: i32,
15826 q5: i32,
15827 q6: i32,
15828) -> [i32; 12] {
15829 if flat2 && flat && mask {
15830 [
15831 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
15832 round_pow2(
15833 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
15834 4,
15835 ),
15836 round_pow2(
15837 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
15838 4,
15839 ),
15840 round_pow2(
15841 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
15842 4,
15843 ),
15844 round_pow2(
15845 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
15846 4,
15847 ),
15848 round_pow2(
15849 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
15850 4,
15851 ),
15852 round_pow2(
15853 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
15854 4,
15855 ),
15856 round_pow2(
15857 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
15858 4,
15859 ),
15860 round_pow2(
15861 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
15862 4,
15863 ),
15864 round_pow2(
15865 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
15866 4,
15867 ),
15868 round_pow2(
15869 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
15870 4,
15871 ),
15872 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
15873 ]
15874 } else {
15875 let [op2, op1, op0, oq0, oq1, oq2] =
15876 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
15877 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
15878 }
15879}
15880
15881/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
15882/// the first (`q0`) sample past the edge, `outer_stride` advances to the
15883/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
15884/// the next along the edge's own filtering direction.
15885#[allow(clippy::too_many_arguments)]
15886fn filter_edge(
15887 data: &mut [u16],
15888 base: usize,
15889 outer_stride: isize,
15890 tap_stride: isize,
15891 len: u8,
15892 level: i32,
15893 sharpness: u8,
15894) {
15895 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
15896 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
15897 // every 8-bit threshold (including the flat masks' fixed `1`) is
15898 // compared against a raw pixel difference on the stream's own bit-depth
15899 // scale, so each is shifted left by `bit_depth - 8` before use.
15900 let shift = bit_depth() - 8;
15901 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
15902 let flat_thresh = 1i32 << shift;
15903 for i in 0..4isize {
15904 let center = (base as isize + i * outer_stride) as usize;
15905 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
15906 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
15907 match len {
15908 4 => {
15909 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
15910 let mask = (p1 - p0).abs() <= limit
15911 && (q1 - q0).abs() <= limit
15912 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
15913 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
15914 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
15915 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
15916 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
15917 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
15918 }
15919 6 => {
15920 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
15921 let mask = (p2 - p1).abs() <= limit
15922 && (p1 - p0).abs() <= limit
15923 && (q1 - q0).abs() <= limit
15924 && (q2 - q1).abs() <= limit
15925 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
15926 let flat = (p1 - p0).abs() <= flat_thresh
15927 && (q1 - q0).abs() <= flat_thresh
15928 && (p2 - p0).abs() <= flat_thresh
15929 && (q2 - q0).abs() <= flat_thresh;
15930 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
15931 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
15932 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
15933 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
15934 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
15935 }
15936 8 => {
15937 let (p3, p2, p1, p0, q0, q1, q2, q3) =
15938 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
15939 let mask = (p3 - p2).abs() <= limit
15940 && (p2 - p1).abs() <= limit
15941 && (p1 - p0).abs() <= limit
15942 && (q1 - q0).abs() <= limit
15943 && (q2 - q1).abs() <= limit
15944 && (q3 - q2).abs() <= limit
15945 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
15946 let flat = (p1 - p0).abs() <= flat_thresh
15947 && (q1 - q0).abs() <= flat_thresh
15948 && (p2 - p0).abs() <= flat_thresh
15949 && (q2 - q0).abs() <= flat_thresh
15950 && (p3 - p0).abs() <= flat_thresh
15951 && (q3 - q0).abs() <= flat_thresh;
15952 let [op2, op1, op0, oq0, oq1, oq2] =
15953 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
15954 data[idx(-3)] = op2.clamp(0, sample_max()) as u16;
15955 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
15956 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
15957 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
15958 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
15959 data[idx(2)] = oq2.clamp(0, sample_max()) as u16;
15960 }
15961 _ => {
15962 let (p6, p5, p4, p3, p2, p1, p0) =
15963 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
15964 let (q0, q1, q2, q3, q4, q5, q6) =
15965 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
15966 let mask = (p3 - p2).abs() <= limit
15967 && (p2 - p1).abs() <= limit
15968 && (p1 - p0).abs() <= limit
15969 && (q1 - q0).abs() <= limit
15970 && (q2 - q1).abs() <= limit
15971 && (q3 - q2).abs() <= limit
15972 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
15973 let flat = (p1 - p0).abs() <= flat_thresh
15974 && (q1 - q0).abs() <= flat_thresh
15975 && (p2 - p0).abs() <= flat_thresh
15976 && (q2 - q0).abs() <= flat_thresh
15977 && (p3 - p0).abs() <= flat_thresh
15978 && (q3 - q0).abs() <= flat_thresh;
15979 let flat2 = (p4 - p0).abs() <= flat_thresh
15980 && (q4 - q0).abs() <= flat_thresh
15981 && (p5 - p0).abs() <= flat_thresh
15982 && (q5 - q0).abs() <= flat_thresh
15983 && (p6 - p0).abs() <= flat_thresh
15984 && (q6 - q0).abs() <= flat_thresh;
15985 let out = filter14(
15986 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
15987 q6,
15988 );
15989 for (k, v) in (-6..=5isize).zip(out) {
15990 data[idx(k)] = v.clamp(0, sample_max()) as u16;
15991 }
15992 }
15993 }
15994 }
15995}
15996
15997/// One plane's worth of spec 7.14: every vertical edge across the plane,
15998/// then every horizontal edge (the order the spec and libaom both use).
15999fn deblock_plane(
16000 plane: &mut PlaneBuf,
16001 plane_idx: usize,
16002 lf: &LoopFilterParams,
16003 n: &Neighbours,
16004 frame_width: usize,
16005 frame_height: usize,
16006) {
16007 let chroma = plane_idx != 0;
16008 // r7: libaom clips the deblock loop to the CODED frame's own
16009 // width/height, not the mi-aligned `true_width`/`true_height` margin
16010 // (the padding up to the next 8-pixel/superblock boundary that
16011 // reconstruction still fills in but the loop filter never visits).
16012 // Confirmed against the superres gate: with the margin included, the
16013 // last coded mi column's horizontal edges were filtered when libaom's
16014 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
16015 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
16016 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
16017 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
16018 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
16019 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
16020 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
16021 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
16022 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
16023 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
16024 // all in columns 64..67; frame 0 survived because that edge carried no
16025 // filter level there). r7's superres measurement is preserved: its frame
16026 // was already 8-aligned, so this bound equals `frame_width` there and
16027 // still excludes the superblock padding up to `true_width`.
16028 let (cw, ch) = if chroma {
16029 (frame_width.div_ceil(2), frame_height.div_ceil(2))
16030 } else {
16031 (frame_width, frame_height)
16032 };
16033 let (tw, th, stride) = (
16034 plane.true_width.min(cw),
16035 plane.true_height.min(ch),
16036 plane.width,
16037 );
16038 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
16039 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
16040 }
16041 let mut y0 = 0usize;
16042 while y0 < th {
16043 let mut x0 = 4usize;
16044 while x0 < tw {
16045 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
16046 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
16047 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
16048 }
16049 filter_edge(
16050 &mut plane.data,
16051 y0 * stride + x0,
16052 stride as isize,
16053 1,
16054 len,
16055 level,
16056 lf.sharpness,
16057 );
16058 }
16059 x0 += 4;
16060 }
16061 y0 += 4;
16062 }
16063 let mut x0 = 0usize;
16064 while x0 < tw {
16065 let mut y0 = 4usize;
16066 while y0 < th {
16067 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
16068 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
16069 && plane_idx == 0
16070 && x0 == 44
16071 {
16072 eprintln!(
16073 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
16074 lf.sharpness
16075 );
16076 }
16077 filter_edge(
16078 &mut plane.data,
16079 y0 * stride + x0,
16080 1,
16081 stride as isize,
16082 len,
16083 level,
16084 lf.sharpness,
16085 );
16086 }
16087 y0 += 4;
16088 }
16089 x0 += 4;
16090 }
16091}
16092
16093fn apply_cdef(
16094 y: &mut PlaneBuf,
16095 u: &mut PlaneBuf,
16096 v: &mut PlaneBuf,
16097 cdef: &CdefParams,
16098 skip_grid: &Neighbours,
16099 // This frame header's own CROPPED luma size, for the straddling-unit
16100 // counter only -- CDEF itself walks the mi-rounded plane.
16101 (frame_w, frame_h): (usize, usize),
16102) {
16103 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
16104 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
16105 return;
16106 }
16107 // lane-cdefstrip r1 instrument, BEFORE either early return so it is valid
16108 // for every frame: an 8x8 CDEF unit none of whose four mi cells a coded
16109 // block wrote this frame. `Neighbours` seeds `skip_grid` all-false, so a
16110 // decode arm that forgets `fill_skip_grid_rect` reads "not skip" and CDEF
16111 // filters a unit libaom's `is_8x8_block_skip` (`cdef.c:29-38`) may exclude.
16112 // Always 0 on every stream measured; a gate asserts it stays 0.
16113 {
16114 let mut r = 0usize;
16115 while r < skip_grid.mi_rows {
16116 let mut c = 0usize;
16117 while c < skip_grid.mi_cols {
16118 if (0..2).any(|rr| {
16119 (0..2).any(|cc| {
16120 !skip_grid
16121 .skip_written
16122 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
16123 .copied()
16124 .unwrap_or(true)
16125 })
16126 }) {
16127 CDEF_UNWRITTEN_SKIP_UNITS.with(|c2| c2.set(c2.get() + 1));
16128 if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") {
16129 eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4);
16130 }
16131 }
16132 let cell = |rr: usize, cc: usize| {
16133 skip_grid
16134 .skip_grid
16135 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
16136 .copied()
16137 .unwrap_or(false)
16138 };
16139 let first = cell(0, 0);
16140 if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) {
16141 CDEF_MIXED_SKIP_UNITS.with(|c2| c2.set(c2.get() + 1));
16142 }
16143 c += 2;
16144 }
16145 r += 2;
16146 }
16147 }
16148 // `cdef.bits == 0` still means "no filtering at all" whenever the single
16149 // (index 0) strength pair is all-zero -- the fast path every existing
16150 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
16151 // at every index, but that is rare enough not to special-case; the
16152 // per-superblock lookup below degrades to the same index-0 read anyway
16153 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
16154 if cdef.bits == 0
16155 && cdef.y_pri_strength[0] == 0
16156 && cdef.y_sec_strength[0] == 0
16157 && cdef.uv_pri_strength[0] == 0
16158 && cdef.uv_sec_strength[0] == 0
16159 {
16160 return;
16161 }
16162 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
16163 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
16164 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
16165 if sb_cols == 0 {
16166 return 0;
16167 }
16168 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
16169 idx_grid
16170 .get(sb_r * sb_cols + sb_c)
16171 .copied()
16172 .unwrap_or(0) as usize
16173 };
16174 let src_y = y.data.clone();
16175 let src_u = u.data.clone();
16176 let src_v = v.data.clone();
16177 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
16178 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
16179 let coeff_shift = i32::from(bit_depth()) - 8;
16180 let damping = i32::from(cdef.damping) + coeff_shift;
16181 let damping_uv = (damping - 1).max(0);
16182 let mut mi_r = 0usize;
16183 while mi_r < skip_grid.mi_rows {
16184 let mut mi_c = 0usize;
16185 while mi_c < skip_grid.mi_cols {
16186 if skip_grid.is_skip_txfm(mi_r, mi_c) {
16187 CDEF_SKIPPED_UNITS.with(|c| c.set(c.get() + 1));
16188 }
16189 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
16190 let sidx = strength_idx(mi_r, mi_c);
16191 let (ox, oy) = (mi_c * 4, mi_r * 4);
16192 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
16193 let sample_y = |r: i32, c: i32| -> i32 {
16194 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
16195 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
16196 CDEF_VERY_LARGE
16197 } else {
16198 i32::from(src_y[ny as usize * y_stride + nx as usize])
16199 }
16200 };
16201 // lane-cdef r1: the direction search reads the SAME padded
16202 // block the taps do -- libaom runs `cdef_find_dir` on the
16203 // prepared filter block (`cdef_block.c:296-320` over
16204 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
16205 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
16206 // Clamping to the last real sample instead made every straddling
16207 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
16208 // a different `adjust_strength`, hence a +-1 band at the crop edge.
16209 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| sample_y(r as i32, c as i32));
16210
16211 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
16212 // -- each plane zeroes the shared direction when *its own*
16213 // frame-level primary strength is 0, independent of the
16214 // per-block adjusted `t` and of the other plane's strength.
16215 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
16216 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
16217 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
16218 let t = cdef_adjust_strength(y_pri_strength, var);
16219 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
16220 if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") {
16221 eprintln!(
16222 "EC_CDEF mi_r={mi_r} mi_c={mi_c} x={ox} y={oy} sidx={sidx} dir={dir} var={var} t={t} pri={y_pri_strength} sec={y_sec_strength} damp={damping}"
16223 );
16224 }
16225 let enable_primary = t != 0;
16226 let enable_secondary = y_sec_strength != 0;
16227 if (ox + 8 > frame_w || oy + 8 > frame_h)
16228 && (enable_primary
16229 || enable_secondary
16230 || cdef.uv_pri_strength[sidx] != 0
16231 || cdef.uv_sec_strength[sidx] != 0)
16232 {
16233 CDEF_STRADDLE_UNITS.with(|c| c.set(c.get() + 1));
16234 }
16235 if enable_primary || enable_secondary {
16236 cdef_filter_block(
16237 sample_y,
16238 y,
16239 ox,
16240 oy,
16241 8,
16242 8,
16243 t,
16244 y_sec_strength,
16245 y_dir,
16246 damping,
16247 damping,
16248 enable_primary,
16249 enable_secondary,
16250 coeff_shift,
16251 );
16252 }
16253
16254 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
16255 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
16256 let uv_dir = if t_uv != 0 { dir } else { 0 };
16257 let enable_primary_uv = t_uv != 0;
16258 let enable_secondary_uv = uv_sec_strength != 0;
16259 if enable_primary_uv || enable_secondary_uv {
16260 let (cox, coy) = (ox / 2, oy / 2);
16261 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
16262 let (tw, th) = (plane.true_width, plane.true_height);
16263 let stride = plane.width;
16264 let sample_uv = |r: i32, c: i32| -> i32 {
16265 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
16266 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
16267 CDEF_VERY_LARGE
16268 } else {
16269 i32::from(src_p[ny as usize * stride + nx as usize])
16270 }
16271 };
16272 cdef_filter_block(
16273 sample_uv,
16274 plane,
16275 cox,
16276 coy,
16277 4,
16278 4,
16279 t_uv,
16280 uv_sec_strength,
16281 uv_dir,
16282 damping_uv,
16283 damping_uv,
16284 enable_primary_uv,
16285 enable_secondary_uv,
16286 coeff_shift,
16287 );
16288 }
16289 }
16290 }
16291 mi_c += 2;
16292 }
16293 mi_r += 2;
16294 }
16295}
16296
16297/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
16298/// ordering note: libaom also runs `superres_post_decode` between the two,
16299/// but this decoder never implements super-resolution, so there is nothing
16300/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
16301/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
16302/// restoration's stripe-boundary rows read from it instead of the
16303/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
16304#[allow(clippy::too_many_arguments)]
16305fn apply_loop_restoration(
16306 y: &mut PlaneBuf,
16307 u: &mut PlaneBuf,
16308 v: &mut PlaneBuf,
16309 deblocked_y: &PlaneBuf,
16310 deblocked_u: &PlaneBuf,
16311 deblocked_v: &PlaneBuf,
16312 lr: &LoopRestorationParams,
16313 grid: &crate::restoration::RestorationGrid,
16314 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
16315 // restoration is the ONE post-decode filter that does NOT run over the
16316 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
16317 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
16318 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
16319 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
16320 // -- and asserts it equals the buffer's CROP width
16321 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
16322 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
16323 // that cropped edge before any unit is filtered. Deblock and CDEF DO
16324 // walk the mi grid, which is why passing `true_width`/`true_height`
16325 // here went unnoticed until a frame whose size is not a multiple of 8
16326 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
16327 // read this decoder's own decoded samples at columns 68..71 where
16328 // libaom reads column 67 replicated -- +-1 over the straddling band
16329 // (class av1-truesize-lane: true frame size vs mi-rounded).
16330 (frame_w, frame_h): (usize, usize),
16331) {
16332 y.data = crate::restoration::apply_loop_restoration_plane(
16333 &y.data,
16334 &deblocked_y.data,
16335 y.width,
16336 frame_w,
16337 frame_h,
16338 0,
16339 lr.frame_restoration_type[0],
16340 lr.loop_restoration_size[0],
16341 grid,
16342 0,
16343 );
16344 u.data = crate::restoration::apply_loop_restoration_plane(
16345 &u.data,
16346 &deblocked_u.data,
16347 u.width,
16348 frame_w.div_ceil(2),
16349 frame_h.div_ceil(2),
16350 1,
16351 lr.frame_restoration_type[1],
16352 lr.loop_restoration_size[1],
16353 grid,
16354 1,
16355 );
16356 v.data = crate::restoration::apply_loop_restoration_plane(
16357 &v.data,
16358 &deblocked_v.data,
16359 v.width,
16360 frame_w.div_ceil(2),
16361 frame_h.div_ceil(2),
16362 1,
16363 lr.frame_restoration_type[2],
16364 lr.loop_restoration_size[2],
16365 grid,
16366 2,
16367 );
16368}
16369
16370/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
16371/// returning the picture it reconstructs to.
16372///
16373/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
16374/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
16375/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
16376/// `compute_image_size` derives one from the other, but not losslessly: a
16377/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
16378/// what the reconstruction is cropped to on the way out, mirroring
16379/// [`crate::encode::crop_encoded`].
16380///
16381/// # Errors
16382/// Returns an error when a block's partition, mode, skip flag or transform
16383/// type is anything this decoder does not reconstruct (round 2: inter, tx
16384/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
16385/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
16386/// or when the tile payload runs out of the symbols this decode expects (a
16387/// genuinely foreign stream).
16388pub fn decode_key_frame_tile(
16389 data: &[u8],
16390 mi_cols: u32,
16391 mi_rows: u32,
16392 base_q_idx: u8,
16393 frame_width: u32,
16394 frame_height: u32,
16395 enable_filter_intra: bool,
16396 cdef: &CdefParams,
16397 loop_filter: &LoopFilterParams,
16398 tx_select: bool,
16399 reduced_tx_set: bool,
16400 allow_screen_content_tools: bool,
16401 allow_intrabc: bool,
16402) -> Result<Picture> {
16403 let delta = DeltaParams::default();
16404 let single_tile = TileInfo {
16405 mi_col_starts: vec![0, mi_cols],
16406 mi_row_starts: vec![0, mi_rows],
16407 ..TileInfo::default()
16408 };
16409 decode_key_frame_tile_with_cdfs(
16410 &[data],
16411 &single_tile,
16412 mi_cols,
16413 mi_rows,
16414 base_q_idx,
16415 crate::quant::QuantDeltas::default(),
16416 frame_width,
16417 frame_height,
16418 enable_filter_intra,
16419 false,
16420 cdef,
16421 loop_filter,
16422 &LoopRestorationParams::default(),
16423 None,
16424 tx_select,
16425 reduced_tx_set,
16426 allow_screen_content_tools,
16427 allow_intrabc,
16428 delta,
16429 )
16430 .map(|(picture, _)| picture)
16431}
16432
16433thread_local! {
16434 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
16435 /// the mi-aligned `true_width`, set by the most recent
16436 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
16437 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
16438 /// their reconstructed buffer down from the same mi-aligned extent, so
16439 /// they share this one slot. See each function's own comment at its
16440 /// write site. `None` when there was no margin to save.
16441 static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
16442 const { std::cell::RefCell::new(None) };
16443}
16444
16445/// The margin the most recent key- or inter-frame tile decode stashed
16446/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
16447/// reads this immediately after the call, before any other frame
16448/// decode can overwrite it.
16449pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
16450 LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
16451}
16452
16453/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
16454/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
16455/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
16456/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
16457/// since a key frame's own header always forces `primary_ref_frame ==
16458/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
16459/// alongside the picture, for the caller to save into whichever reference
16460/// slots this frame's `refresh_frame_flags` names.
16461/// The order the 64x64 superblock quadrants of a tile are decoded in.
16462///
16463/// At `sb_size == 64` this is plain raster order over the tile's own
16464/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
16465/// each 128x128 superblock in raster order and visits its four 64x64
16466/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
16467/// 64-level bodies must run in that nested order. `row_start` marks the first
16468/// item of each *superblock* row (where the left neighbour context resets),
16469/// `sb_start` the first item of each superblock (where the 128 root's own
16470/// loop-restoration units and partition symbol are read).
16471fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
16472 let mut out = Vec::new();
16473 if !sb128 {
16474 for r in r0..r1 {
16475 for c in c0..c1 {
16476 out.push((r, c, c == c0, true));
16477 }
16478 }
16479 return out;
16480 }
16481 let mut r = r0;
16482 while r < r1 {
16483 let mut first_in_row = true;
16484 let mut c = c0;
16485 while c < c1 {
16486 let mut first_in_sb = true;
16487 for qr in 0..2 {
16488 for qc in 0..2 {
16489 let (rr, cc) = (r + qr, c + qc);
16490 if rr >= r1 || cc >= c1 {
16491 continue;
16492 }
16493 out.push((rr, cc, first_in_row, first_in_sb));
16494 first_in_row = false;
16495 first_in_sb = false;
16496 }
16497 }
16498 c += 2;
16499 }
16500 r += 2;
16501 }
16502 out
16503}
16504
16505/// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
16506/// the inter tile loop. Its loop-restoration units are read once for the whole
16507/// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
16508/// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
16509/// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
16510/// decoder codes, the other seven arms refuse by name.
16511#[allow(clippy::too_many_arguments)]
16512thread_local! {
16513 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
16514 /// whole 128x128 block (lane-sb128b r1's gate counter).
16515 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16516 /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one
16517 /// when the bottom half is out of frame) -- lane-sb128c r7.
16518 pub(crate) static PART128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16519 /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces).
16520 pub(crate) static PART128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16521 /// Of those, the ones decided by the GATHERED bit at a frame edge -- the
16522 /// only shape a 1080p (mi_rows = 270) stream reaches.
16523 pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16524 pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16525 /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes,
16526 /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order.
16527 pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
16528}
16529
16530/// [`PART128_AB_HITS`], for a gate's own before/after delta.
16531pub(crate) fn part128_ab_hits() -> [usize; 4] {
16532 PART128_AB_HITS.with(std::cell::Cell::get)
16533}
16534
16535/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
16536pub(crate) fn part128_none_hits() -> usize {
16537 PART128_NONE_HITS.with(std::cell::Cell::get)
16538}
16539
16540/// [`PART128_HORZ_HITS`], for a gate's own before/after delta.
16541pub(crate) fn part128_horz_hits() -> usize {
16542 PART128_HORZ_HITS.with(std::cell::Cell::get)
16543}
16544
16545/// [`PART128_VERT_HITS`], for a gate's own before/after delta.
16546pub(crate) fn part128_vert_hits() -> usize {
16547 PART128_VERT_HITS.with(std::cell::Cell::get)
16548}
16549
16550/// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge.
16551pub(crate) fn part128_edge_horz_hits() -> usize {
16552 PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get)
16553}
16554
16555/// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge.
16556pub(crate) fn part128_edge_vert_hits() -> usize {
16557 PART128_EDGE_VERT_HITS.with(std::cell::Cell::get)
16558}
16559
16560thread_local! {
16561 /// How many CHROMA transform units were coded inside a block whose uv
16562 /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128
16563 /// block, four per plane).
16564 pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16565}
16566
16567/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta.
16568pub(crate) fn chroma_split_tx_hits() -> usize {
16569 CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get)
16570}
16571
16572fn read_sb128_root(
16573 dec: &mut SymbolDecoder,
16574 cdfs: &mut Cdfs,
16575 neighbours: &Neighbours,
16576 lr: &LoopRestorationParams,
16577 lr_grid: &mut crate::restoration::RestorationGrid,
16578 lr_reference: &mut [(
16579 crate::restoration::WienerInfo,
16580 crate::restoration::SgrprojInfo,
16581 ); 3],
16582 sb_r: u32,
16583 sb_c: u32,
16584 mi_cols: u32,
16585 mi_rows: u32,
16586) -> Result<usize> {
16587 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
16588 crate::restoration::read_lr(
16589 dec,
16590 cdfs,
16591 lr,
16592 lr_grid,
16593 lr_reference,
16594 mi_r128,
16595 mi_c128,
16596 SB_MI * 2,
16597 );
16598 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
16599 let ctx128 = neighbours.partition_ctx(at128, 128);
16600 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
16601 let part128 = if has_cols128 && has_rows128 {
16602 PART128_SYMBOLS.with(|c| c.set(c.get() + 1));
16603 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
16604 if crate::envflags::env_flag!("EC_AV1_TRACE") {
16605 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
16606 }
16607 p
16608 } else {
16609 // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the
16610 // partition, they are not a forced split -- exactly the discarded-bit
16611 // defect the 64 root carries a comment about at `partition_w64`'s
16612 // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or
16613 // VERT (cols out of frame), which the refusal below then names
16614 // instead of silently reconstructing a split.
16615 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() + 1));
16616 match (has_cols128, has_rows128) {
16617 (true, false) => {
16618 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 {
16619 PARTITION_SPLIT
16620 } else {
16621 PART128_EDGE_HORZ_HITS.with(|c| c.set(c.get() + 1));
16622 PARTITION_HORZ
16623 }
16624 }
16625 (false, true) => {
16626 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 {
16627 PARTITION_SPLIT
16628 } else {
16629 PART128_EDGE_VERT_HITS.with(|c| c.set(c.get() + 1));
16630 PARTITION_VERT
16631 }
16632 }
16633 _ => {
16634 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
16635 bump_edge_both_cut(3);
16636 PARTITION_SPLIT
16637 }
16638 }
16639 };
16640 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
16641 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
16642 // four AB shapes) still need the rect/AB machinery at this size.
16643 // lane-sb128c r7: HORZ (two 128x64) and VERT (two 64x128) now decode on
16644 // both tile paths. The four AB shapes (libaom `decode_partition`'s
16645 // PARTITION_HORZ_A..VERT_B, decodeframe.c) still need the mixed
16646 // 128x64 + 64x64 + 64x64 visit order and stay refused by name; a 128
16647 // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded
16648 // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet,
16649 // which stops at VERT_B).
16650 match part128 {
16651 PARTITION_SPLIT => PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1)),
16652 PARTITION_NONE => PART128_NONE_HITS.with(|c| c.set(c.get() + 1)),
16653 PARTITION_HORZ => PART128_HORZ_HITS.with(|c| c.set(c.get() + 1)),
16654 PARTITION_VERT => PART128_VERT_HITS.with(|c| c.set(c.get() + 1)),
16655 // lane-sb128c r9: the four AB shapes at the 128 root -- one
16656 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
16657 // paths below in libaom `decode_partition`'s own visit order.
16658 p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {
16659 PART128_AB_HITS.with(|c| {
16660 let mut h = c.get();
16661 h[p - PARTITION_HORZ_A] += 1;
16662 c.set(h);
16663 });
16664 }
16665 _ => {
16666 return Err(unsupported(
16667 "a 128x128 superblock partition value outside the 8-symbol alphabet",
16668 ));
16669 }
16670 }
16671 Ok(part128)
16672}
16673
16674pub(crate) fn decode_key_frame_tile_with_cdfs(
16675 tiles: &[&[u8]],
16676 tile_info: &TileInfo,
16677 mi_cols: u32,
16678 mi_rows: u32,
16679 base_q_idx: u8,
16680 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
16681 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
16682 // tile alongside [`CURRENT_Q_IDX`].
16683 deltas: crate::quant::QuantDeltas,
16684 frame_width: u32,
16685 frame_height: u32,
16686 enable_filter_intra: bool,
16687 enable_edge_filter: bool,
16688 cdef: &CdefParams,
16689 loop_filter: &LoopFilterParams,
16690 lr: &LoopRestorationParams,
16691 initial_cdfs: Option<Cdfs>,
16692 tx_select: bool,
16693 reduced_tx_set: bool,
16694 allow_screen_content_tools: bool,
16695 allow_intrabc: bool,
16696 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
16697 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
16698 // `stream.rs` still refuses a frame with `lf_present` set before this
16699 // function is ever called.
16700 delta: DeltaParams,
16701) -> Result<(Picture, Cdfs)> {
16702 // lane-frame80: [`TX_SELECT_INTER`] is set by the INTER tile decoder
16703 // only, so a key frame decoded after an inter frame on this thread would
16704 // otherwise inherit it and read its `tx_depth` context off the inter
16705 // frame's stale `TXFM_CONTEXT` bands.
16706 TX_SELECT_INTER.with(|c| c.set(false));
16707 if mi_cols == 0 || mi_rows == 0 {
16708 return Err(unsupported("a frame with no mode-info grid"));
16709 }
16710 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
16711 let sb128 = sb128();
16712 if sb128 && allow_intrabc {
16713 return Err(unsupported(
16714 "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)",
16715 ));
16716 }
16717 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
16718 INTRABC_MI_GRID.with(|g| {
16719 *g.borrow_mut() = allow_intrabc.then(|| {
16720 (
16721 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
16722 mi_cols as usize,
16723 mi_rows as usize,
16724 )
16725 });
16726 });
16727 INTRABC_DV.with(|c| c.set(None));
16728 CDEF_BITS.with(|c| c.set(cdef.bits));
16729 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
16730 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
16731 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
16732 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
16733 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
16734 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
16735 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
16736 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
16737 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
16738 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
16739
16740 let mut y = PlaneBuf {
16741 data: vec![0u16; width * height],
16742 width,
16743 height,
16744 true_width,
16745 true_height,
16746 tile_x0: 0,
16747 tile_y0: 0,
16748 tile_x1: width,
16749 tile_y1: height,
16750 };
16751 let mut u = PlaneBuf {
16752 data: vec![0u16; width * height / 4],
16753 width: width / 2,
16754 height: height / 2,
16755 true_width: true_width / 2,
16756 true_height: true_height / 2,
16757 tile_x0: 0,
16758 tile_y0: 0,
16759 tile_x1: width / 2,
16760 tile_y1: height / 2,
16761 };
16762 let mut v = PlaneBuf {
16763 data: vec![0u16; width * height / 4],
16764 width: width / 2,
16765 height: height / 2,
16766 true_width: true_width / 2,
16767 true_height: true_height / 2,
16768 tile_x0: 0,
16769 tile_y0: 0,
16770 tile_x1: width / 2,
16771 tile_y1: height / 2,
16772 };
16773
16774 let scan32 = default_scan(TX32);
16775 let scan16 = default_scan(TX16);
16776 let scan8 = default_scan(TX8);
16777 let scan4 = default_scan(TX4);
16778
16779 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
16780 let mut result_cdfs = base_cdfs.clone();
16781 let mut neighbours = Neighbours::new(
16782 cols32 as usize * 2,
16783 rows32 as usize * 2,
16784 mi_cols as usize,
16785 mi_rows as usize,
16786 );
16787 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
16788
16789 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
16790 // own byte range and its own fresh copy of the frame's initial CDFs
16791 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
16792 // `context_update_tile_id` has its end-of-tile adapted table kept as the
16793 // frame's own output (spec `exit_symbol`) -- every other tile's
16794 // adaptation is discarded, matching the refusal this replaces.
16795 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
16796 let tile_num = tile_idx as u32;
16797 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
16798 let mi_row0 = tile_info.mi_row_starts[trow as usize];
16799 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
16800 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
16801 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
16802 // Tile boundaries are always superblock-aligned in mi units (spec
16803 // 5.9.15's uniform/non-uniform derivation both only ever emit
16804 // multiples of the superblock's own mi size), so plain division is
16805 // exact here -- no rounding needed.
16806 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
16807 // tile boundary) are always superblock-aligned by spec 5.9.15; the
16808 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
16809 // last entry) is not, so the upper bound needs `div_ceil` the same
16810 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
16811 // trailing partial superblock row/column in scope.
16812 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
16813 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
16814
16815 // lane-t900 r19: spec 5.11.2 `decode_tile` resets `RefLrWiener` /
16816 // `RefSgrXqd` to the midpoint filter at the top of EVERY tile, not
16817 // once per frame. Carried across a tile boundary, the loop-restoration
16818 // coefficients of the next tile decode off the previous tile's
16819 // reference -- same symbol count, so entropy and reconstruction stay
16820 // exact and only the filtered pixels of every tile after the first
16821 // are wrong.
16822 let mut lr_reference = [(
16823 crate::restoration::WienerInfo::default(),
16824 crate::restoration::SgrprojInfo::default(),
16825 ); 3];
16826 let mut cdfs = base_cdfs.clone();
16827 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
16828 // `base_q_idx` at the top of every tile, not once per frame.
16829 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
16830 QUANT_DELTAS.with(|c| c.set(deltas));
16831 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
16832 if crate::envflags::env_flag!("EC_AV1_TRACE") {
16833 eprintln!(
16834 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
16835 tile_bytes.len(),
16836 &tile_bytes[..tile_bytes.len().min(8)]
16837 );
16838 }
16839 let mut dec = SymbolDecoder::new(tile_bytes);
16840 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
16841 y.set_tile_origin(
16842 mi_col0 as usize * 4,
16843 mi_row0 as usize * 4,
16844 (mi_col1 as usize * 4).min(y.width),
16845 (mi_row1 as usize * 4).min(y.height),
16846 );
16847 u.set_tile_origin(
16848 mi_col0 as usize * 2,
16849 mi_row0 as usize * 2,
16850 (mi_col1 as usize * 2).min(u.width),
16851 (mi_row1 as usize * 2).min(u.height),
16852 );
16853 v.set_tile_origin(
16854 mi_col0 as usize * 2,
16855 mi_row0 as usize * 2,
16856 (mi_col1 as usize * 2).min(v.width),
16857 (mi_row1 as usize * 2).min(v.height),
16858 );
16859 TILE_HITS.with(|c| c.set(c.get() + 1));
16860
16861 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
16862 // its one block covers all four 64x64 quadrants, so the remaining three
16863 // visits of this superblock code nothing at all.
16864 let mut sb128_none = false;
16865 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
16866 if row_start {
16867 neighbours.start_row();
16868 }
16869 if sb_start {
16870 sb128_none = false;
16871 }
16872 if sb128_none {
16873 continue;
16874 }
16875 {
16876 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
16877 // once for the whole 128x128 (spec 5.11.57 is called with the
16878 // superblock's own size), then one partition symbol off the
16879 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
16880 // recurses into the four 64x64 quadrants this decoder codes.
16881 if sb128 && sb_start {
16882 let part128 = read_sb128_root(
16883 &mut dec,
16884 &mut cdfs,
16885 &neighbours,
16886 lr,
16887 &mut lr_grid,
16888 &mut lr_reference,
16889 sb_r,
16890 sb_c,
16891 mi_cols,
16892 mi_rows,
16893 )?;
16894 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) {
16895 // lane-sb128c r9: the four AB shapes at the 128 root.
16896 // libaom `decode_partition` (decodeframe.c) codes each as
16897 // two `bsize2` (64x64) squares plus one `subsize`
16898 // (128x64 / 64x128) half, visited HORZ_A = TL, TR, bottom
16899 // half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right
16900 // half; VERT_B = left half, TR, BR. AB values only come
16901 // from the FULL alphabet symbol, which is only read when
16902 // both halves of the root are inside the frame, so no
16903 // piece needs libaom's `i > 0` frame-edge break (a piece
16904 // may still overhang the bottom/right, which
16905 // `PlaneBuf::reconstruct`'s r8 clip handles).
16906 sb128_none = true;
16907 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
16908 let (br, bc) = (at128.0 + 4, at128.1 + 4);
16909 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
16910 // Only the VERTICAL arms reorder the squares (TL, BL, TR,
16911 // BR), so only they switch libaom's `has_tr_vert_*` /
16912 // `has_bl_vert_*` tables (lane-sb128c r6 visit order).
16913 let _vert_ab =
16914 (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B)
16915 .then(crate::encode::Reach::vert_ab_partition);
16916 // One `cdef_idx` literal per CODED BLOCK, at the first
16917 // non-skip one of each 64x64 CDEF unit; the 128x64 /
16918 // 64x128 half covers two units and its read lands in the
16919 // unit holding its origin, so that value is copied to the
16920 // other one (libaom: every mi of the block points at the
16921 // same `MB_MODE_INFO`).
16922 let cdef_copy = |src: (usize, usize), dst: (usize, usize)| {
16923 CDEF_IDX_GRID.with(|g| {
16924 let mut g = g.borrow_mut();
16925 let cols = CDEF_SB_COLS.with(|c| c.get());
16926 if cols == 0 {
16927 return;
16928 }
16929 let (si, di) = (
16930 (q_r + src.0) * cols + q_c + src.1,
16931 (q_r + dst.0) * cols + q_c + dst.1,
16932 );
16933 if q_c + src.1 < cols
16934 && q_c + dst.1 < cols
16935 && si < g.len()
16936 && di < g.len()
16937 {
16938 g[di] = g[si];
16939 }
16940 });
16941 };
16942 macro_rules! square64 {
16943 ($at:expr) => {{
16944 CDEF_TRANSMITTED.with(|c| c.set(false));
16945 decode_block(
16946 &mut dec,
16947 &mut cdfs,
16948 &mut neighbours,
16949 $at,
16950 SB,
16951 TxbSet::Luma64,
16952 TxbSet::Chroma32,
16953 TX32,
16954 TX32,
16955 (&scan32, &scan32),
16956 false,
16957 &mut y,
16958 &mut u,
16959 &mut v,
16960 base_q_idx,
16961 enable_filter_intra,
16962 allow_screen_content_tools,
16963 allow_intrabc,
16964 &scan32,
16965 &scan16,
16966 &scan8,
16967 &scan4,
16968 tx_select,
16969 reduced_tx_set,
16970 )?
16971 }};
16972 }
16973 macro_rules! half128 {
16974 ($at:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{
16975 CDEF_TRANSMITTED.with(|c| c.set(false));
16976 decode_block_128rect(
16977 &mut dec,
16978 &mut cdfs,
16979 &mut neighbours,
16980 $at,
16981 $bw,
16982 $bh,
16983 &mut y,
16984 &mut u,
16985 &mut v,
16986 base_q_idx,
16987 enable_filter_intra,
16988 allow_screen_content_tools,
16989 tx_select,
16990 reduced_tx_set,
16991 )?;
16992 cdef_copy($src, $dst);
16993 }};
16994 }
16995 match part128 {
16996 PARTITION_HORZ_A => {
16997 square64!(at128);
16998 square64!((at128.0, bc));
16999 half128!((br, at128.1), 128, 64, (1, 0), (1, 1));
17000 }
17001 PARTITION_HORZ_B => {
17002 half128!(at128, 128, 64, (0, 0), (0, 1));
17003 square64!((br, at128.1));
17004 square64!((br, bc));
17005 }
17006 PARTITION_VERT_A => {
17007 square64!(at128);
17008 square64!((br, at128.1));
17009 half128!((at128.0, bc), 64, 128, (0, 1), (1, 1));
17010 }
17011 _ => {
17012 half128!(at128, 64, 128, (0, 0), (1, 0));
17013 square64!((at128.0, bc));
17014 square64!((br, bc));
17015 }
17016 }
17017 continue;
17018 }
17019 if matches!(part128, PARTITION_HORZ | PARTITION_VERT) {
17020 // lane-sb128c r8: libaom `decode_partition`
17021 // (decodeframe.c:1554) codes PARTITION_HORZ at the 128
17022 // root as `subsize = BLOCK_128X64` at (mi_row, mi_col)
17023 // plus a second one at (mi_row + hbs, mi_col) only
17024 // `if (mi_row + hbs < mi_rows)`; PARTITION_VERT mirrors it
17025 // on the column. `hbs` is `mi_size_high[BLOCK_128X128]/2`
17026 // = 16 mi. Both halves together cover the whole root, so
17027 // the remaining three 64x64 quadrant visits code nothing
17028 // (same flag the NONE arm sets).
17029 sb128_none = true;
17030 let horz = part128 == PARTITION_HORZ;
17031 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
17032 let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) };
17033 for i in 0..2 {
17034 let at = if horz {
17035 (at128.0 + i * 4, at128.1)
17036 } else {
17037 (at128.0, at128.1 + i * 4)
17038 };
17039 let (blk_mi_r, blk_mi_c) = (at.0 * (SUB / MI), at.1 * (SUB / MI));
17040 if i > 0
17041 && (blk_mi_r >= mi_rows as usize || blk_mi_c >= mi_cols as usize)
17042 {
17043 break;
17044 }
17045 // Each half reads its OWN `cdef_idx` literal
17046 // (libaom `read_cdef` keys the `-1` test on the
17047 // block's own `MB_MODE_INFO`, and the two halves have
17048 // different ones).
17049 CDEF_TRANSMITTED.with(|c| c.set(false));
17050 decode_block_128rect(
17051 &mut dec,
17052 &mut cdfs,
17053 &mut neighbours,
17054 at,
17055 bw,
17056 bh,
17057 &mut y,
17058 &mut u,
17059 &mut v,
17060 base_q_idx,
17061 enable_filter_intra,
17062 allow_screen_content_tools,
17063 tx_select,
17064 reduced_tx_set,
17065 )?;
17066 }
17067 // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF
17068 // unit it covers (the inter path's own fan-out).
17069 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
17070 CDEF_IDX_GRID.with(|g| {
17071 let mut g = g.borrow_mut();
17072 let cols = CDEF_SB_COLS.with(|c| c.get());
17073 if cols == 0 {
17074 return;
17075 }
17076 for (src, dst) in if horz {
17077 [((0, 0), (0, 1)), ((1, 0), (1, 1))]
17078 } else {
17079 [((0, 0), (1, 0)), ((0, 1), (1, 1))]
17080 } {
17081 let (si, di) = (
17082 (q_r + src.0) * cols + q_c + src.1,
17083 (q_r + dst.0) * cols + q_c + dst.1,
17084 );
17085 if q_c + src.1 < cols
17086 && q_c + dst.1 < cols
17087 && si < g.len()
17088 && di < g.len()
17089 {
17090 g[di] = g[si];
17091 }
17092 }
17093 });
17094 continue;
17095 }
17096 if part128 == PARTITION_NONE {
17097 // One 128x128 intra block: four TX_64X64 luma units and a
17098 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
17099 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
17100 // block). No CfL, no filter intra, no palette at this size --
17101 // [`read_intra_mode`]'s own size gates already say so.
17102 sb128_none = true;
17103 CDEF_TRANSMITTED.with(|c| c.set(false));
17104 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
17105 decode_block(
17106 &mut dec,
17107 &mut cdfs,
17108 &mut neighbours,
17109 at128,
17110 SB * 2,
17111 TxbSet::Luma64,
17112 TxbSet::Chroma32,
17113 TX32,
17114 TX32,
17115 (&scan32, &scan32),
17116 false,
17117 &mut y,
17118 &mut u,
17119 &mut v,
17120 base_q_idx,
17121 enable_filter_intra,
17122 allow_screen_content_tools,
17123 allow_intrabc,
17124 &scan32,
17125 &scan16,
17126 &scan8,
17127 &scan4,
17128 tx_select,
17129 reduced_tx_set,
17130 )?;
17131 // libaom writes one `cdef_strength` into the block's own
17132 // `MB_MODE_INFO`, which every mi cell of the block --
17133 // hence all four 64x64 CDEF units -- points at; our grid
17134 // is per-unit, so the read (which only ever lands in the
17135 // top-left unit, `read_cdef`'s index 0) is copied across.
17136 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
17137 CDEF_IDX_GRID.with(|g| {
17138 let mut g = g.borrow_mut();
17139 let cols = CDEF_SB_COLS.with(|c| c.get());
17140 if cols > 0 && q_r * cols + q_c < g.len() {
17141 let idx = g[q_r * cols + q_c];
17142 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
17143 let i = (q_r + dr) * cols + q_c + dc;
17144 if q_c + dc < cols && i < g.len() {
17145 g[i] = idx;
17146 }
17147 }
17148 }
17149 });
17150 continue;
17151 }
17152 }
17153 if !sb128 {
17154 crate::restoration::read_lr(
17155 &mut dec,
17156 &mut cdfs,
17157 lr,
17158 &mut lr_grid,
17159 &mut lr_reference,
17160 sb_r * SB_MI,
17161 sb_c * SB_MI,
17162 SB_MI,
17163 );
17164 }
17165 CDEF_TRANSMITTED.with(|c| c.set(false));
17166 let at = (sb_r as usize * 4, sb_c as usize * 4);
17167 let ctx = neighbours.partition_ctx(at, SB);
17168 let (has_cols, has_rows) = (
17169 sb_c * SB_MI + SB_MI / 2 < mi_cols,
17170 sb_r * SB_MI + SB_MI / 2 < mi_rows,
17171 );
17172 // Recomputed at this superblock's own half (spec
17173 // `decode_partition`): a full alphabet symbol when both halves are
17174 // inside the true frame, a single gathered bit when just one is
17175 // (the superblock cannot be left whole, so this is forced split),
17176 // and nothing at all (SPLIT inferred, no bits) when neither is —
17177 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
17178 // three-way write exactly.
17179 let part = if has_cols && has_rows {
17180 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
17181 if crate::envflags::env_flag!("EC_AV1_TRACE") {
17182 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
17183 }
17184 p
17185 } else {
17186 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
17187 // the unmerged lane-golomb r1): the gathered bit IS the
17188 // partition -- libaom `ec_read_partition_impl` returns
17189 // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1.
17190 // Forcing SPLIT desynced the last superblock row of every
17191 // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0,
17192 // the first block of that row.
17193 match (has_cols, has_rows) {
17194 (true, false) => {
17195 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
17196 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
17197 bump_edge32(4 + b.min(1) as usize);
17198 bump_edge_part(b.min(1) as usize);
17199 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
17200 }
17201 (false, true) => {
17202 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
17203 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
17204 bump_edge32(4 + b.min(1) as usize);
17205 bump_edge_part(b.min(1) as usize);
17206 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
17207 }
17208 _ => {
17209 bump_edge_both_cut(2);
17210 PARTITION_SPLIT
17211 }
17212 }
17213 };
17214 match part {
17215 PARTITION_NONE => {
17216 decode_block(
17217 &mut dec,
17218 &mut cdfs,
17219 &mut neighbours,
17220 at,
17221 SB,
17222 TxbSet::Luma64,
17223 TxbSet::Chroma32,
17224 TX32,
17225 TX32,
17226 (&scan32, &scan32),
17227 false,
17228 &mut y,
17229 &mut u,
17230 &mut v,
17231 base_q_idx,
17232 enable_filter_intra,
17233 allow_screen_content_tools,
17234 allow_intrabc,
17235 &scan32,
17236 &scan16,
17237 &scan8,
17238 &scan4,
17239 tx_select,
17240 reduced_tx_set,
17241 )?;
17242 }
17243 PARTITION_SPLIT => {
17244 for q in 0..4 {
17245 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
17246 if r32 >= rows32 || c32 >= cols32 {
17247 continue;
17248 }
17249 let at32 = (r32 as usize * 2, c32 as usize * 2);
17250 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
17251 let (has_cols32, has_rows32) = (
17252 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
17253 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
17254 );
17255 let part32 = if has_cols32 && has_rows32 {
17256 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
17257 if crate::envflags::env_flag!("EC_AV1_TRACE") {
17258 let (rng, _) = dec.debug_state();
17259 eprintln!(
17260 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
17261 r32 * BLOCK_MI,
17262 c32 * BLOCK_MI
17263 );
17264 }
17265 p
17266 } else {
17267 // lane-hgkf r1: the 32-level frame-edge bit is the
17268 // partition too (same libaom reader as the
17269 // superblock level above).
17270 match (has_cols32, has_rows32) {
17271 (true, false) => {
17272 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
17273 let b = dec.symbol_fixed(&gather(
17274 &cdfs.partition_w32[ctx32],
17275 VERT_ALIKE,
17276 ));
17277 bump_edge32(b.min(1) as usize);
17278 bump_edge_part(2 + b.min(1) as usize);
17279 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
17280 }
17281 (false, true) => {
17282 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
17283 let b = dec.symbol_fixed(&gather(
17284 &cdfs.partition_w32[ctx32],
17285 HORZ_ALIKE,
17286 ));
17287 bump_edge32(b.min(1) as usize);
17288 bump_edge_part(2 + b.min(1) as usize);
17289 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
17290 }
17291 _ => {
17292 bump_edge_both_cut(1);
17293 PARTITION_SPLIT
17294 }
17295 }
17296 };
17297 match part32 {
17298 PARTITION_NONE => {
17299 decode_block(
17300 &mut dec,
17301 &mut cdfs,
17302 &mut neighbours,
17303 at32,
17304 BLOCK,
17305 TxbSet::Luma32,
17306 TxbSet::Chroma16,
17307 TX32,
17308 TX16,
17309 (&scan32, &scan16),
17310 true,
17311 &mut y,
17312 &mut u,
17313 &mut v,
17314 base_q_idx,
17315 enable_filter_intra,
17316 allow_screen_content_tools,
17317 allow_intrabc,
17318 &scan32,
17319 &scan16,
17320 &scan8,
17321 &scan4,
17322 tx_select,
17323 reduced_tx_set,
17324 )?;
17325 }
17326 PARTITION_SPLIT => {
17327 for sub in 0..4 {
17328 let (sr, sc) =
17329 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
17330 if (sr as u32) * SUB_MI >= mi_rows
17331 || (sc as u32) * SUB_MI >= mi_cols
17332 {
17333 continue;
17334 }
17335 let (has_cols16, has_rows16) = (
17336 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
17337 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
17338 );
17339 let at16 = (sr, sc);
17340 let ctx16 = neighbours.partition_ctx(at16, SUB);
17341 if has_cols16 && has_rows16 {
17342 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
17343 if crate::envflags::env_flag!("EC_AV1_TRACE") {
17344 eprintln!(
17345 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
17346 at16.0, at16.1
17347 );
17348 }
17349 if part16 == PARTITION_NONE {
17350 decode_block(
17351 &mut dec,
17352 &mut cdfs,
17353 &mut neighbours,
17354 at16,
17355 SUB,
17356 TxbSet::Luma16,
17357 TxbSet::Chroma8,
17358 TX16,
17359 TX8,
17360 (&scan16, &scan8),
17361 true,
17362 &mut y,
17363 &mut u,
17364 &mut v,
17365 base_q_idx,
17366 enable_filter_intra,
17367 allow_screen_content_tools,
17368 allow_intrabc,
17369 &scan32,
17370 &scan16,
17371 &scan8,
17372 &scan4,
17373 tx_select,
17374 reduced_tx_set,
17375 )?;
17376 continue;
17377 }
17378 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
17379 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
17380 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
17381 // `decode_partition` visit order (decodeframe.c):
17382 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
17383 // HORZ_B: top 16x8, BL 8x8, BR 8x8
17384 // VERT_A: TL 8x8, BL 8x8, right 8x16
17385 // VERT_B: left 8x16, TR 8x8, BR 8x8
17386 // The squares go through `decode_leaf8`, the strip through
17387 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
17388 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
17389 // used refuses the non-skip case at this size). Both writers keep
17390 // mi-granular mode/skip/palette records, so a later block's
17391 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
17392 // 16x16 cell.
17393 //
17394 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
17395 // top-right neighbour is the partition's own not-yet-decoded
17396 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
17397 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
17398 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
17399 let arm = part16 - PARTITION_HORZ_A;
17400 bump_ab16(arm);
17401 if part16 == PARTITION_VERT_B {
17402 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
17403 }
17404 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
17405 Some(crate::encode::Reach::vert_ab_partition())
17406 } else {
17407 None
17408 };
17409 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
17410 macro_rules! ab_leaf8 {
17411 ($mi:expr, $prev:expr) => {
17412 decode_leaf8(
17413 &mut dec,
17414 &mut cdfs,
17415 &mut neighbours,
17416 at16,
17417 $mi,
17418 (&scan8, &scan4),
17419 $prev,
17420 &mut y,
17421 &mut u,
17422 &mut v,
17423 base_q_idx,
17424 enable_filter_intra,
17425 allow_screen_content_tools,
17426 allow_intrabc,
17427 tx_select,
17428 reduced_tx_set,
17429 )?
17430 };
17431 }
17432 macro_rules! ab_strip {
17433 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
17434 decode_leaf_rect(
17435 &mut dec,
17436 &mut cdfs,
17437 &mut neighbours,
17438 at16,
17439 $mi,
17440 $bw,
17441 $bh,
17442 $prev,
17443 &mut y,
17444 &mut u,
17445 &mut v,
17446 enable_filter_intra,
17447 allow_screen_content_tools,
17448 base_q_idx,
17449 tx_select,
17450 reduced_tx_set,
17451 )?
17452 };
17453 }
17454 let tl = (mi_row0, mi_col0);
17455 let tr = (mi_row0, mi_col0 + 2);
17456 let bl = (mi_row0 + 2, mi_col0);
17457 let br = (mi_row0 + 2, mi_col0 + 2);
17458 let mut done: Vec<((usize, usize), usize)> = Vec::new();
17459 match part16 {
17460 PARTITION_HORZ_A => {
17461 let m_tl = ab_leaf8!(tl, done.last().copied());
17462 done.push((tl, m_tl));
17463 let m_tr = ab_leaf8!(tr, done.last().copied());
17464 done.push((tr, m_tr));
17465 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
17466 done.push((bl, m_bot));
17467 }
17468 PARTITION_HORZ_B => {
17469 let m_top = ab_strip!(tl, 16, 8, None);
17470 done.push((tl, m_top));
17471 let m_bl = ab_leaf8!(bl, done.last().copied());
17472 done.push((bl, m_bl));
17473 let m_br = ab_leaf8!(br, done.last().copied());
17474 done.push((br, m_br));
17475 }
17476 PARTITION_VERT_A => {
17477 let m_tl = ab_leaf8!(tl, done.last().copied());
17478 done.push((tl, m_tl));
17479 let m_bl = ab_leaf8!(bl, done.last().copied());
17480 done.push((bl, m_bl));
17481 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
17482 done.push((tr, m_right));
17483 }
17484 _ => {
17485 let m_left = ab_strip!(tl, 8, 16, None);
17486 done.push((tl, m_left));
17487 let m_tr = ab_leaf8!(tr, done.last().copied());
17488 done.push((tr, m_tr));
17489 let m_br = ab_leaf8!(br, done.last().copied());
17490 done.push((br, m_br));
17491 }
17492 }
17493 // Same coarse-slot write-back the real SPLIT path takes: the
17494 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
17495 // sub-block on the parent's bottom / right edge (the mi-exact map
17496 // above wins wherever it has an entry).
17497 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
17498 continue;
17499 }
17500 if part16 == PARTITION_HORZ {
17501 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
17502 let (mi_row0, mi_col0) = (
17503 sr as u32 * SUB_MI,
17504 sc as u32 * SUB_MI,
17505 );
17506 let top = (mi_row0 as usize, mi_col0 as usize);
17507 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
17508 let mode_top = decode_leaf_rect(
17509 &mut dec,
17510 &mut cdfs,
17511 &mut neighbours,
17512 at16,
17513 top,
17514 16,
17515 8,
17516 None,
17517 &mut y,
17518 &mut u,
17519 &mut v,
17520 enable_filter_intra,
17521 allow_screen_content_tools,
17522 base_q_idx,
17523 tx_select,
17524 reduced_tx_set,
17525 )?;
17526 let mode_bot = decode_leaf_rect(
17527 &mut dec,
17528 &mut cdfs,
17529 &mut neighbours,
17530 at16,
17531 bot,
17532 16,
17533 8,
17534 Some((top, mode_top)),
17535 &mut y,
17536 &mut u,
17537 &mut v,
17538 enable_filter_intra,
17539 allow_screen_content_tools,
17540 base_q_idx,
17541 tx_select,
17542 reduced_tx_set,
17543 )?;
17544 neighbours.above_mode[sc] = mode_bot;
17545 neighbours.left_mode[sr] = mode_bot;
17546 continue;
17547 }
17548 if part16 == PARTITION_VERT {
17549 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
17550 let (mi_row0, mi_col0) = (
17551 sr as u32 * SUB_MI,
17552 sc as u32 * SUB_MI,
17553 );
17554 let left = (mi_row0 as usize, mi_col0 as usize);
17555 let right = (mi_row0 as usize, mi_col0 as usize + 2);
17556 let mode_left = decode_leaf_rect(
17557 &mut dec,
17558 &mut cdfs,
17559 &mut neighbours,
17560 at16,
17561 left,
17562 8,
17563 16,
17564 None,
17565 &mut y,
17566 &mut u,
17567 &mut v,
17568 enable_filter_intra,
17569 allow_screen_content_tools,
17570 base_q_idx,
17571 tx_select,
17572 reduced_tx_set,
17573 )?;
17574 let mode_right = decode_leaf_rect(
17575 &mut dec,
17576 &mut cdfs,
17577 &mut neighbours,
17578 at16,
17579 right,
17580 8,
17581 16,
17582 Some((left, mode_left)),
17583 &mut y,
17584 &mut u,
17585 &mut v,
17586 enable_filter_intra,
17587 allow_screen_content_tools,
17588 base_q_idx,
17589 tx_select,
17590 reduced_tx_set,
17591 )?;
17592 neighbours.above_mode[sc] = mode_right;
17593 neighbours.left_mode[sr] = mode_right;
17594 continue;
17595 }
17596 if part16 == PARTITION_HORZ_4
17597 || part16 == PARTITION_VERT_4
17598 {
17599 decode_rect4_16(
17600 &mut dec,
17601 &mut cdfs,
17602 &mut neighbours,
17603 at16,
17604 part16 == PARTITION_HORZ_4,
17605 &mut y,
17606 &mut u,
17607 &mut v,
17608 enable_filter_intra,
17609 allow_screen_content_tools,
17610 base_q_idx,
17611 tx_select,
17612 reduced_tx_set,
17613 )?;
17614 continue;
17615 }
17616 // lane-r14 r2 (verifier note): every
17617 // one of the 10 symbols this CDF can
17618 // produce is handled above, so SPLIT
17619 // is the only value that reaches
17620 // here -- the refusal that used to
17621 // stand here was unreachable and is
17622 // gone from `refusal_inventory`.
17623 debug_assert_eq!(part16, PARTITION_SPLIT);
17624 // A real (non-straddle) SPLIT of a
17625 // whole 16x16 into four 8x8 leaves --
17626 // the same recursion the straddle
17627 // path below already runs when the
17628 // true frame edge forces it, just
17629 // over all four positions instead of
17630 // the one or two the edge leaves.
17631 let (mi_row0, mi_col0) =
17632 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
17633 // Each 8x8 leaf's intra-mode context
17634 // must see its own siblings: the
17635 // bottom-left leaf's ABOVE neighbour
17636 // is leaf 0, not the previously
17637 // decoded leaf 1 (and the bottom-right
17638 // leaf's above is leaf 1, while
17639 // `prev_leaf` only ever carried the
17640 // immediately preceding one). The
17641 // coarse `above_mode`/`left_mode`
17642 // arrays hold one slot per 16x16, so
17643 // the sibling modes are swapped in
17644 // around each leaf call and restored
17645 // after; the loop tail writes the last
17646 // leaf's mode as before.
17647 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
17648 for i in 0..4 {
17649 let (mr, mc) =
17650 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
17651 let leaf_mi = (mr as usize, mc as usize);
17652 let li = i as usize;
17653 let saved_modes =
17654 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
17655 if li >= 2 {
17656 if let Some((below, _)) = sib_modes[li - 2] {
17657 neighbours.above_mode[sc] = below;
17658 }
17659 }
17660 if li % 2 == 1 {
17661 if let Some((_, right)) = sib_modes[li - 1] {
17662 neighbours.left_mode[sr] = right;
17663 }
17664 }
17665 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
17666 let part8 =
17667 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
17668 if crate::envflags::env_flag!("EC_AV1_TRACE") {
17669 eprintln!(
17670 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
17671 );
17672 }
17673 let leaf_mode = if part8 == PARTITION_NONE {
17674 decode_leaf8(
17675 &mut dec,
17676 &mut cdfs,
17677 &mut neighbours,
17678 at16,
17679 leaf_mi,
17680 (&scan8, &scan4),
17681 None,
17682 &mut y,
17683 &mut u,
17684 &mut v,
17685 base_q_idx,
17686 enable_filter_intra,
17687 allow_screen_content_tools,
17688 allow_intrabc,
17689 tx_select,
17690 reduced_tx_set,
17691 ).map(|m| (m, m))?
17692 } else if part8 == PARTITION_SPLIT {
17693 decode_leaf_split4(
17694 &mut dec,
17695 &mut cdfs,
17696 &mut neighbours,
17697 at16,
17698 leaf_mi,
17699 &scan4,
17700 None,
17701 &mut y,
17702 &mut u,
17703 &mut v,
17704 base_q_idx,
17705 enable_filter_intra,
17706 allow_intrabc,
17707 reduced_tx_set,
17708 )?
17709 } else if part8 == PARTITION_HORZ
17710 || part8 == PARTITION_VERT
17711 {
17712 decode_leaf_rect8(
17713 &mut dec,
17714 &mut cdfs,
17715 &mut neighbours,
17716 at16,
17717 leaf_mi,
17718 part8 == PARTITION_VERT,
17719 &scan4,
17720 &mut y,
17721 &mut u,
17722 &mut v,
17723 base_q_idx,
17724 enable_filter_intra,
17725 allow_intrabc,
17726 tx_select,
17727 reduced_tx_set,
17728 )?
17729 } else {
17730 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
17731 };
17732 neighbours.above_mode[sc] = saved_modes.0;
17733 neighbours.left_mode[sr] = saved_modes.1;
17734 sib_modes[li] = Some(leaf_mode);
17735 }
17736 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
17737 neighbours.above_mode[sc] = below;
17738 }
17739 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
17740 neighbours.left_mode[sr] = right;
17741 }
17742 continue;
17743 }
17744 // The true edge falls inside this 16x16
17745 // leaf itself (mod-32==8 target sizes,
17746 // lane-av1-rect): one axis only -- an 8x8
17747 // leaf never itself straddles, so the
17748 // block splits cleanly along whichever
17749 // axis is short.
17750 // lane-edgeboth r1: when the true frame
17751 // edge cuts BOTH axes libaom's
17752 // `decode_partition` takes
17753 // `else if (!has_rows && !has_cols)
17754 // partition = PARTITION_SPLIT;` -- no
17755 // symbol of any kind is read, and the four
17756 // 8x8 children are then visited by the
17757 // same loop below, whose
17758 // `mr < mi_rows && mc < mi_cols` filter IS
17759 // libaom's own
17760 // `if (mi_row >= mi_rows || mi_col >= mi_cols) return;`
17761 // early return, so the three out-of-frame
17762 // quadrants get no neighbour or tx-grid
17763 // write.
17764 if !has_cols16 && !has_rows16 {
17765 bump_edge_both_cut(0);
17766 } else {
17767 // lane-golomb r1 (class
17768 // `parsed-then-discarded`): the gathered
17769 // bit IS the partition -- 0 names
17770 // PARTITION_HORZ (resp. VERT), only 1 is
17771 // SPLIT (libaom `ec_read_partition_impl`).
17772 // This path can only walk the four SPLIT
17773 // leaves, so a 0 refuses by name instead
17774 // of desyncing.
17775 trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32);
17776 let edge_split = if has_cols16 {
17777 dec.symbol_fixed(&gather(
17778 &cdfs.partition_w16[ctx16],
17779 VERT_ALIKE,
17780 ))
17781 } else {
17782 dec.symbol_fixed(&gather(
17783 &cdfs.partition_w16[ctx16],
17784 HORZ_ALIKE,
17785 ))
17786 };
17787 // lane-hgkf r1: slots 2/3 of
17788 // [`EDGE_PART_HITS`], the gate's proof the
17789 // non-SPLIT edge arm actually decoded.
17790 bump_edge_part(if edge_split == 1 { 3 } else { 2 });
17791 if edge_split == 0 {
17792 // lane-oddh r1: the strip IS decodable
17793 // -- libaom's `decode_partition` codes
17794 // only the FIRST half of an edge
17795 // HORZ/VERT (the second call is
17796 // guarded by the same has_rows/
17797 // has_cols test that made the
17798 // partition non-square), so one
17799 // 16x8 (resp. 8x16) strip covers the
17800 // whole visible band of a frame whose
17801 // height (resp. width) is 8 mod 16 --
17802 // the user's 3840x1608 film.
17803 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
17804 EDGE_RECT_STRIP_HITS.with(|c| c.set(c.get() + 1));
17805 let (mi_row0, mi_col0) =
17806 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
17807 let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) };
17808 let mode = decode_leaf_rect(
17809 &mut dec,
17810 &mut cdfs,
17811 &mut neighbours,
17812 at16,
17813 (mi_row0 as usize, mi_col0 as usize),
17814 bw,
17815 bh,
17816 None,
17817 &mut y,
17818 &mut u,
17819 &mut v,
17820 enable_filter_intra,
17821 allow_screen_content_tools,
17822 base_q_idx,
17823 tx_select,
17824 reduced_tx_set,
17825 )?;
17826 neighbours.above_mode[sc] = mode;
17827 neighbours.left_mode[sr] = mode;
17828 continue;
17829 }
17830 }
17831 let (mi_row0, mi_col0) =
17832 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
17833 let leaf_positions: Vec<(u32, u32)> = (0..4)
17834 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
17835 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
17836 .collect();
17837 // See the sibling-mode note in the clean
17838 // SPLIT path above.
17839 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
17840 for (mr, mc) in leaf_positions {
17841 let leaf_mi = (mr as usize, mc as usize);
17842 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
17843 as usize;
17844 let saved_modes =
17845 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
17846 if li >= 2 {
17847 if let Some((below, _)) = sib_modes[li - 2] {
17848 neighbours.above_mode[sc] = below;
17849 }
17850 }
17851 if li % 2 == 1 {
17852 if let Some((_, right)) = sib_modes[li - 1] {
17853 neighbours.left_mode[sr] = right;
17854 }
17855 }
17856 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
17857 let pre8 = dec.debug_state().0;
17858 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
17859 if crate::envflags::env_flag!("EC_AV1_TRACE") {
17860 eprintln!(
17861 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
17862 );
17863 }
17864 let leaf_mode = if part8 == PARTITION_NONE {
17865 decode_leaf8(
17866 &mut dec,
17867 &mut cdfs,
17868 &mut neighbours,
17869 at16,
17870 leaf_mi,
17871 (&scan8, &scan4),
17872 None,
17873 &mut y,
17874 &mut u,
17875 &mut v,
17876 base_q_idx,
17877 enable_filter_intra,
17878 allow_screen_content_tools,
17879 allow_intrabc,
17880 tx_select,
17881 reduced_tx_set,
17882 ).map(|m| (m, m))?
17883 } else if part8 == PARTITION_SPLIT {
17884 decode_leaf_split4(
17885 &mut dec,
17886 &mut cdfs,
17887 &mut neighbours,
17888 at16,
17889 leaf_mi,
17890 &scan4,
17891 None,
17892 &mut y,
17893 &mut u,
17894 &mut v,
17895 base_q_idx,
17896 enable_filter_intra,
17897 allow_intrabc,
17898 reduced_tx_set,
17899 )?
17900 } else if part8 == PARTITION_HORZ
17901 || part8 == PARTITION_VERT
17902 {
17903 decode_leaf_rect8(
17904 &mut dec,
17905 &mut cdfs,
17906 &mut neighbours,
17907 at16,
17908 leaf_mi,
17909 part8 == PARTITION_VERT,
17910 &scan4,
17911 &mut y,
17912 &mut u,
17913 &mut v,
17914 base_q_idx,
17915 enable_filter_intra,
17916 allow_intrabc,
17917 tx_select,
17918 reduced_tx_set,
17919 )?
17920 } else {
17921 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
17922 };
17923 neighbours.above_mode[sc] = saved_modes.0;
17924 neighbours.left_mode[sr] = saved_modes.1;
17925 sib_modes[li] = Some(leaf_mode);
17926 }
17927 // `record()`'s `above_mode`/`left_mode`
17928 // write is a no-op at an 8x8 leaf's own
17929 // side, so force the write once the whole
17930 // 16x16 slot's leaves are done, from the
17931 // last leaf (mirrors the writer's r15
17932 // fix).
17933 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
17934 neighbours.above_mode[sc] = below;
17935 }
17936 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
17937 neighbours.left_mode[sr] = right;
17938 }
17939 }
17940 }
17941 PARTITION_HORZ => {
17942 // lane-intradisp r1: two true 32x16 strips.
17943 decode_block_rect(
17944 &mut dec,
17945 &mut cdfs,
17946 &mut neighbours,
17947 at32,
17948 32,
17949 16,
17950 &mut y,
17951 &mut u,
17952 &mut v,
17953 enable_filter_intra,
17954 allow_screen_content_tools,
17955 base_q_idx,
17956 tx_select,
17957 reduced_tx_set,
17958 )?;
17959 if !has_rows32 {
17960 bump_edge32(2);
17961 }
17962 // lane-hgkf r1: at the frame edge only the first half of the strip is
17963 // coded (libaom `decode_partition` guards the second half with the same
17964 // test that made this partition non-square).
17965 if has_rows32 {
17966 decode_block_rect(
17967 &mut dec,
17968 &mut cdfs,
17969 &mut neighbours,
17970 (at32.0 + 1, at32.1),
17971 32,
17972 16,
17973 &mut y,
17974 &mut u,
17975 &mut v,
17976 enable_filter_intra,
17977 allow_screen_content_tools,
17978 base_q_idx,
17979 tx_select,
17980 reduced_tx_set,
17981 )?;
17982 }
17983 }
17984 PARTITION_VERT => {
17985 // lane-intradisp r1: mirror of PARTITION_HORZ
17986 // above with width/height swapped.
17987 decode_block_rect(
17988 &mut dec,
17989 &mut cdfs,
17990 &mut neighbours,
17991 at32,
17992 16,
17993 32,
17994 &mut y,
17995 &mut u,
17996 &mut v,
17997 enable_filter_intra,
17998 allow_screen_content_tools,
17999 base_q_idx,
18000 tx_select,
18001 reduced_tx_set,
18002 )?;
18003 if !has_cols32 {
18004 bump_edge32(3);
18005 }
18006 // lane-hgkf r1: at the frame edge only the first half of the strip is
18007 // coded (libaom `decode_partition` guards the second half with the same
18008 // test that made this partition non-square).
18009 if has_cols32 {
18010 decode_block_rect(
18011 &mut dec,
18012 &mut cdfs,
18013 &mut neighbours,
18014 (at32.0, at32.1 + 1),
18015 16,
18016 32,
18017 &mut y,
18018 &mut u,
18019 &mut v,
18020 enable_filter_intra,
18021 allow_screen_content_tools,
18022 base_q_idx,
18023 tx_select,
18024 reduced_tx_set,
18025 )?;
18026 }
18027 }
18028 PARTITION_HORZ_A => {
18029 // lane-part32 r1: two 16x16 squares on top +
18030 // a true 32x16 strip below (mirrors
18031 // decode_inter_block's cd6cb6d HORZ_A: TL,
18032 // TR, bottom strip).
18033 INTRA_HORZ_A_HITS.with(|c| c.set(c.get() + 1));
18034 decode_block(
18035 &mut dec,
18036 &mut cdfs,
18037 &mut neighbours,
18038 at32,
18039 SUB,
18040 TxbSet::Luma16,
18041 TxbSet::Chroma8,
18042 TX16,
18043 TX8,
18044 (&scan16, &scan8),
18045 true,
18046 &mut y,
18047 &mut u,
18048 &mut v,
18049 base_q_idx,
18050 enable_filter_intra,
18051 allow_screen_content_tools,
18052 allow_intrabc,
18053 &scan32,
18054 &scan16,
18055 &scan8,
18056 &scan4,
18057 tx_select,
18058 reduced_tx_set,
18059 )?;
18060 decode_block(
18061 &mut dec,
18062 &mut cdfs,
18063 &mut neighbours,
18064 (at32.0, at32.1 + 1),
18065 SUB,
18066 TxbSet::Luma16,
18067 TxbSet::Chroma8,
18068 TX16,
18069 TX8,
18070 (&scan16, &scan8),
18071 true,
18072 &mut y,
18073 &mut u,
18074 &mut v,
18075 base_q_idx,
18076 enable_filter_intra,
18077 allow_screen_content_tools,
18078 allow_intrabc,
18079 &scan32,
18080 &scan16,
18081 &scan8,
18082 &scan4,
18083 tx_select,
18084 reduced_tx_set,
18085 )?;
18086 decode_block_rect(
18087 &mut dec,
18088 &mut cdfs,
18089 &mut neighbours,
18090 (at32.0 + 1, at32.1),
18091 32,
18092 16,
18093 &mut y,
18094 &mut u,
18095 &mut v,
18096 enable_filter_intra,
18097 allow_screen_content_tools,
18098 base_q_idx,
18099 tx_select,
18100 reduced_tx_set,
18101 )?;
18102 }
18103 PARTITION_HORZ_B => {
18104 // lane-part32 r1: a true 32x16 strip on top +
18105 // two 16x16 squares below (mirrors HORZ_A
18106 // with the strip/squares order flipped, same
18107 // shape as libaom decode_partition's HORZ_B).
18108 INTRA_HORZ_B_HITS.with(|c| c.set(c.get() + 1));
18109 decode_block_rect(
18110 &mut dec,
18111 &mut cdfs,
18112 &mut neighbours,
18113 at32,
18114 32,
18115 16,
18116 &mut y,
18117 &mut u,
18118 &mut v,
18119 enable_filter_intra,
18120 allow_screen_content_tools,
18121 base_q_idx,
18122 tx_select,
18123 reduced_tx_set,
18124 )?;
18125 decode_block(
18126 &mut dec,
18127 &mut cdfs,
18128 &mut neighbours,
18129 (at32.0 + 1, at32.1),
18130 SUB,
18131 TxbSet::Luma16,
18132 TxbSet::Chroma8,
18133 TX16,
18134 TX8,
18135 (&scan16, &scan8),
18136 true,
18137 &mut y,
18138 &mut u,
18139 &mut v,
18140 base_q_idx,
18141 enable_filter_intra,
18142 allow_screen_content_tools,
18143 allow_intrabc,
18144 &scan32,
18145 &scan16,
18146 &scan8,
18147 &scan4,
18148 tx_select,
18149 reduced_tx_set,
18150 )?;
18151 decode_block(
18152 &mut dec,
18153 &mut cdfs,
18154 &mut neighbours,
18155 (at32.0 + 1, at32.1 + 1),
18156 SUB,
18157 TxbSet::Luma16,
18158 TxbSet::Chroma8,
18159 TX16,
18160 TX8,
18161 (&scan16, &scan8),
18162 true,
18163 &mut y,
18164 &mut u,
18165 &mut v,
18166 base_q_idx,
18167 enable_filter_intra,
18168 allow_screen_content_tools,
18169 allow_intrabc,
18170 &scan32,
18171 &scan16,
18172 &scan8,
18173 &scan4,
18174 tx_select,
18175 reduced_tx_set,
18176 )?;
18177 }
18178 PARTITION_VERT_A => {
18179 // lane-part32 r1: mirror of HORZ_A with
18180 // width/height swapped (TL, BL, right 16x32
18181 // strip).
18182 INTRA_VERT_A_HITS.with(|c| c.set(c.get() + 1));
18183 let _vert_ab = crate::encode::Reach::vert_ab_partition();
18184 decode_block(
18185 &mut dec,
18186 &mut cdfs,
18187 &mut neighbours,
18188 at32,
18189 SUB,
18190 TxbSet::Luma16,
18191 TxbSet::Chroma8,
18192 TX16,
18193 TX8,
18194 (&scan16, &scan8),
18195 true,
18196 &mut y,
18197 &mut u,
18198 &mut v,
18199 base_q_idx,
18200 enable_filter_intra,
18201 allow_screen_content_tools,
18202 allow_intrabc,
18203 &scan32,
18204 &scan16,
18205 &scan8,
18206 &scan4,
18207 tx_select,
18208 reduced_tx_set,
18209 )?;
18210 decode_block(
18211 &mut dec,
18212 &mut cdfs,
18213 &mut neighbours,
18214 (at32.0 + 1, at32.1),
18215 SUB,
18216 TxbSet::Luma16,
18217 TxbSet::Chroma8,
18218 TX16,
18219 TX8,
18220 (&scan16, &scan8),
18221 true,
18222 &mut y,
18223 &mut u,
18224 &mut v,
18225 base_q_idx,
18226 enable_filter_intra,
18227 allow_screen_content_tools,
18228 allow_intrabc,
18229 &scan32,
18230 &scan16,
18231 &scan8,
18232 &scan4,
18233 tx_select,
18234 reduced_tx_set,
18235 )?;
18236 decode_block_rect(
18237 &mut dec,
18238 &mut cdfs,
18239 &mut neighbours,
18240 (at32.0, at32.1 + 1),
18241 16,
18242 32,
18243 &mut y,
18244 &mut u,
18245 &mut v,
18246 enable_filter_intra,
18247 allow_screen_content_tools,
18248 base_q_idx,
18249 tx_select,
18250 reduced_tx_set,
18251 )?;
18252 }
18253 PARTITION_VERT_B => {
18254 // lane-part32 r1: a true 16x32 strip on the
18255 // left + two 16x16 squares on the right
18256 // (libaom decode_partition VERT_B: left
18257 // strip, TR, BR).
18258 INTRA_VERT_B_HITS.with(|c| c.set(c.get() + 1));
18259 let _vert_ab = crate::encode::Reach::vert_ab_partition();
18260 decode_block_rect(
18261 &mut dec,
18262 &mut cdfs,
18263 &mut neighbours,
18264 at32,
18265 16,
18266 32,
18267 &mut y,
18268 &mut u,
18269 &mut v,
18270 enable_filter_intra,
18271 allow_screen_content_tools,
18272 base_q_idx,
18273 tx_select,
18274 reduced_tx_set,
18275 )?;
18276 decode_block(
18277 &mut dec,
18278 &mut cdfs,
18279 &mut neighbours,
18280 (at32.0, at32.1 + 1),
18281 SUB,
18282 TxbSet::Luma16,
18283 TxbSet::Chroma8,
18284 TX16,
18285 TX8,
18286 (&scan16, &scan8),
18287 true,
18288 &mut y,
18289 &mut u,
18290 &mut v,
18291 base_q_idx,
18292 enable_filter_intra,
18293 allow_screen_content_tools,
18294 allow_intrabc,
18295 &scan32,
18296 &scan16,
18297 &scan8,
18298 &scan4,
18299 tx_select,
18300 reduced_tx_set,
18301 )?;
18302 decode_block(
18303 &mut dec,
18304 &mut cdfs,
18305 &mut neighbours,
18306 (at32.0 + 1, at32.1 + 1),
18307 SUB,
18308 TxbSet::Luma16,
18309 TxbSet::Chroma8,
18310 TX16,
18311 TX8,
18312 (&scan16, &scan8),
18313 true,
18314 &mut y,
18315 &mut u,
18316 &mut v,
18317 base_q_idx,
18318 enable_filter_intra,
18319 allow_screen_content_tools,
18320 allow_intrabc,
18321 &scan32,
18322 &scan16,
18323 &scan8,
18324 &scan4,
18325 tx_select,
18326 reduced_tx_set,
18327 )?;
18328 }
18329 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
18330 // lane-tx64x16 r3: the 1:4 pair at the 32x32
18331 // level -- four 32x8 (or 8x32) strips in
18332 // raster order, `quarter_step` = 2 mi, with
18333 // libaom `decode_partition`'s own `i > 0`
18334 // frame-edge break.
18335 let horz = part32 == PARTITION_HORZ_4;
18336 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
18337 let mut prev: Option<((usize, usize), usize)> = None;
18338 for i in 0..4 {
18339 let strip_mi = if horz {
18340 (base_mi.0 + i * 2, base_mi.1)
18341 } else {
18342 (base_mi.0, base_mi.1 + i * 2)
18343 };
18344 if i > 0
18345 && (strip_mi.0 >= mi_rows as usize
18346 || strip_mi.1 >= mi_cols as usize)
18347 {
18348 break;
18349 }
18350 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
18351 let (mode, _uv) = decode_block_rect4(
18352 &mut dec,
18353 &mut cdfs,
18354 &mut neighbours,
18355 strip_mi,
18356 bw,
18357 bh,
18358 prev,
18359 &mut y,
18360 &mut u,
18361 &mut v,
18362 enable_filter_intra,
18363 allow_screen_content_tools,
18364 base_q_idx,
18365 tx_select,
18366 )?;
18367 prev = Some((strip_mi, mode));
18368 }
18369 }
18370 _ => {
18371 return Err(unsupported(format!(
18372 "a 32x32 partition type this decoder does not code (value={part32})"
18373 )));
18374 }
18375 }
18376 }
18377 }
18378 PARTITION_HORZ => {
18379 // lane-sbpart r2: two true 64x32 strips.
18380 decode_block_rect64(
18381 &mut dec,
18382 &mut cdfs,
18383 &mut neighbours,
18384 at,
18385 64,
18386 32,
18387 &mut y,
18388 &mut u,
18389 &mut v,
18390 enable_filter_intra,
18391 allow_screen_content_tools,
18392 base_q_idx,
18393 tx_select,
18394 reduced_tx_set,
18395 )?;
18396 if !has_rows {
18397 bump_edge32(6);
18398 }
18399 // lane-golomb r1: at the frame edge only the first half of the
18400 // strip is coded (libaom `decode_partition` guards the second
18401 // with the same has_rows test that made this partition non-square).
18402 if has_rows {
18403 decode_block_rect64(
18404 &mut dec,
18405 &mut cdfs,
18406 &mut neighbours,
18407 (at.0 + 2, at.1),
18408 64,
18409 32,
18410 &mut y,
18411 &mut u,
18412 &mut v,
18413 enable_filter_intra,
18414 allow_screen_content_tools,
18415 base_q_idx,
18416 tx_select,
18417 reduced_tx_set,
18418 )?;
18419 }
18420 }
18421 PARTITION_VERT => {
18422 // lane-sbpart r2: mirror of PARTITION_HORZ above with
18423 // width/height swapped.
18424 decode_block_rect64(
18425 &mut dec,
18426 &mut cdfs,
18427 &mut neighbours,
18428 at,
18429 32,
18430 64,
18431 &mut y,
18432 &mut u,
18433 &mut v,
18434 enable_filter_intra,
18435 allow_screen_content_tools,
18436 base_q_idx,
18437 tx_select,
18438 reduced_tx_set,
18439 )?;
18440 if !has_cols {
18441 bump_edge32(7);
18442 }
18443 // lane-golomb r1: at the frame edge only the first half of the
18444 // strip is coded (libaom `decode_partition` guards the second
18445 // with the same has_cols test that made this partition non-square).
18446 if has_cols {
18447 decode_block_rect64(
18448 &mut dec,
18449 &mut cdfs,
18450 &mut neighbours,
18451 (at.0, at.1 + 2),
18452 32,
18453 64,
18454 &mut y,
18455 &mut u,
18456 &mut v,
18457 enable_filter_intra,
18458 allow_screen_content_tools,
18459 base_q_idx,
18460 tx_select,
18461 reduced_tx_set,
18462 )?;
18463 }
18464 }
18465 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
18466 // lane-part32 r4: the four superblock-level AB arms, each
18467 // two 32x32 squares plus one 64x32/32x64 strip, in
18468 // libaom's own `decode_partition` order (decodeframe.c:
18469 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
18470 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
18471 // TR, BR). The pieces are exactly the ones already proven
18472 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
18473 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
18474 SB_AB_HITS.with(|c| {
18475 let mut h = c.get();
18476 h[part - PARTITION_HORZ_A] += 1;
18477 c.set(h);
18478 });
18479 // lane-part32 r5: only the two VERTICAL arms reorder the
18480 // square sub-blocks (TL, BL, TR, BR), so only they switch
18481 // libaom's `has_tr`/`has_bl` tables.
18482 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
18483 .then(crate::encode::Reach::vert_ab_partition);
18484 macro_rules! square32 {
18485 ($at:expr) => {
18486 decode_block(
18487 &mut dec,
18488 &mut cdfs,
18489 &mut neighbours,
18490 $at,
18491 BLOCK,
18492 TxbSet::Luma32,
18493 TxbSet::Chroma16,
18494 TX32,
18495 TX16,
18496 (&scan32, &scan16),
18497 true,
18498 &mut y,
18499 &mut u,
18500 &mut v,
18501 base_q_idx,
18502 enable_filter_intra,
18503 allow_screen_content_tools,
18504 allow_intrabc,
18505 &scan32,
18506 &scan16,
18507 &scan8,
18508 &scan4,
18509 tx_select,
18510 reduced_tx_set,
18511 )?
18512 };
18513 }
18514 macro_rules! strip64 {
18515 ($at:expr, $bw:expr, $bh:expr) => {
18516 decode_block_rect64(
18517 &mut dec,
18518 &mut cdfs,
18519 &mut neighbours,
18520 $at,
18521 $bw,
18522 $bh,
18523 &mut y,
18524 &mut u,
18525 &mut v,
18526 enable_filter_intra,
18527 allow_screen_content_tools,
18528 base_q_idx,
18529 tx_select,
18530 reduced_tx_set,
18531 )?
18532 };
18533 }
18534 let (br, bc) = (at.0 + 2, at.1 + 2);
18535 match part {
18536 PARTITION_HORZ_A => {
18537 square32!(at);
18538 square32!((at.0, bc));
18539 strip64!((br, at.1), 64, 32);
18540 }
18541 PARTITION_HORZ_B => {
18542 strip64!(at, 64, 32);
18543 square32!((br, at.1));
18544 square32!((br, bc));
18545 }
18546 PARTITION_VERT_A => {
18547 square32!(at);
18548 square32!((br, at.1));
18549 strip64!((at.0, bc), 32, 64);
18550 }
18551 _ => {
18552 strip64!(at, 32, 64);
18553 square32!((at.0, bc));
18554 square32!((br, bc));
18555 }
18556 }
18557 }
18558 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
18559 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
18560 // 16x64) strips in raster order. `decode_partition`
18561 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
18562 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
18563 // frame edge for `i > 0`, so a partial superblock codes
18564 // only the strips whose origin is inside the frame.
18565 let horz = part == PARTITION_HORZ_4;
18566 for i in 0..4 {
18567 let step_mi = i * (SB_MI as usize / 4);
18568 let (this_r_mi, this_c_mi) = if horz {
18569 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
18570 } else {
18571 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
18572 };
18573 if i > 0
18574 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
18575 {
18576 break;
18577 }
18578 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
18579 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
18580 decode_block_rect64(
18581 &mut dec,
18582 &mut cdfs,
18583 &mut neighbours,
18584 strip_at,
18585 bw,
18586 bh,
18587 &mut y,
18588 &mut u,
18589 &mut v,
18590 enable_filter_intra,
18591 allow_screen_content_tools,
18592 base_q_idx,
18593 tx_select,
18594 reduced_tx_set,
18595 )?;
18596 }
18597 }
18598 _ => {
18599 return Err(unsupported(
18600 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
18601 ));
18602 }
18603 }
18604 }
18605 }
18606
18607 if tile_num == tile_info.context_update_tile_id {
18608 result_cdfs = cdfs;
18609 }
18610 }
18611
18612 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
18613 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
18614 // that isolate whether a decode-order frame's mismatch already exists
18615 // in reconstruction (this dump) vs is introduced by the loop filter
18616 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
18617 // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders.
18618 if crate::envflags::env_flag!("EC_OBMC")
18619 || crate::envflags::env_flag!("EC_TRACE_MODE")
18620 || crate::envflags::env_flag!("EC_PRED")
18621 {
18622 eprintln!(
18623 "EC_PICT idx={}",
18624 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst)
18625 );
18626 }
18627 dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
18628 if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") {
18629 use std::io::Write;
18630 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
18631 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
18632 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
18633 let _ = f.write_all(&narrow(&y));
18634 let _ = f.write_all(&narrow(&u));
18635 let _ = f.write_all(&narrow(&v));
18636 }
18637 } else {
18638 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
18639 }
18640 if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") {
18641 use std::io::Write;
18642 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18643 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
18644 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
18645 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
18646 for row in 0..plane.true_height {
18647 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
18648 }
18649 out
18650 };
18651 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
18652 let _ = f.write_all(&crop_wide(&y));
18653 let _ = f.write_all(&crop_wide(&u));
18654 let _ = f.write_all(&crop_wide(&v));
18655 }
18656 }
18657 apply_deblock(
18658 &mut y,
18659 &mut u,
18660 &mut v,
18661 loop_filter,
18662 &neighbours,
18663 frame_width as usize,
18664 frame_height as usize,
18665 );
18666 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
18667 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
18668 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
18669 // dump above these bisect WHICH filter stage introduced a mismatch.
18670 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
18671 dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
18672 apply_cdef(
18673 &mut y,
18674 &mut u,
18675 &mut v,
18676 cdef,
18677 &neighbours,
18678 (frame_width as usize, frame_height as usize),
18679 );
18680 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
18681 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
18682 apply_loop_restoration(
18683 &mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid,
18684 (frame_width as usize, frame_height as usize),
18685 );
18686
18687 let (fw, fh) = (frame_width as usize, frame_height as usize);
18688 if fw == width && fh == height {
18689 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
18690 return Ok((
18691 Picture {
18692 width,
18693 height,
18694 y: y.data,
18695 u: u.data,
18696 v: v.data,
18697 },
18698 result_cdfs,
18699 ));
18700 }
18701 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
18702 let mut out = Vec::with_capacity(w * h);
18703 for row in 0..h {
18704 out.extend(plane.data[row * plane.width..][..w].iter().copied());
18705 }
18706 out
18707 };
18708 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
18709 // is the real reconstructed extent -- columns `[fw, true_width)` hold
18710 // genuine decoded samples (the last coding block straddles the frame
18711 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
18712 // libaom's superres upscale runs on that buffer's own border-extended
18713 // margin, so it reads those real columns, not a synthetic replicate of
18714 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
18715 // aomenc 43->64 stream pinned column-by-column against libaom's own
18716 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
18717 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
18718 // decoder used before was off by 1 at the columns the tap window
18719 // reaches into that real margin; `None` when there is no margin (this
18720 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
18721 // non-superres frame whose width just isn't 32-block aligned).
18722 LAST_FRAME_WIDE_MARGIN.with(|m| {
18723 *m.borrow_mut() = if true_width > fw || true_height > fh {
18724 let yc = crop(&y, true_width, true_height);
18725 if let Ok(path) = crate::envflags::var("EC_AV1_MARGIN_DUMP") {
18726 use std::io::Write;
18727 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18728 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
18729 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
18730 // corner-cut: this diagnostic dump stays 8-bit-narrowed
18731 // regardless of the stream's real bit depth (debug-only,
18732 // never read by a gate); widen if a >8-bit margin dump
18733 // is ever needed.
18734 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
18735 }
18736 }
18737 Some(Picture {
18738 width: true_width,
18739 height: true_height,
18740 y: yc,
18741 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
18742 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
18743 })
18744 } else {
18745 None
18746 }
18747 });
18748 Ok((
18749 Picture {
18750 width: fw,
18751 height: fh,
18752 y: crop(&y, fw, fh),
18753 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
18754 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
18755 },
18756 result_cdfs,
18757 ))
18758}
18759
18760/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
18761/// -- `above`/`left` are the neighbour's own resolved index for this
18762/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
18763/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
18764/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
18765/// block itself has a second reference) -- lane-av1idx: a stale "this
18766/// decoder never codes a compound reference" assumption baked this to
18767/// always-0, which desynced the CDF context bucket (not the decoded value
18768/// outright, hence small pixel deltas rather than a hard desync) the moment
18769/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
18770/// filter frame.
18771fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
18772 let base = dir * 8 + if is_compound { 4 } else { 0 };
18773 let term = if left == above {
18774 left
18775 } else if left == 3 {
18776 above
18777 } else if above == 3 {
18778 left
18779 } else {
18780 3
18781 };
18782 base + term as usize
18783}
18784
18785/// Resolves the interpolation filter kernel(s) an inter block's motion
18786/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
18787/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
18788/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
18789/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
18790/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
18791/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
18792/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
18793/// which forces `EIGHTTAP` without reading anything.
18794#[allow(clippy::too_many_arguments)]
18795fn resolve_interp_filter(
18796 dec: &mut SymbolDecoder,
18797 cdfs: &mut Cdfs,
18798 interp_fixed: Option<mc::InterpFilterKind>,
18799 enable_dual_filter: bool,
18800 force_regular: bool,
18801 above: [u8; 2],
18802 left: [u8; 2],
18803 is_compound: bool,
18804) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
18805 if let Some(kind) = interp_fixed {
18806 return (kind, kind, [3, 3]);
18807 }
18808 if force_regular {
18809 return (
18810 mc::InterpFilterKind::Regular,
18811 mc::InterpFilterKind::Regular,
18812 [0, 0],
18813 );
18814 }
18815 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
18816 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
18817 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
18818 // "horizontal then vertical" despite `predict_with_filters`' own
18819 // `h_kind`/`v_kind` argument order, which is why this function returns
18820 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
18821 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
18822 if crate::envflags::env_flag!("EC_AV1_IFDBG") {
18823 eprintln!(
18824 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
18825 &cdfs.switchable_interp[ctx0][..3]
18826 );
18827 }
18828 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
18829 let sym1 = if enable_dual_filter {
18830 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
18831 if crate::envflags::env_flag!("EC_AV1_IFDBG") {
18832 eprintln!(
18833 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
18834 &cdfs.switchable_interp[ctx1][..3]
18835 );
18836 }
18837 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
18838 } else {
18839 sym0
18840 };
18841 if enable_dual_filter && sym0 != sym1 {
18842 DUAL_FILTER_DIFF_HITS.with(|c| c.set(c.get() + 1));
18843 }
18844 if crate::envflags::env_flag!("EC_TRACE_MODE") {
18845 eprintln!(
18846 "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}",
18847 dec.debug_state().0
18848 );
18849 }
18850 (
18851 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
18852 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
18853 [sym0, sym1],
18854 )
18855}
18856
18857/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
18858/// duplicating [`crate::tile`]'s private copy of the same rule.
18859pub(crate) fn intra_inter_ctx(
18860 has_above: bool,
18861 has_left: bool,
18862 above_inter: bool,
18863 left_inter: bool,
18864) -> usize {
18865 match (has_above, has_left) {
18866 (true, true) => {
18867 let (above_intra, left_intra) = (!above_inter, !left_inter);
18868 if above_intra && left_intra {
18869 3
18870 } else {
18871 usize::from(above_intra || left_intra)
18872 }
18873 }
18874 (true, false) => 2 * usize::from(!above_inter),
18875 (false, true) => 2 * usize::from(!left_inter),
18876 (false, false) => 0,
18877 }
18878}
18879
18880/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
18881/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
18882/// bits start counting from.
18883fn mv_class_base(class: usize) -> i32 {
18884 if class == 0 { 0 } else { 2i32 << (class + 2) }
18885}
18886
18887/// One motion vector component's non-zero diff (spec 5.11.32
18888/// `read_mv_component`), the inverse of [`crate::tile`]'s private
18889/// `write_mv_component`.
18890fn read_mv_component(
18891 dec: &mut SymbolDecoder,
18892 c: &mut MvComponentCdfs,
18893 allow_high_precision_mv: bool,
18894 force_integer_mv: bool,
18895) -> i32 {
18896 let sign = dec.symbol(&mut c.sign);
18897 let class = dec.symbol(&mut c.class);
18898 let local = if class == 0 {
18899 let bit = dec.symbol(&mut c.class0_bit);
18900 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
18901 // forces integer motion vectors -- implicitly `3` (the top
18902 // fractional value) rather than read, else every symbol after it
18903 // in the tile desyncs by one read.
18904 let fr = if force_integer_mv {
18905 3
18906 } else {
18907 dec.symbol(&mut c.class0_fr[bit])
18908 };
18909 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
18910 // high-precision motion vectors, else implicitly 1 (the low bit
18911 // stays at half-pel precision) -- this crate's own writer always
18912 // leaves the flag off, but a foreign stream can set it per frame.
18913 let hp = if allow_high_precision_mv {
18914 dec.symbol(&mut c.class0_hp)
18915 } else {
18916 1
18917 };
18918 (bit << 3) | (fr << 1) | hp
18919 } else {
18920 let mut d = 0;
18921 for i in 0..class {
18922 d |= dec.symbol(&mut c.bit[i]) << i;
18923 }
18924 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
18925 // `mv_class0_fr` above.
18926 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
18927 let hp = if allow_high_precision_mv {
18928 dec.symbol(&mut c.hp)
18929 } else {
18930 1
18931 };
18932 (d << 3) | (fr << 1) | hp
18933 };
18934 let mag = mv_class_base(class) + local as i32 + 1;
18935 if sign == 1 { -mag } else { mag }
18936}
18937
18938/// A motion vector coded as a residual against `pred` (spec 5.11.32
18939/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
18940fn read_mv(
18941 dec: &mut SymbolDecoder,
18942 mv_comp: &mut [MvComponentCdfs; 2],
18943 mv_joint: &mut [u16; 5],
18944 pred: (i32, i32),
18945 allow_high_precision_mv: bool,
18946 force_integer_mv: bool,
18947) -> (i32, i32) {
18948 let joint = dec.symbol(mv_joint);
18949 let mut diff = (0, 0);
18950 if joint == 2 || joint == 3 {
18951 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
18952 }
18953 if joint == 1 || joint == 3 {
18954 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
18955 }
18956 (pred.0 + diff.0, pred.1 + diff.1)
18957}
18958
18959/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
18960/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
18961///
18962/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
18963/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
18964/// when that is zero, or -- when both are -- the fixed fallback DV one
18965/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
18966/// left when this is the tile's first superblock row. The predictor is then
18967/// rounded to full pel, and the difference reads off the *dv* nmv context
18968/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
18969/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
18970/// symbol is coded for a DV, so none of this can move the bitstream
18971/// position -- only the reconstructed vector.
18972fn read_intrabc_dv(
18973 dec: &mut SymbolDecoder,
18974 cdfs: &mut Cdfs,
18975 mi_r: usize,
18976 mi_c: usize,
18977 side: usize,
18978) -> (i32, i32) {
18979 const INTRABC_DELAY_PIXELS: i32 = 256;
18980 let n4 = side / MI;
18981 let stack_pred = INTRABC_MI_GRID.with(|g| {
18982 let g = g.borrow();
18983 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
18984 let stack = crate::mvstack::find_mv_stack(
18985 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
18986 *mi_cols, *mi_rows,
18987 );
18988 if stack.nearest_mv == (0, 0) {
18989 stack.near_mv
18990 } else {
18991 stack.nearest_mv
18992 }
18993 })
18994 });
18995 let mut pred = stack_pred.unwrap_or((0, 0));
18996 if pred == (0, 0) {
18997 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
18998 // single-tile-row case every intrabc gate stream is).
18999 let sb_px = SB_MI as i32 * MI as i32;
19000 pred = if mi_r < SB_MI as usize {
19001 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
19002 } else {
19003 (-sb_px * 8, 0)
19004 };
19005 }
19006 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
19007 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
19008 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
19009}
19010
19011/// A 1/8-pel motion vector component converted to the 1/16-pel offset
19012/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
19013/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
19014fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
19015 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
19016}
19017
19018impl PlaneBuf {
19019 /// Adds `residual` onto an already-computed `prediction` (motion
19020 /// compensation's output, rather than [`predict`]'s intra one), writing
19021 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
19022 /// counterpart of [`PlaneBuf::reconstruct`].
19023 fn reconstruct_mc(
19024 &mut self,
19025 x: usize,
19026 y: usize,
19027 side: usize,
19028 prediction: &[u16],
19029 residual: &[i32],
19030 ) {
19031 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
19032 }
19033
19034 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
19035 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
19036 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
19037 /// VERT strip is predicted at its enclosing square `side` (matching
19038 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
19039 /// but only its own true `w`x`h` footprint is committed to the plane, so
19040 /// two strips sharing a square's coordinate origin never clobber each
19041 /// other's real pixels.
19042 fn reconstruct_mc_rect(
19043 &mut self,
19044 x: usize,
19045 y: usize,
19046 side: usize,
19047 w: usize,
19048 h: usize,
19049 prediction: &[u16],
19050 residual: &[i32],
19051 ) {
19052 // lane-sb128c r7: a 128x64 half of a 128 root at the BOTTOM frame edge
19053 // is the first block shape whose true footprint overhangs the padded
19054 // coding surface (mi_rows = 198 -> a plane 800 rows tall, block rows
19055 // 768..832). libaom reconstructs those rows into the frame buffer's
19056 // border; nothing reads them back, so they are simply dropped here.
19057 let (h, w) = (h.min(self.height.saturating_sub(y)), w.min(self.width.saturating_sub(x)));
19058 for row in 0..h {
19059 for col in 0..w {
19060 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
19061 .clamp(0, crate::decode::sample_max()) as u16;
19062 self.data[(y + row) * self.width + x + col] = sample;
19063 }
19064 }
19065 }
19066}
19067
19068/// Reads one inter-coded plane's transform block and reconstructs it by
19069/// adding its residual onto a motion-compensated `prediction` -- the inter
19070/// counterpart of [`read_plane`] (every inter transform this decoder reads is
19071/// `side`-square with no oversized-64 case, so there is no padded-grid
19072/// branch to mirror).
19073#[allow(clippy::too_many_arguments)]
19074fn read_inter_plane(
19075 dec: &mut SymbolDecoder,
19076 cdfs: &mut Cdfs,
19077 set: TxbSet,
19078 scan: &[u16],
19079 plane_idx: usize,
19080 around: (bool, bool, i32),
19081 tx_mode: usize,
19082 plane: &mut PlaneBuf,
19083 x: usize,
19084 y: usize,
19085 side: usize,
19086 base_q_idx: u8,
19087 prediction: &[u16],
19088 // lane-chromau: this block's own luma transform's *actual coded*
19089 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
19090 // chroma plane never codes its own `tx_type` symbol, but (unlike an
19091 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
19092 // the colocated luma transform's coded type, narrowed to the extended
19093 // set the CHROMA size selects ([`reduce_inherited_chroma_tx_type`]).
19094 // `None` for the luma call itself
19095 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
19096 // `DCT_DCT` default at 32-point+) already resolves it without help.
19097 inherited_luma_tx_type: Option<TxType>,
19098 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
19099 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
19100 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
19101 // transform every non-var-tx caller reads, whose plane-0 context is the
19102 // lone-transform-unit 0.
19103 luma_skip_ctx: Option<usize>,
19104) -> Result<(Vec<i32>, TxType)> {
19105 let skip_ctx = if plane_idx == 0 {
19106 luma_skip_ctx.unwrap_or(0)
19107 } else {
19108 // lane-sb128c r1: on a CHROMA plane this same parameter carries
19109 // `get_txb_ctx`'s own offset instead -- `combine_entropy_contexts(..)`
19110 // is +7 normally and +10 when the plane block is LARGER than the
19111 // transform (a 128x128 block's 64x64 uv plane block with TX_32X32
19112 // units, AV1's only such case), and the `txb_skip_chroma_32` table
19113 // carries the offset-10 rows at +3 (lane-sb128b r3).
19114 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
19115 };
19116 let mut coding = cdfs.txb(set, tx_mode);
19117 let default_tx_type = match inherited_luma_tx_type {
19118 Some(t) => reduce_inherited_chroma_tx_type(t, side, side),
19119 None => TxType::DctDct,
19120 };
19121 let (grid, tx_type) = read_coeffs(
19122 dec,
19123 &mut coding,
19124 scan,
19125 skip_ctx,
19126 dc_sign_ctx(around.2),
19127 default_tx_type,
19128 None,
19129 )?;
19130 note_chroma_class1(plane_idx, tx_type);
19131 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
19132 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} side={side} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
19133 }
19134 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
19135 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
19136 // caller hands the 32-point `scan` there, and the coded corner goes into
19137 // the top-left of the true `side`-sized grid before dequantization
19138 // (dqDenom is keyed by the true size, not the corner's), mirroring
19139 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
19140 // this decoder codes has `tx_side == side`, so this is inert below 64.
19141 let tx_side = side.min(32);
19142 let grid = if tx_side == side {
19143 grid
19144 } else {
19145 let mut full = vec![0i32; side * side];
19146 for row in 0..tx_side {
19147 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
19148 }
19149 full
19150 };
19151 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
19152 let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
19153 plane.reconstruct_mc(x, y, side, prediction, &residual);
19154 Ok((grid, tx_type))
19155}
19156
19157/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
19158/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
19159/// `reference_select` set before this is ever called, so that read is never
19160/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
19161/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
19162fn read_single_ref(
19163 dec: &mut SymbolDecoder,
19164 cdfs: &mut Cdfs,
19165 above_ref: i8,
19166 above_ref1: Option<i8>,
19167 left_ref: i8,
19168 left_ref1: Option<i8>,
19169) -> i8 {
19170 let above = (above_ref > 0).then_some(above_ref);
19171 let left = (left_ref > 0).then_some(left_ref);
19172 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
19173 let ref_frame = if p1 == 1 {
19174 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
19175 if p2 == 1 {
19176 ALTREF_FRAME
19177 } else {
19178 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
19179 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
19180 }
19181 } else {
19182 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
19183 if p3 == 1 {
19184 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
19185 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
19186 } else {
19187 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
19188 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
19189 }
19190 };
19191 if ref_frame != LAST_FRAME {
19192 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
19193 let c = match ref_frame {
19194 LAST2_FRAME => &LAST2_HITS,
19195 LAST3_FRAME => &LAST3_HITS,
19196 GOLDEN_FRAME => &GOLDEN_HITS,
19197 BWDREF_FRAME => &BWDREF_HITS,
19198 ALTREF2_FRAME => &ALTREF2_HITS,
19199 ALTREF_FRAME => &ALTREF_HITS,
19200 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
19201 };
19202 c.with(|v| v.set(v.get() + 1));
19203 }
19204 ref_frame
19205}
19206
19207/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
19208/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
19209/// `reference_select` header bit lets a block choose per-block instead of
19210/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
19211/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
19212/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
19213/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
19214/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
19215/// Resolves a compound reference's own planes -- the same `ref_frame ==
19216/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
19217/// [`decode_inter_block`]'s single-ref path already does, factored out so
19218/// the compound path can call it twice (lane-av1comp).
19219fn ref_planes<'a>(
19220 ref_frame: i8,
19221 ref_y: &'a PlaneBuf,
19222 ref_u: &'a PlaneBuf,
19223 ref_v: &'a PlaneBuf,
19224 other_refs: &'a RefSlots,
19225) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
19226 if ref_frame == LAST_FRAME {
19227 Ok((ref_y, ref_u, ref_v))
19228 } else {
19229 match other_refs[ref_frame as usize] {
19230 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
19231 None => Err(unsupported(
19232 "a reference frame selected with no picture at this frame's own \
19233 ref_frame_idx slot for it",
19234 )),
19235 }
19236 }
19237}
19238
19239/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
19240/// directly above this block's own column span, one bordering block at a
19241/// time (stepping by that neighbour's own `MiInfo::size`, which is always
19242/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
19243/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
19244/// unit at a time, and does not itself count as a step). `max_neighbors`
19245/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
19246/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
19247/// real blend pass. lane-intra16x4 r2: libaom's own "4-wide block, treat as
19248/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) IS
19249/// ported below -- the round-1 note that no block is narrower than 8px stopped
19250/// being true when the 1:4 partitions landed. A 16x4 / 4x16 strip has
19251/// `mi_size_high`/`mi_size_wide` 1, so libaom snaps the walk back to the pair's
19252/// even index, reads the ODD (chroma-carrying) half as the neighbour and steps
19253/// by 2. Measured: the 16x16 block right of a 16x16-level HORZ_4 partition
19254/// whose strip 0 is inter and strips 1..3 intra counted that inter strip as
19255/// overlappable here, while libaom's pair merge reads the INTRA strip 1 and
19256/// counts none -- so we read a `motion_mode` symbol libaom never wrote (class
19257/// `symbol-consumption-gap`), desyncing the tile at the next coefficient.
19258fn overlappable_above(
19259 grid: &MiGrid,
19260 mi_row: usize,
19261 mi_col: usize,
19262 bw4: usize,
19263 mi_cols: usize,
19264 max_neighbors: usize,
19265) -> Vec<(usize, usize, MiInfo, usize)> {
19266 let mut out = Vec::new();
19267 if mi_row == 0 {
19268 return out;
19269 }
19270 let end_col = (mi_col + bw4).min(mi_cols);
19271 let mut col = mi_col;
19272 while col < end_col && out.len() < max_neighbors {
19273 let cell = grid.get(mi_row - 1, col);
19274 let mut step = cell.map_or(1, |c| c.size).max(1).min(SB_MI as usize);
19275 let mut nb = cell;
19276 // lane-obmcrec r1: the mi the neighbour's `MiInfo` is actually taken
19277 // from -- the pair merge below moves it, and libaom reads that same
19278 // `mbmi`'s `interp_filters` (`av1_setup_build_prediction_by_above_pred`).
19279 let mut src = col;
19280 if step == 1 {
19281 // The pair merge: the walk snaps back to the pair's even column
19282 // and the ODD half (the chroma-carrying one) is the neighbour for
19283 // both -- a 4-wide 1:4 strip is never an OBMC source on its own.
19284 col &= !1;
19285 src = col + 1;
19286 nb = grid.get(mi_row - 1, src);
19287 step = 2;
19288 }
19289 if let Some(info) = nb {
19290 if info.is_inter {
19291 if src != col {
19292 OBMC_PAIR_FILTER_HITS.with(|c| c.set(c.get() + 1));
19293 }
19294 // lane-t900 r14: libaom passes `AOMMIN(xd->width, mi_step)`
19295 // as `op_mi_size` -- the block's OWN width, never the
19296 // frame-edge clamp `end_col` carries. Clamping here shrank the
19297 // neighbour PREDICTION at a frame edge, which picks the
19298 // 4-tap kernel below 8 px (class narrow-block-sharp-kernel);
19299 // the destination clip stays in `obmc_blend`.
19300 out.push((col - mi_col, step.min(bw4), *info, src - mi_col));
19301 }
19302 }
19303 col += step;
19304 }
19305 out
19306}
19307
19308/// `foreach_overlappable_nb_left`'s left-column mirror of
19309/// [`overlappable_above`] -- see its doc for the shared corner-cut.
19310fn overlappable_left(
19311 grid: &MiGrid,
19312 mi_row: usize,
19313 mi_col: usize,
19314 bh4: usize,
19315 mi_rows: usize,
19316 max_neighbors: usize,
19317) -> Vec<(usize, usize, MiInfo, usize)> {
19318 let mut out = Vec::new();
19319 if mi_col == 0 {
19320 return out;
19321 }
19322 let end_row = (mi_row + bh4).min(mi_rows);
19323 let mut row = mi_row;
19324 while row < end_row && out.len() < max_neighbors {
19325 let cell = grid.get(row, mi_col - 1);
19326 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
19327 // width (8) would swallow the strip below it.
19328 let mut step = cell.map_or(1, |c| c.size_h).max(1).min(SB_MI as usize);
19329 let mut nb = cell;
19330 // lane-obmcrec r1: see `overlappable_above`'s `src`.
19331 let mut src = row;
19332 if step == 1 {
19333 // The pair merge, left-column mirror: a 4-TALL neighbour (a 16x4
19334 // strip) is half of a chroma pair and the pair's SECOND row is the
19335 // neighbour for both.
19336 row &= !1;
19337 src = row + 1;
19338 nb = grid.get(src, mi_col - 1);
19339 step = 2;
19340 }
19341 if let Some(info) = nb {
19342 if info.is_inter {
19343 if src != row {
19344 OBMC_PAIR_FILTER_HITS.with(|c| c.set(c.get() + 1));
19345 }
19346 // lane-t900 r14: `AOMMIN(xd->height, mi_step)` -- see
19347 // `overlappable_above`.
19348 out.push((row - mi_row, step.min(bh4), *info, src - mi_row));
19349 }
19350 }
19351 row += step;
19352 }
19353 out
19354}
19355
19356/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples`
19357/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2:
19358/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128`
19359/// libaom's mask loop runs one level further and strips the top-right sample
19360/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame
19361/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates
19362/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is
19363/// the block's own side in 4x4 (`mi`) units (square inter leaves only here).
19364fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
19365 crate::mvstack::has_top_right(mi_row, mi_col, bs, bs)
19366}
19367
19368/// `av1_findSamples` (`mvref_common.c`), full port: the up to
19369/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
19370/// samples (`record_samples`) that share this block's own single reference
19371/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
19372/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
19373/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
19374/// libaom are also mi units of that same square side here). Each sample's
19375/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
19376/// come from the *neighbour* cell's own coded size, not this block's.
19377#[allow(clippy::too_many_arguments)]
19378fn find_samples(
19379 grid: &MiGrid,
19380 mi_row: usize,
19381 mi_col: usize,
19382 bw4: usize,
19383 bh4: usize,
19384 mi_cols: usize,
19385 mi_rows: usize,
19386 ref_frame: i8,
19387) -> Vec<crate::warp::Sample> {
19388 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
19389 let up_available = mi_row > 0;
19390 let left_available = mi_col > 0;
19391 let mut samples = Vec::with_capacity(MAX);
19392 // lane-t900 r9: `EC_PROJ_MI=<mi_row>,<mi_col>` lists this block's warp
19393 // sample candidates in libaom's own order (above, left, top-left,
19394 // top-right) -- `num_proj_ref >= 1` is what picks the 3-symbol
19395 // motion_mode alphabet over the 2-symbol obmc one.
19396 let proj_dbg = crate::envflags::var("EC_PROJ_MI")
19397 .is_ok_and(|v| v == format!("{mi_row},{mi_col}"));
19398 let single_ref_match = |info: &MiInfo| {
19399 let m = info.ref_frame == ref_frame && info.ref_frame1.is_none();
19400 if proj_dbg {
19401 eprintln!(
19402 "EC_PROJ cand ref={} ref1={:?} size={} size_h={} is_inter={} want={ref_frame} match={m}",
19403 info.ref_frame, info.ref_frame1, info.size, info.size_h, info.is_inter
19404 );
19405 }
19406 m
19407 };
19408 let mut do_tl = true;
19409 let mut do_tr = true;
19410 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
19411 let nb_bw = (info.size * 4) as i32;
19412 // lane-rect r2: the neighbour's own true height -- a rect strip
19413 // neighbour donates its sample at ITS center (aom pts y=-72 for a
19414 // 32x16 above strip; the square assumption put it at -136).
19415 let nb_bh = (info.size_h * 4) as i32;
19416 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
19417 };
19418
19419 'outer: {
19420 if up_available {
19421 let above = grid.get(mi_row - 1, mi_col);
19422 let superblock_width = above.map_or(1, |c| c.size).max(1);
19423 if bw4 <= superblock_width {
19424 let col_offset = -((mi_col % superblock_width) as isize);
19425 if col_offset < 0 {
19426 do_tl = false;
19427 }
19428 if col_offset + superblock_width as isize > bw4 as isize {
19429 do_tr = false;
19430 }
19431 if let Some(info) = above {
19432 if single_ref_match(info) {
19433 samples.push(rec(info, 0, -1, col_offset as i32, 1));
19434 if samples.len() >= MAX {
19435 break 'outer;
19436 }
19437 }
19438 }
19439 } else {
19440 let mut i = 0usize;
19441 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
19442 while i < limit {
19443 let cell = grid.get(mi_row - 1, mi_col + i);
19444 let sw = cell.map_or(1, |c| c.size).max(1);
19445 if let Some(info) = cell {
19446 if single_ref_match(info) {
19447 samples.push(rec(info, 0, -1, i as i32, 1));
19448 if samples.len() >= MAX {
19449 break 'outer;
19450 }
19451 }
19452 }
19453 i += sw;
19454 }
19455 }
19456 }
19457
19458 if left_available {
19459 let left = grid.get(mi_row, mi_col - 1);
19460 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
19461 if bh4 <= superblock_height {
19462 let row_offset = -((mi_row % superblock_height) as isize);
19463 if row_offset < 0 {
19464 do_tl = false;
19465 }
19466 if let Some(info) = left {
19467 if single_ref_match(info) {
19468 samples.push(rec(info, row_offset as i32, 1, 0, -1));
19469 if samples.len() >= MAX {
19470 break 'outer;
19471 }
19472 }
19473 }
19474 } else {
19475 let mut i = 0usize;
19476 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
19477 while i < limit {
19478 let cell = grid.get(mi_row + i, mi_col - 1);
19479 let sh = cell.map_or(1, |c| c.size_h).max(1);
19480 if let Some(info) = cell {
19481 if single_ref_match(info) {
19482 samples.push(rec(info, i as i32, 1, 0, -1));
19483 if samples.len() >= MAX {
19484 break 'outer;
19485 }
19486 }
19487 }
19488 i += sh;
19489 }
19490 }
19491 }
19492
19493 if do_tl && left_available && up_available {
19494 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
19495 if single_ref_match(info) {
19496 samples.push(rec(info, 0, -1, 0, -1));
19497 if samples.len() >= MAX {
19498 break 'outer;
19499 }
19500 }
19501 }
19502 }
19503
19504 // lane-t900 r9: libaom passes `AOMMAX(xd->width, xd->height)` here
19505 // (`mvref_common.c:1235`), NOT the block's width -- a rect block's
19506 // top-right reach is probed at its LONGER side. With `bw4` a 64x128
19507 // block found a top-right sample libaom never sees, so
19508 // `num_proj_ref >= 1` picked the 3-symbol `motion_mode_cdf` where
19509 // libaom reads the 2-symbol `obmc_cdf` (class
19510 // wrong-alphabet-same-value).
19511 let tr_reach = crate::mvstack::has_top_right(mi_row, mi_col, bw4, bh4);
19512 if do_tr && bw4 != bh4 && tr_reach != has_top_right(mi_row, mi_col, bw4) {
19513 TR_REACH_LONGER_SIDE_HITS.with(|c| c.set(c.get() + 1));
19514 }
19515 if do_tr && tr_reach {
19516 let tr_col = mi_col + bw4;
19517 if mi_row > 0 && tr_col < mi_cols {
19518 if let Some(info) = grid.get(mi_row - 1, tr_col) {
19519 if single_ref_match(info) {
19520 samples.push(rec(info, 0, -1, bw4 as i32, 1));
19521 }
19522 }
19523 }
19524 }
19525 }
19526 samples
19527}
19528
19529/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
19530/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
19531/// the 2-symbol `obmc_cdf` (spec 5.11.24).
19532#[allow(clippy::too_many_arguments)]
19533fn num_proj_ref(
19534 grid: &MiGrid,
19535 mi_row: usize,
19536 mi_col: usize,
19537 bw4: usize,
19538 bh4: usize,
19539 mi_cols: usize,
19540 mi_rows: usize,
19541 ref_frame: i8,
19542) -> u8 {
19543 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
19544}
19545
19546/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
19547/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
19548/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
19549/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
19550/// to 64 (no neighbour contribution) away from it. Only the lengths this
19551/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
19552/// are transcribed.
19553fn obmc_mask(len: usize) -> &'static [u8] {
19554 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
19555 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
19556 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
19557 // round wired interior 16x16 splits down to real 8x8 leaves, where the
19558 // old `unreachable!()` below fired as a hard panic.
19559 const M1: [u8; 1] = [64];
19560 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
19561 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
19562 // chroma), which only became live once 8x8 inter leaves stopped being
19563 // refused.
19564 const M2: [u8; 2] = [45, 64];
19565 const M4: [u8; 4] = [39, 50, 59, 64];
19566 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
19567 const M16: [u8; 16] = [
19568 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
19569 ];
19570 const M32: [u8; 32] = [
19571 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
19572 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
19573 ];
19574 match len {
19575 1 => &M1,
19576 2 => &M2,
19577 4 => &M4,
19578 8 => &M8,
19579 16 => &M16,
19580 32 => &M32,
19581 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
19582 }
19583}
19584
19585/// A bordering block's own resolved interp filter kernel, `(h, v)` --
19586/// mirrors [`resolve_interp_filter`]'s own return order from its stored
19587/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
19588/// `[v_sym, h_sym]`). The `[3, 3]` sentinel is only ever stored for an intra
19589/// neighbour (excluded by [`overlappable_above`]/[`overlappable_left`]'s
19590/// `is_inter` gate) or when `interp_fixed` is `Some` for the whole frame
19591/// (handled here first) -- so a sentinel reaching the kernel lookup means the
19592/// stream desynced upstream, and this refuses instead of panicking.
19593fn neighbour_filter(
19594 interp_fixed: Option<mc::InterpFilterKind>,
19595 sym: [u8; 2],
19596) -> Result<(mc::InterpFilterKind, mc::InterpFilterKind)> {
19597 if let Some(kind) = interp_fixed {
19598 return Ok((kind, kind));
19599 }
19600 // lane-golomb r9: this used to hand the sentinel straight to
19601 // `from_switchable_symbol`, which PANICS on any value above 2 -- a crash
19602 // on stream data (measured on a real 192x68 cq40 aomenc stream, where an
19603 // inter leaf below 8x8 desyncs upstream and leaves an unrecorded filter
19604 // behind). A decoder must refuse such a stream by name, never abort the
19605 // process; the desync that produces the sentinel belongs to lane-intersub8.
19606 if sym[0] > 2 || sym[1] > 2 {
19607 return Err(unsupported(
19608 "an OBMC neighbour whose switchable interp filter was never recorded",
19609 ));
19610 }
19611 Ok((
19612 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
19613 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
19614 ))
19615}
19616
19617/// lane-obmcrec r1 MEASUREMENT rung (`EC_OBMCREC=1`): every OBMC neighbour whose
19618/// recorded switchable-filter symbols are the `[3, 3]` "never recorded" sentinel
19619/// -- names the neighbour's own position/shape/reference so the decode path that
19620/// failed to record its filter can be identified. Read-only, off by default.
19621#[allow(clippy::too_many_arguments)]
19622fn obmcrec_probe(
19623 dir: &str,
19624 mi_row: usize,
19625 mi_col: usize,
19626 write_w: usize,
19627 write_h: usize,
19628 off4: usize,
19629 span4: usize,
19630 nb: &MiInfo,
19631 syms: [u8; 2],
19632 cell: Option<MiInfo>,
19633 fixed: bool,
19634) {
19635 if (syms[0] <= 2 && syms[1] <= 2) || !crate::envflags::env_flag!("EC_OBMCREC") {
19636 return;
19637 }
19638 eprintln!(
19639 "OBMCREC {dir} cur_mi=({mi_row},{mi_col}) cur_wh=({write_w}x{write_h}) off4={off4} \
19640span4={span4} syms={syms:?} fixed={fixed} nb_size=({}x{}) nb_ref={} nb_ref1={:?} nb_mv=({},{}) \
19641nb_newmv={} cell_size={:?} cell_inter={:?} cell_ref={:?} sb_row_off={} sb_col_off={}",
19642 nb.size * 4,
19643 nb.size_h * 4,
19644 nb.ref_frame,
19645 nb.ref_frame1,
19646 nb.mv.0,
19647 nb.mv.1,
19648 nb.is_new_mv,
19649 cell.map(|c| (c.size * 4, c.size_h * 4)),
19650 cell.map(|c| c.is_inter),
19651 cell.map(|c| c.ref_frame),
19652 mi_row % 32,
19653 mi_col % 32,
19654 );
19655}
19656
19657/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
19658/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
19659/// under `av1_setup_build_prediction_by_{above,left}_pred`).
19660#[allow(clippy::too_many_arguments)]
19661fn obmc_neighbour_pred(
19662 refplane: &PlaneBuf,
19663 x: usize,
19664 y: usize,
19665 mv: (i32, i32),
19666 w: usize,
19667 h: usize,
19668 luma: bool,
19669 h_kind: mc::InterpFilterKind,
19670 v_kind: mc::InterpFilterKind,
19671 // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own
19672 // reference (derived from luma widths, applied unchanged to chroma whose
19673 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
19674 // the ordinary stride-1 path bit-exact.
19675 x_scale_fp: i64,
19676) -> Vec<u16> {
19677 let mut out = vec![0u16; w * h];
19678 if x_scale_fp == mc::REF_NO_SCALE {
19679 mc::predict_with_filters(
19680 &refplane.data,
19681 refplane.width,
19682 refplane.true_width,
19683 refplane.true_height,
19684 mv_to_q4(x, mv.1, luma),
19685 mv_to_q4(y, mv.0, luma),
19686 w,
19687 h,
19688 h_kind,
19689 v_kind,
19690 &mut out,
19691 );
19692 } else {
19693 mc::predict_scaled(
19694 &refplane.data,
19695 refplane.width,
19696 refplane.true_width,
19697 refplane.true_height,
19698 mv_to_q4(x, mv.1, luma),
19699 mv_to_q4(y, mv.0, luma),
19700 x_scale_fp,
19701 w,
19702 h,
19703 h_kind,
19704 v_kind,
19705 &mut out,
19706 );
19707 }
19708 out
19709}
19710
19711/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
19712/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
19713/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
19714const II_WEIGHTS_1D: [u8; 128] = [
19715 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
19716 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
19717 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
19718 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
19719 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
19720 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
19721 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
19722];
19723
19724/// lane-interintra r1: non-wedge interintra prediction for one plane
19725/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
19726/// `build_smooth_interintra_mask`). Builds the intra predictor for the
19727/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
19728/// own decoded edges at `(x, y)`, then blends it over the inter prediction
19729/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
19730/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
19731/// reduces to `128 / side` for the square plane sizes this decoder reaches.
19732/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
19733/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
19734fn interintra_blend(
19735 plane: &PlaneBuf,
19736 x: usize,
19737 y: usize,
19738 bw: usize,
19739 bh: usize,
19740 stride: usize,
19741 ii_mode: u8,
19742 wedge: Option<(&'static [u8], usize)>,
19743 pred: &mut [u16],
19744) {
19745 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
19746 let intra_mode = match ii_mode {
19747 0 => crate::intra::DC_PRED,
19748 1 => crate::intra::V_PRED,
19749 2 => crate::intra::H_PRED,
19750 _ => crate::intra::SMOOTH_PRED,
19751 };
19752 let (above, left, corner) = plane.edges_rect(
19753 x,
19754 y,
19755 bw,
19756 bh,
19757 crate::encode::Reach {
19758 above_right: false,
19759 below_left: false,
19760 },
19761 );
19762 let mut intra = vec![0u16; bw * bh];
19763 // Edge filtering never applies here: V/H at delta 0 are plain edge
19764 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
19765 // angle at all.
19766 predict(
19767 intra_mode,
19768 0,
19769 above.as_deref(),
19770 left.as_deref(),
19771 corner,
19772 bw,
19773 bh,
19774 false,
19775 false,
19776 &mut intra,
19777 );
19778 // `ii_size_scales[bsize]` is keyed on the block's LONGER side
19779 // (`MAX_SB_SIZE >> max(bw,bh)` order), not on the square this decoder
19780 // builds the predictor buffer at.
19781 let scale = 128 / bw.max(bh);
19782 for i in 0..bh {
19783 for j in 0..bw {
19784 let m = u32::from(match wedge {
19785 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
19786 // over the wedge codebook, intra as src0, fixed sign 0).
19787 // Luma plane: mask rows are luma-resolution, ms == side.
19788 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
19789 // subw == subh == 1).
19790 Some((mask, ms)) if ms == stride => mask[i * stride + j],
19791 Some((mask, ms)) => {
19792 let t = 2 * i * ms + 2 * j;
19793 ((u32::from(mask[t])
19794 + u32::from(mask[t + 1])
19795 + u32::from(mask[t + ms])
19796 + u32::from(mask[t + ms + 1])
19797 + 2)
19798 >> 2) as u8
19799 }
19800 None => match ii_mode {
19801 0 => 32,
19802 1 => II_WEIGHTS_1D[i * scale],
19803 2 => II_WEIGHTS_1D[j * scale],
19804 _ => II_WEIGHTS_1D[i.min(j) * scale],
19805 },
19806 });
19807 let idx = i * stride + j;
19808 pred[idx] = ((m * u32::from(intra[i * bw + j]) + (64 - m) * u32::from(pred[idx]) + 32)
19809 >> 6) as u16;
19810 }
19811 }
19812}
19813
19814/// `w` is the number of columns actually written (clipped to the block's own
19815/// buffer at a frame edge); `ts` is `tmp`'s own stride, the neighbour
19816/// prediction's full width.
19817#[allow(clippy::too_many_arguments)]
19818fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, ts: usize, tmp: &[u16]) {
19819 let mask = obmc_mask(h);
19820 for row in 0..h {
19821 let m = u32::from(mask[row]);
19822 for col in 0..w {
19823 let d = &mut dst[(oy + row) * stride + ox + col];
19824 let t = u32::from(tmp[row * ts + col]);
19825 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
19826 }
19827 }
19828}
19829
19830/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
19831/// left-neighbour pass, `aom_blend_a64_hmask`).
19832fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
19833 let mask = obmc_mask(w);
19834 for row in 0..h {
19835 for col in 0..w {
19836 let m = u32::from(mask[col]);
19837 let d = &mut dst[(oy + row) * stride + ox + col];
19838 let t = u32::from(tmp[row * w + col]);
19839 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
19840 }
19841 }
19842}
19843
19844/// libaom's own `BLOCK_SIZE` enum index for a `w4`x`h4` (mi-unit) block --
19845/// only for the `EC_OBMC` trace rung below, so it reads byte-identical to
19846/// the instrumented aomdec's `backup_mbmi.bsize`.
19847fn ec_obmc_bsize(w4: usize, h4: usize) -> i32 {
19848 match (w4, h4) {
19849 (1, 1) => 0,
19850 (1, 2) => 1,
19851 (2, 1) => 2,
19852 (2, 2) => 3,
19853 (2, 4) => 4,
19854 (4, 2) => 5,
19855 (4, 4) => 6,
19856 (4, 8) => 7,
19857 (8, 4) => 8,
19858 (8, 8) => 9,
19859 (8, 16) => 10,
19860 (16, 8) => 11,
19861 (16, 16) => 12,
19862 (1, 4) => 16,
19863 (4, 1) => 17,
19864 (2, 8) => 18,
19865 (8, 2) => 19,
19866 (4, 16) => 20,
19867 (16, 4) => 21,
19868 _ => -1,
19869 }
19870}
19871
19872/// The `EC_OBMC` rung: one line per blended neighbour, in the instrumented
19873/// aomdec's own byte format (`decodeframe.c`
19874/// `dec_build_prediction_by_{above,left}_pred`), so the two decoders' OBMC
19875/// neighbour lists diff line for line. `filt` is libaom's packed
19876/// `interp_filters.as_int` = `y_filter | (x_filter << 16)`.
19877#[allow(clippy::too_many_arguments)]
19878fn ec_obmc_trace(
19879 dir: &str,
19880 mi_row: usize,
19881 mi_col: usize,
19882 write_w: usize,
19883 write_h: usize,
19884 rel: usize,
19885 op: usize,
19886 nb: &MiInfo,
19887 h_kind: mc::InterpFilterKind,
19888 v_kind: mc::InterpFilterKind,
19889) {
19890 if !crate::envflags::env_flag!("EC_OBMC") {
19891 return;
19892 }
19893 let sym = |k: mc::InterpFilterKind| match k {
19894 mc::InterpFilterKind::Smooth => 1u32,
19895 mc::InterpFilterKind::Sharp => 2,
19896 _ => 0,
19897 };
19898 eprintln!(
19899 "EC_OBMC {dir} mi=({mi_row},{mi_col}) wh=({write_w}x{write_h}) rel={rel} op={op} \
19900nbmv=({},{}) nbref={} nbbsize={} filt={}",
19901 nb.mv.0,
19902 nb.mv.1,
19903 nb.ref_frame,
19904 ec_obmc_bsize(nb.size, nb.size_h),
19905 sym(v_kind) | (sym(h_kind) << 16),
19906 );
19907}
19908
19909/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
19910/// the overlap strip against each bordering above/left inter neighbour's own
19911/// mv/ref/filter and blends it into this block's just-built single-reference
19912/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
19913/// left, each reading only the *original* prediction this function was
19914/// handed (never the other pass's own output), matching libaom's own
19915/// independence between the two. `max_neighbor_obmc`'s own cap table
19916/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
19917/// decoder's own square blocks always index the same value both ways) bounds
19918/// how many bordering blocks actually get blended, separate from the
19919/// eligibility scan's own unbounded ("any at all") walk.
19920#[allow(clippy::too_many_arguments)]
19921fn obmc_blend(
19922 grid: &MiGrid,
19923 neighbours: &Neighbours,
19924 mi_row: usize,
19925 mi_col: usize,
19926 bw4: usize,
19927 bh4: usize,
19928 mi_rows: usize,
19929 mi_cols: usize,
19930 side: usize,
19931 write_w: usize,
19932 write_h: usize,
19933 chroma_side: usize,
19934 px: usize,
19935 py: usize,
19936 cpx: usize,
19937 cpy: usize,
19938 ref_y: &PlaneBuf,
19939 ref_u: &PlaneBuf,
19940 ref_v: &PlaneBuf,
19941 other_refs: &RefSlots,
19942 interp_fixed: Option<mc::InterpFilterKind>,
19943 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
19944 // neighbour is re-predicted against ITS OWN reference, which may be
19945 // scaled differently from this block's (spec 7.11.3.3 / libaom
19946 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
19947 // `scale_factors`).
19948 frame_width: usize,
19949 pred_y: &mut [u16],
19950 pred_u: &mut [u16],
19951 pred_v: &mut [u16],
19952) -> Result<()> {
19953 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
19954 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
19955 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
19956 // right only for square blocks.
19957 // libaom `max_neighbor_obmc[6] = { 0, 1, 2, 3, 4, 4 }` indexed by
19958 // `mi_size_wide_log2[bsize]` (above pass) / `mi_size_high_log2` (left):
19959 // 1 mi -> 0, 2 -> 1, 4 -> 2, 8 -> 3, 16+ -> 4. lane-inter4 r3: the old
19960 // `1..=4 => 2` row was right only for blocks at least 16 px on that axis
19961 // -- a 16x8 leaf's LEFT pass (bh4 = 2) walked up to two neighbours where
19962 // libaom walks one, blending an extra 8-px-tall neighbour into every
19963 // rect leaf with two of them on its left edge (class table-narrowed-to-
19964 // the-reachable-sizes; the square gates could never expose it).
19965 let max_nb = |n4: usize| match n4 {
19966 0..=1 => 0,
19967 2 => 1,
19968 3..=4 => 2,
19969 5..=8 => 3,
19970 _ => 4,
19971 };
19972 // lane-inter4 r4: r3 refused OBMC on a 16x8/8x16 leaf (5302 luma pixels
19973 // of one frame wrong). Re-measured on this tree with an `EC_OBMC` rung in
19974 // both decoders on that exact stream: the neighbour lists agree entry for
19975 // entry (position, span, mv, ref, size, filter) and all six pre-filter
19976 // frames are byte-identical to the instrumented aomdec's. The refusal is
19977 // gone; the counter below is what the gate's `--enable-obmc=1` arm reads.
19978 // The only decode-path change between r3's measurement and this one is the
19979 // lane-interbis merge (`build_motion_field`'s compound slot walk), which
19980 // moves temporal MV candidates -- not bisected further.
19981 if matches!((write_w, write_h), (16, 8) | (8, 16)) {
19982 OBMC_RECT_LEAF_HITS.with(|c| c.set(c.get() + 1));
19983 }
19984 // lane-sb128c r1: libaom caps the overlap strip at a 64x64 block's own
19985 // half (`reconinter.c` 860/899: `AOMMIN(block_size_high[bsize],
19986 // block_size_high[BLOCK_64X64]) >> 1`, and the `block_size_wide` mirror) --
19987 // inert below 128, where a 128x128 block would otherwise blend a 64-row
19988 // strip `obmc_mask` has no table for.
19989 let overlap_above = write_h.min(64) / 2;
19990 let overlap_left = write_w.min(64) / 2;
19991 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
19992 // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided
19993 // obmc") returns `dir == 0` when the chroma plane's own block is
19994 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
19995 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
19996 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
19997
19998 // lane-t900 r13 rung: EC_MCB="<plane>:<px>:<py>[:<frame>]" (chroma plane
19999 // 1 only) prints this block's chroma prediction rows before and after the
20000 // OBMC blend, matching the instrumented aomdec's EC_MCB dump.
20001 let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::var("EC_MCB").ok().and_then(|v| {
20002 let f: Vec<&str> = v.split(':').collect();
20003 if f.len() < 3 || f[0] != "1" {
20004 return None;
20005 }
20006 let (x, y) = (f[1].parse::<usize>().ok()?, f[2].parse::<usize>().ok()?);
20007 let fr = f.get(3).and_then(|s| s.parse::<i64>().ok()).unwrap_or(-1);
20008 let idx = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) as i64;
20009 if x >= cpx && x < cpx + write_w / 2 && y >= cpy && y < cpy + write_h / 2
20010 && (fr < 0 || fr == idx)
20011 {
20012 Some((x, y, idx))
20013 } else {
20014 None
20015 }
20016 });
20017 if let Some((_, _, idx)) = ec_mcb {
20018 eprintln!(
20019 "OUR_MCB pre f={idx} cpx={cpx} cpy={cpy} cw={} ch={}",
20020 write_w / 2,
20021 write_h / 2
20022 );
20023 for r in 0..write_h / 2 {
20024 let row: Vec<u16> = (0..write_w / 2).map(|c| pred_u[r * chroma_side + c]).collect();
20025 eprintln!("OUR_MCB prerow{r}: {row:?}");
20026 }
20027 }
20028 for (off4, span4, nb, src4) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
20029 {
20030 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
20031 // (this decoder's own outer block-loop granularity), one step
20032 // coarser than the mi(4px) units `overlappable_above` walks in --
20033 // divide back down to that column.
20034 // lane-gmaffine r2: the neighbour's OWN mi-granular filter
20035 // (libaom `av1_setup_build_prediction_by_above_pred` reads
20036 // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot
20037 // stays as the fallback for paths that do not record one yet
20038 // (compound), which is what every earlier round used.
20039 let above_syms = neighbours.above_filter[mi_col + src4];
20040 obmcrec_probe(
20041 "above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, above_syms,
20042 grid.get(mi_row - 1, mi_col + src4).copied(), interp_fixed.is_some(),
20043 );
20044 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;
20045 ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
20046 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
20047 let nb_scale = mc::scale_factor(ny.width, frame_width);
20048 if mi_col + off4 + span4 > mi_cols {
20049 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
20050 }
20051 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
20052 // lane-t900 r14: the prediction is `op_mi_size` wide (kernel choice
20053 // included); only the WRITE is clipped to this block's own buffer.
20054 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
20055 obmc_blend_v(pred_y, side, ox, 0, bw.min(write_w - ox), bh, bw, &tmp_y);
20056 if !skip_chroma_above {
20057 // lane-t900 r13 (measured, NOT a defect): libaom's min-4 clamp
20058 // (`dec_build_prediction_by_above_pred`) sizes only the OBMC
20059 // PREDICTION buffer; the blend length is the plain half
20060 // (`build_obmc_inter_pred_above`: `overlap >> ss_y`), so flooring
20061 // this at 4 blends rows libaom never blends -- on a 10-bit
20062 // 1920x792 cut that went 36 differing frames -> 266, worst
20063 // 13 B -> 11007 B.
20064 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
20065 let cw = cbw.min(write_w / 2 - cox);
20066 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
20067 obmc_blend_v(pred_u, chroma_side, cox, 0, cw, cbh, cbw, &tmp_u);
20068 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
20069 obmc_blend_v(pred_v, chroma_side, cox, 0, cw, cbh, cbw, &tmp_v);
20070 }
20071 }
20072
20073 for (off4, span4, nb, src4) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4))
20074 {
20075 let left_syms = neighbours.left_filter[mi_row + src4];
20076 obmcrec_probe(
20077 "left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, left_syms,
20078 grid.get(mi_row + src4, mi_col - 1).copied(), interp_fixed.is_some(),
20079 );
20080 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;
20081 ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
20082 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
20083 let nb_scale = mc::scale_factor(ny.width, frame_width);
20084 if mi_row + off4 + span4 > mi_rows {
20085 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
20086 }
20087 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
20088 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
20089 obmc_blend_h(pred_y, side, 0, oy, bw, bh.min(write_h - oy), &tmp_y);
20090 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
20091 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
20092 if let Some((_, _, idx)) = ec_mcb {
20093 eprintln!(
20094 "OUR_MCB left f={idx} off4={off4} span4={span4} cbw={cbw} cbh={cbh} coy={coy} mv=({},{}) ref0={}",
20095 nb.mv.0, nb.mv.1, nb.ref_frame
20096 );
20097 for r in 0..cbh {
20098 let row: Vec<u16> = (0..cbw).map(|c| tmp_u[r * cbw + c]).collect();
20099 eprintln!("OUR_MCB lrow{r}: {row:?}");
20100 }
20101 }
20102 let ch = cbh.min(write_h / 2 - coy);
20103 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, ch, &tmp_u);
20104 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
20105 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, ch, &tmp_v);
20106 }
20107 if let Some((_, _, idx)) = ec_mcb {
20108 for r in 0..write_h / 2 {
20109 let row: Vec<u16> = (0..write_w / 2).map(|c| pred_u[r * chroma_side + c]).collect();
20110 eprintln!("OUR_MCB post f={idx} row{r}: {row:?}");
20111 }
20112 }
20113 Ok(())
20114}
20115
20116/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
20117/// the square block sizes this decoder ever decodes (32/16/8, all
20118/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
20119/// always `is_interinter_compound_used`, so the function is always `true`
20120/// for `side` -- kept as a named call (rather than inlined `true`) so a
20121/// future sub-8 block size does not silently misdecode a real stream.
20122fn is_any_masked_compound_used_here(bw: usize, bh: usize) -> bool {
20123 // lane-inter16ab r4 (class sweep of the r3 CDF-row defect):
20124 // `is_comp_ref_allowed(bsize)` is `AOMMIN(block_size_wide, block_size_high)
20125 // >= 8` on the block's TRUE footprint -- a 16x4/4x16 strip is NOT allowed,
20126 // so libaom writes no `comp_group_idx` symbol there at all. Keyed off the
20127 // square `side` we read one the reference never wrote.
20128 bw.min(bh) >= 8
20129}
20130
20131/// The `BLOCK_SIZES_ALL` index of a `bw x bh` block (libaom `enum BLOCK_SIZE`,
20132/// `blockd.h`) -- the row every size-indexed inter CDF table
20133/// (`compound_type_cdf`, `wedge_idx_cdf`) is keyed by. Our `decode_inter_block`
20134/// carries the enclosing SQUARE `side` for context purposes (the accepted
20135/// strip corner-cut), so a 16x8 / 8x16 PARTITION_HORZ/VERT strip that reads
20136/// one of those symbols off `side` alone takes BLOCK_16X16's row and desyncs
20137/// (lane-inter16ab r3: a real 16x8 compound strip with `comp_group_idx == 1`,
20138/// decode-order frame 5, our range 64901 vs the oracle's 47271 at the very
20139/// next block's mode read).
20140fn bsize_all_index(bw: usize, bh: usize) -> Option<usize> {
20141 Some(match (bw, bh) {
20142 (4, 4) => 0,
20143 (4, 8) => 1,
20144 (8, 4) => 2,
20145 (8, 8) => 3,
20146 (8, 16) => 4,
20147 (16, 8) => 5,
20148 (16, 16) => 6,
20149 (16, 32) => 7,
20150 (32, 16) => 8,
20151 (32, 32) => 9,
20152 (32, 64) => 10,
20153 (64, 32) => 11,
20154 (64, 64) => 12,
20155 (64, 128) => 13,
20156 (128, 64) => 14,
20157 (128, 128) => 15,
20158 (4, 16) => 16,
20159 (16, 4) => 17,
20160 (8, 32) => 18,
20161 (32, 8) => 19,
20162 (16, 64) => 20,
20163 (64, 16) => 21,
20164 _ => return None,
20165 })
20166}
20167
20168/// `av1_wedge_params_lookup[bsize].wedge_types > 0` (libaom `reconinter.c`):
20169/// the block sizes that carry a wedge codebook at all. A `compound_type`
20170/// symbol is written only for these; every other size infers
20171/// `COMPOUND_DIFFWTD`.
20172fn wedge_used_bsize(bw: usize, bh: usize) -> bool {
20173 matches!(
20174 (bw, bh),
20175 (8, 8) | (8, 16) | (16, 8) | (16, 16) | (16, 32) | (32, 16) | (32, 32) | (8, 32) | (32, 8)
20176 )
20177}
20178
20179
20180
20181
20182/// Whether a compound reference pair is unidirectional (both references on
20183/// the same temporal side of the current frame) -- `has_uni_comp_refs`
20184/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
20185/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
20186/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
20187/// is_backward(ref1)`). Used to build a real
20188/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
20189/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
20190fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
20191 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
20192 backward(ref0) == backward(ref1)
20193}
20194
20195/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
20196/// above/left neighbour contributions [`Neighbours::record_inter`]/
20197/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
20198/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
20199/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
20200/// leaves read the same neighbour cell (class context-read-from-one-cell).
20201fn get_comp_group_idx_context(
20202 neighbours: &Neighbours,
20203 at_mi: (usize, usize),
20204 side: usize,
20205) -> usize {
20206 let _ = side;
20207 let (rmi, cmi) = at_mi;
20208 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
20209 .min(5)
20210}
20211
20212/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
20213/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
20214/// block's own two references' distances from the current frame (spec
20215/// 7.11.3.15's `get_relative_dist`, same convention
20216/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
20217#[allow(clippy::too_many_arguments)]
20218fn get_comp_index_context(
20219 neighbours: &Neighbours,
20220 at_mi: (usize, usize),
20221 side: usize,
20222 order_hint_bits: u32,
20223 cur_order_hint: u32,
20224 ref0_order_hint: u32,
20225 ref1_order_hint: u32,
20226) -> usize {
20227 let _ = side;
20228 let (rmi, cmi) = at_mi;
20229 let fwd =
20230 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
20231 .abs();
20232 let bck =
20233 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
20234 .abs();
20235 let offset = usize::from(fwd == bck);
20236 neighbours.above_compound_idx[cmi] as usize
20237 + neighbours.left_compound_idx[rmi] as usize
20238 + 3 * offset
20239}
20240
20241fn read_comp_mode(
20242 dec: &mut SymbolDecoder,
20243 cdfs: &mut Cdfs,
20244 above: Option<NeighbourRef>,
20245 left: Option<NeighbourRef>,
20246) -> bool {
20247 let ctx = reference_mode_ctx(above, left);
20248 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
20249 if compound {
20250 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
20251 }
20252 compound
20253}
20254
20255/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
20256/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
20257/// arm), reached once [`read_comp_mode`] has already returned
20258/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
20259/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
20260/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
20261/// convention [`read_single_ref`] already uses, for every downstream binary
20262/// decision. libaom `pred_common.c`'s own compound context functions
20263/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
20264/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
20265/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
20266/// (same vote-the-neighbours-above-left shape, same forward/backward and
20267/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
20268/// against the C source rather than porting six near-duplicate functions.
20269/// Its caller today only needs the symbols consumed, correctly, to keep the
20270/// arithmetic decoder's own state in sync before refusing the block by name
20271/// -- the returned pair is not yet threaded into any motion-compensation
20272/// path.
20273fn read_compound_ref_frames(
20274 dec: &mut SymbolDecoder,
20275 cdfs: &mut Cdfs,
20276 above: Option<NeighbourRef>,
20277 left: Option<NeighbourRef>,
20278 above_ref: i8,
20279 left_ref: i8,
20280) -> (i8, i8) {
20281 let a = (above_ref > 0).then_some(above_ref);
20282 let l = (left_ref > 0).then_some(left_ref);
20283 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
20284 // neighbour's references, not just its first -- `a1`/`l1` carry that
20285 // second reference through to every vote below (lane-av1blend r6: a
20286 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
20287 // row for a block sitting under a skip_mode-forced compound neighbour).
20288 let a1 = above.and_then(|n| n.ref1);
20289 let l1 = left.and_then(|n| n.ref1);
20290 let type_ctx = comp_reference_type_ctx(above, left);
20291 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
20292 if unidir {
20293 UNI_COMP_HITS.with(|c| c.set(c.get() + 1));
20294 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
20295 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
20296 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
20297 if bit == 1 {
20298 (BWDREF_FRAME, ALTREF_FRAME)
20299 } else {
20300 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
20301 if p1 == 1 {
20302 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
20303 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
20304 if p2 == 1 {
20305 (LAST_FRAME, GOLDEN_FRAME)
20306 } else {
20307 (LAST_FRAME, LAST3_FRAME)
20308 }
20309 } else {
20310 (LAST_FRAME, LAST2_FRAME)
20311 }
20312 }
20313 } else {
20314 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
20315 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
20316 let ref0 = if bit0 == 0 {
20317 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
20318 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
20319 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
20320 } else {
20321 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
20322 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
20323 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
20324 };
20325 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
20326 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
20327 let ref1 = if bit1 == 0 {
20328 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
20329 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
20330 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
20331 } else {
20332 ALTREF_FRAME
20333 };
20334 (ref0, ref1)
20335 }
20336}
20337
20338/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
20339/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
20340/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
20341/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
20342/// libaom's `av1_mode_context_analyzer`'s compound branch --
20343/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
20344/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
20345/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
20346/// is not yet turned into an assigned MV pair or motion-compensated --
20347/// lane-av1comp.
20348fn read_inter_compound_mode(
20349 dec: &mut SymbolDecoder,
20350 cdfs: &mut Cdfs,
20351 new_mv_ctx: usize,
20352 ref_mv_ctx: usize,
20353) -> u8 {
20354 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
20355 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
20356 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
20357}
20358
20359/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
20360/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
20361/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
20362/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
20363/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
20364/// non-`IDENTITY` global motion model before a tile is ever decoded.
20365///
20366/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
20367/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
20368/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
20369/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
20370/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
20371fn assign_compound_mv(
20372 dec: &mut SymbolDecoder,
20373 cdfs: &mut Cdfs,
20374 comp_stack: &crate::mvstack::CompoundMvStack,
20375 mode: u8,
20376 allow_high_precision_mv: bool,
20377 force_integer_mv: bool,
20378 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
20379 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
20380 global_mv: ((i32, i32), (i32, i32)),
20381) -> ((i32, i32), (i32, i32)) {
20382 const NEAREST_NEARESTMV: u8 = 0;
20383 const NEAR_NEARMV: u8 = 1;
20384 const NEAREST_NEWMV: u8 = 2;
20385 const NEW_NEARESTMV: u8 = 3;
20386 const NEAR_NEWMV: u8 = 4;
20387 const NEW_NEARMV: u8 = 5;
20388 const GLOBAL_GLOBALMV: u8 = 6;
20389 const NEW_NEWMV: u8 = 7;
20390
20391 let mut ref_mv_idx = 0usize;
20392 if mode == NEW_NEWMV {
20393 let mut idx = 0usize;
20394 while idx < 2 && comp_stack.entries.len() > idx + 1 {
20395 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
20396 break;
20397 }
20398 idx += 1;
20399 }
20400 ref_mv_idx = idx;
20401 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
20402 let mut idx = 1usize;
20403 while idx < 3 && comp_stack.entries.len() > idx + 1 {
20404 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
20405 break;
20406 }
20407 idx += 1;
20408 }
20409 ref_mv_idx = idx - 1;
20410 }
20411
20412 let near = comp_stack
20413 .entries
20414 .get(ref_mv_idx + 1)
20415 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
20416 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
20417 ref_mv_idx + 1
20418 } else {
20419 ref_mv_idx
20420 };
20421 let new_pred = comp_stack
20422 .entries
20423 .get(new_idx)
20424 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
20425
20426 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
20427 read_mv(
20428 dec,
20429 &mut cdfs.mv_comp,
20430 &mut cdfs.mv_joint,
20431 base,
20432 allow_high_precision_mv,
20433 force_integer_mv,
20434 )
20435 };
20436
20437 match mode {
20438 NEAREST_NEARESTMV => comp_stack.nearest_mv,
20439 NEAR_NEARMV => near,
20440 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
20441 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
20442 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
20443 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
20444 GLOBAL_GLOBALMV => global_mv,
20445 _ => (
20446 read_new(dec, cdfs, new_pred.0),
20447 read_new(dec, cdfs, new_pred.1),
20448 ),
20449 }
20450}
20451
20452/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
20453/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
20454/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
20455/// table is always computed at the *querying* block's position, never a
20456/// donating neighbour's).
20457fn build_gm_mv_table(
20458 global_motion: &[ec_av1_syntax::WarpParams; 7],
20459 mi_row: usize,
20460 mi_col: usize,
20461 bw4: usize,
20462 bh4: usize,
20463 allow_high_precision_mv: bool,
20464 force_integer_mv: bool,
20465) -> crate::mvstack::GmMvTable {
20466 std::array::from_fn(|i| {
20467 let gm = &global_motion[i];
20468 crate::warp::gm_get_motion_vector(
20469 gm.model,
20470 &gm.params,
20471 mi_row,
20472 mi_col,
20473 bw4,
20474 bh4,
20475 allow_high_precision_mv,
20476 force_integer_mv,
20477 )
20478 })
20479}
20480
20481/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
20482/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
20483/// and motion-compensated reconstruction, or the inter frame's own intra
20484/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
20485/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
20486/// private `write_inter_frame_leaf` -- both share this one function here,
20487/// parameterised by `side`/the transform sets/scan tables/size group they
20488/// each use.
20489///
20490/// # Errors
20491/// Returns an error when a symbol names anything this decoder does not
20492/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
20493/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
20494/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
20495/// refuse.
20496#[allow(clippy::too_many_arguments)]
20497/// lane-inter4 r1: 16-px-cell coordinates -> MI (4-px) coordinates, the unit
20498/// [`decode_inter_block`]'s `at` now takes.
20499const fn sub16_to_mi(t: (usize, usize)) -> (usize, usize) {
20500 (t.0 * (SUB / MI), t.1 * (SUB / MI))
20501}
20502
20503fn decode_inter_block(
20504 dec: &mut SymbolDecoder,
20505 cdfs: &mut Cdfs,
20506 neighbours: &mut Neighbours,
20507 grid: &mut MiGrid,
20508 at: (usize, usize),
20509 side: usize,
20510 mi_cols: u32,
20511 mi_rows: u32,
20512 y: &mut PlaneBuf,
20513 u: &mut PlaneBuf,
20514 v: &mut PlaneBuf,
20515 ref_y: &PlaneBuf,
20516 ref_u: &PlaneBuf,
20517 ref_v: &PlaneBuf,
20518 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
20519 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
20520 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
20521 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
20522 // slot's still empty (an error-resilient stream, or too early in the
20523 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
20524 other_refs: &RefSlots,
20525 sign_bias_table: &SignBiasTable,
20526 // lane-gm r2: this frame header's own `global_motion` table (spec
20527 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
20528 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
20529 // assignment and the mv-stack's neighbour substitution.
20530 global_motion: &[ec_av1_syntax::WarpParams; 7],
20531 base_q_idx: u8,
20532 luma_set_intra: TxbSet,
20533 luma_set_inter: TxbSet,
20534 chroma_set: TxbSet,
20535 luma_tx: usize,
20536 chroma_tx: usize,
20537 scan_luma: &[u16],
20538 scan_chroma: &[u16],
20539 // lane-inter4 r3: superseded by `size_group_wh(write_w, write_h)` at the
20540 // one site that read it (`y_mode`) -- a rect strip's group comes from its
20541 // true footprint, not the caller's square `side`. Kept in the signature
20542 // rather than editing twenty call sites.
20543 _size_group: usize,
20544 allow_high_precision_mv: bool,
20545 force_integer_mv: bool,
20546 interp_fixed: Option<mc::InterpFilterKind>,
20547 enable_dual_filter: bool,
20548 tpl_frame: Option<&TplFrameArgs>,
20549 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
20550 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
20551 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
20552 // refuses (rather than silently misdecoding) the ones that pick
20553 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
20554 // wired yet.
20555 reference_select: bool,
20556 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
20557 // compound enable bits, gating `comp_group_idx`/`compound_idx`
20558 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
20559 // compound blend weights need this frame's own order hint regardless
20560 // of `use_ref_frame_mvs`.
20561 enable_masked_compound: bool,
20562 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
20563 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
20564 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
20565 // and before `read_motion_mode` on the single-ref path below, gated by
20566 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
20567 // every mode this single-ref branch can produce is already in
20568 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
20569 // (inter+intra blended prediction unimplemented) rather than a
20570 // mis-decode.
20571 enable_interintra_compound: bool,
20572 enable_jnt_comp: bool,
20573 order_hint_bits: u32,
20574 order_hint: u32,
20575 ref_order_hints: [u32; 7],
20576 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
20577 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
20578 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
20579 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
20580 // when this is `true` (every block this decoder reaches is >= 8x8, so
20581 // `is_comp_ref_allowed` never gates it further); a `true` result forces
20582 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
20583 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
20584 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
20585 skip_mode_present: bool,
20586 skip_mode_frame: [u8; 2],
20587 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
20588 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
20589 switchable_motion_mode: bool,
20590 allow_warped_motion: bool,
20591 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
20592 // as a square 32x32 block, which over-reads a residual unless coded
20593 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
20594 reject_residual: bool,
20595 // lane-partitions r1: the strip's own true width/height in pixels --
20596 // `side` keeps governing every syntax/CDF/prediction-buffer decision
20597 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
20598 // the final pixel write and this block's own neighbour-context stamp
20599 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
20600 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
20601 // for every existing (square) caller.
20602 write_w: usize,
20603 write_h: usize,
20604 // lane-screen r2: this frame header's own `allow_screen_content_tools`
20605 // bit, threaded to the intra-sub-block branch below -- libaom's
20606 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
20607 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
20608 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
20609 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
20610 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
20611 // under the same `av1_allow_palette` gate as the key-frame path.
20612 allow_screen_content_tools: bool,
20613 // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) --
20614 // compared against each reference's stored picture width to decide
20615 // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary
20616 // stride-1 one (`mc::predict_with_filters`) applies per reference, and to
20617 // refuse (rather than mis-decode) the warp/OBMC/interintra/compound
20618 // combinations that don't implement scaled MC yet.
20619 frame_width: usize,
20620) -> Result<()> {
20621 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can
20622 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the
20623 // few 16-px-granular uses below.
20624 let (r, c) = (at.0 / (SUB / MI), at.1 / (SUB / MI));
20625 // lane-inter8 r2: the inter side bands are mi-granular; this block's own
20626 // above/left neighbour is the mi cell at its top-left corner (libaom
20627 // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads
20628 // exactly what it read before.
20629 let (rmi, cmi) = at;
20630 let (px, py) = (at.1 * MI, at.0 * MI);
20631 census_inter_block_shape(side, write_w, write_h);
20632 // lane-inter16ab r2: a 16x4 / 4x16 inter strip's chroma is the PAIR's
20633 // (8x4 / 4x8 at the even strip's origin) and is coded only by the odd
20634 // strip (`is_chroma_reference`); every other block keeps its own.
20635 let strip_chroma = INTER_STRIP_CHROMA.with(std::cell::Cell::take);
20636 INTER_LAST_MC.with(|c| c.set(None));
20637 let has_chroma = strip_chroma.is_none_or(|s| s.has_chroma);
20638 let (cpx, cpy) = match strip_chroma {
20639 Some(s) if s.has_chroma => (s.pair_mi.1 * MI / 2, s.pair_mi.0 * MI / 2),
20640 _ => (px / 2, py / 2),
20641 };
20642 let chroma_side = side / 2;
20643 let (write_chroma_w, write_chroma_h) = match strip_chroma {
20644 Some(s) if s.has_chroma => {
20645 if s.horz {
20646 (8, 4)
20647 } else {
20648 (4, 8)
20649 }
20650 }
20651 _ => (write_w / 2, write_h / 2),
20652 };
20653 // lane-midcut r3 (same rule as lane-t900 r5's `warp_plane_allowed`, one
20654 // copy kept at the merge): `av1_init_warp_params` (libaom reconinter.c)
20655 // bails per PLANE at `block_width < 8 || block_height < 8` -- on the
20656 // block's own dims, never on the square prediction buffer this reader
20657 // allocates.
20658 if crate::envflags::env_flag!("EC_MC_TRACE") {
20659 eprintln!("EC_IB px={px} py={py} side={side} w={write_w} h={write_h}");
20660 }
20661
20662 if crate::envflags::env_flag!("EC_AV1_TELL") {
20663 eprintln!(
20664 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
20665 rmi, cmi, dec.debug_bitpos(), dec.debug_state().0
20666 );
20667 }
20668 let skip_mode_ctx =
20669 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
20670 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
20671 // MSAC tell so it can be diffed against an equivalent hook in libaom's
20672 // own `read_skip_mode`/`av1_get_skip_mode_context`.
20673 if crate::envflags::env_flag!("EC_AV1_SKIPMODE_DUMP") {
20674 eprintln!(
20675 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
20676 dec.debug_bitpos()
20677 );
20678 }
20679 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
20680 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
20681 let (seg_mi_r, seg_mi_c) = (rmi, cmi);
20682 let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
20683 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
20684 // libaom `read_skip_mode` (decodemv.c): `if (!is_comp_ref_allowed(bsize))
20685 // return 0` -- a 16x4 / 4x16 strip (min(bw, bh) == 4, blockd.h:65) reads
20686 // no `skip_mode` symbol at all.
20687 let comp_allowed = write_w.min(write_h) >= 8;
20688 let skip_mode =
20689 skip_mode_present && comp_allowed && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
20690 if crate::envflags::env_flag!("EC_AV1_SKIPMODE_DUMP") {
20691 eprintln!(
20692 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
20693 dec.debug_bitpos()
20694 );
20695 }
20696 if skip_mode {
20697 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
20698 }
20699
20700 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
20701 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
20702 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
20703 maybe_read_cdef_idx(dec, rmi, cmi, skip);
20704 // lane-inter4 r1: spec 5.11.6's `bSize == sbSize` -- a 64x32/64x16 strip
20705 // is NOT the whole superblock, so its `skip` never suppresses the read.
20706 // lane-sb128c r7: `sbSize` is 128 under `--sb-size=128`, so the whole-block
20707 // test is against the sequence's own superblock side, not a hardcoded 64.
20708 let sb_px = sb_mi_cur() as usize * 4;
20709 let whole_sb = side == sb_px && write_w == sb_px && write_h == sb_px;
20710 maybe_read_delta_q(dec, cdfs, rmi, cmi, whole_sb, skip);
20711 maybe_read_delta_lf(dec, cdfs, rmi, cmi, whole_sb, skip);
20712 let (has_above, has_left) = (
20713 rmi > neighbours.tile_row0_mi,
20714 cmi > neighbours.tile_col0_mi,
20715 );
20716 let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]);
20717 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
20718 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
20719 // lane-sb128c r1: this round wires the INTER half of a 128x128 block (four
20720 // TX_64X64 luma units and four TX_32X32 chroma units interleaved per mu
20721 // chunk). An INTRA block at that size inside an inter frame takes the
20722 // intra tail below, which still codes one whole-block chroma unit and one
20723 // `read_tx_size` at 128 -- refuse by name instead of mis-decoding it.
20724 if crate::envflags::env_flag!("EC_TRACE_MODE") {
20725 eprintln!(
20726 "EC_MODE mi_row={} mi_col={} rng={} is_inter={} skip={} side={side}",
20727 rmi,
20728 cmi,
20729 dec.debug_state().0,
20730 u8::from(is_inter),
20731 u8::from(skip)
20732 );
20733 }
20734 // lane-warp r5: see `reject_residual` -- a square-block decode of a
20735 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
20736 // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just
20737 // after the `skip` read to here, past `is_inter` (class
20738 // [[refusal-short-circuits-its-own-code]]: at the old place it refused
20739 // 24/24 attempts of this lane's own gate before the intra arm below
20740 // could run). An INTRA strip with its true `write_w`x`write_h` footprint
20741 // now codes its residual rectangularly ([`decode_intra_rect_in_inter`]);
20742 // an INTER one, and a strip decoded with square dimensions anyway, still
20743 // cannot.
20744 // merge b51719f+lane-intrarect: main's `rect_inter_residual_supported`
20745 // term stays -- lane-inter4's 16x8/8x16 inter leaves DO code a
20746 // rectangular residual, and the lane's condition (written before that
20747 // landed) refused every one of them.
20748 if reject_residual
20749 && !skip
20750 && !rect_inter_residual_supported(write_w, write_h)
20751 && (is_inter || (write_w == side && write_h == side))
20752 {
20753 if crate::envflags::env_flag!("EC_RECTRES") {
20754 eprintln!(
20755 "EC_RECTRES w={write_w} h={write_h} side={side} skip={} is_inter={} mi_row={rmi} mi_col={cmi}",
20756 u8::from(skip),
20757 u8::from(is_inter)
20758 );
20759 }
20760 return Err(unsupported(
20761 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
20762 ));
20763 }
20764 if crate::envflags::env_flag!("EC_AV1_TELL") {
20765 eprintln!(
20766 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
20767 rmi, cmi, dec.debug_bitpos(), dec.debug_state().0
20768 );
20769 }
20770
20771 let mode_for_tx;
20772 let uv_predict_mode;
20773 let (luma_grid, u_grid, v_grid);
20774 let block_filter;
20775 let ref_frame_for_lf;
20776 let globalmv_for_lf;
20777 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
20778 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
20779 // common `record_inter` call below (which would otherwise stamp the
20780 // single-ref ALTREF-special-case default over it).
20781 let mut compound_ctx: Option<(i8, u8, u8)> = None;
20782 // lane-txselect: `read_block_tx_size`'s leaf transform units (spec
20783 // 5.11.17), `Some` only when this block's var-tx tree resolved to more
20784 // than one luma transform -- read back by the residual loop, the
20785 // coefficient-context write-back and the loop-filter grid fill below.
20786 let mut vartx_leaves: Option<Vec<(usize, usize, usize, usize)>> = None;
20787 // lane-t900 r22: this block's own palette state, stamped into the
20788 // mi-granular neighbour bands at the tail below for EVERY block --
20789 // libaom's `MB_MODE_INFO.palette_size` is 0 on an inter block, and
20790 // `av1_get_palette_cache`/`av1_get_palette_mode_ctx` read those cells, so
20791 // leaving a previous palette block's colours standing here would feed the
20792 // next intra block a cache libaom never builds.
20793 let mut palette_record: (usize, [u16; 8], usize, [u16; 8]) = (0, [0u16; 8], 0, [0u16; 8]);
20794 let at_mi = at;
20795 // lane-vert46 r1: set when this block's chroma was coded as one 32x32 unit
20796 // per 64x64 "mu" chunk (any side above 64), so the end-of-block record
20797 // below must NOT re-stamp the chroma neighbour context from the assembled
20798 // whole-block grid.
20799 let mut mu_chroma = false;
20800 if is_inter {
20801 let above_nbr = has_above.then(|| NeighbourRef {
20802 is_inter: above_inter,
20803 ref0: if above_inter {
20804 neighbours.above_ref[cmi]
20805 } else {
20806 0
20807 },
20808 ref1: neighbours.above_ref1[cmi],
20809 uni: neighbours.above_ref1[cmi]
20810 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[cmi], r1)),
20811 });
20812 let left_nbr = has_left.then(|| NeighbourRef {
20813 is_inter: left_inter,
20814 ref0: if left_inter {
20815 neighbours.left_ref[rmi]
20816 } else {
20817 0
20818 },
20819 ref1: neighbours.left_ref1[rmi],
20820 uni: neighbours.left_ref1[rmi]
20821 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
20822 });
20823 if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") {
20824 eprintln!(
20825 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
20826 dec.debug_bitpos()
20827 );
20828 }
20829 let is_compound =
20830 skip_mode
20831 || (reference_select
20832 // `is_comp_ref_allowed` (blockd.h:65) gates the
20833 // `comp_mode` read exactly as it gates `skip_mode`.
20834 && comp_allowed
20835 && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
20836 if is_compound {
20837 let (ref0, ref1) = if skip_mode {
20838 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
20839 } else {
20840 read_compound_ref_frames(
20841 dec,
20842 cdfs,
20843 above_nbr,
20844 left_nbr,
20845 neighbours.above_ref[cmi],
20846 neighbours.left_ref[rmi],
20847 )
20848 };
20849 let (mi_row, mi_col) = (rmi, cmi);
20850 // lane-rect r2: true footprint, mirroring the single-ref path below.
20851 let bw4 = write_w / 4;
20852 let bh4 = write_h / 4;
20853 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
20854 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
20855 // below, just one `get_relative_dist` per reference.
20856 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
20857 field: t.field,
20858 cur_offset_0: crate::motion_field::get_relative_dist(
20859 t.order_hint_bits,
20860 t.order_hint,
20861 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
20862 ),
20863 cur_offset_1: crate::motion_field::get_relative_dist(
20864 t.order_hint_bits,
20865 t.order_hint,
20866 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
20867 ),
20868 allow_high_precision_mv,
20869 });
20870 let gm_table = build_gm_mv_table(
20871 global_motion,
20872 mi_row,
20873 mi_col,
20874 bw4,
20875 bh4,
20876 allow_high_precision_mv,
20877 force_integer_mv,
20878 );
20879 let comp_stack = crate::mvstack::find_mv_stack_compound(
20880 grid,
20881 mi_row,
20882 mi_col,
20883 bw4,
20884 bh4,
20885 (ref0, ref1),
20886 mi_cols as usize,
20887 mi_rows as usize,
20888 sign_bias_table,
20889 &gm_table,
20890 comp_tpl,
20891 );
20892 let compound_mode = if skip_mode {
20893 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
20894 } else {
20895 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
20896 };
20897 let (mv0, mv1) = assign_compound_mv(
20898 dec,
20899 cdfs,
20900 &comp_stack,
20901 compound_mode,
20902 allow_high_precision_mv,
20903 force_integer_mv,
20904 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
20905 );
20906 if crate::envflags::env_flag!("EC_TRACE_MODE") {
20907 eprintln!(
20908 "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={} ref0={ref0} ref1={ref1} mv0=({},{}) stack={} rng={}",
20909 compound_mode + 17,
20910 mv0.0,
20911 mv0.1,
20912 comp_stack.entries.len(),
20913 dec.debug_state().0
20914 );
20915 for (i, e) in comp_stack.entries.iter().enumerate() {
20916 eprintln!(
20917 "EC_STACK mi_row={mi_row} mi_col={mi_col} i={i} this=({},{}) comp=({},{}) w={}",
20918 e.mv0.0, e.mv0.1, e.mv1.0, e.mv1.1, e.weight
20919 );
20920 }
20921 }
20922 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
20923 // spec `is_nontrans_global_motion`: ALL active refs' models must
20924 // be non-TRANSLATION (IDENTITY counts) for the compound block's
20925 // interp-filter read to be suppressed.
20926 let gm_nontrans_models = is_globalmv
20927 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
20928 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
20929 // lane-t900 r9: `is_nontrans_global_motion` bails at
20930 // `AOMMIN(mi_size_wide, mi_size_high) < 2` before it looks at any
20931 // model, so a 4-px-sided block still reads its interp filter.
20932 let gm_nontrans = gm_nontrans_models && bw4.min(bh4) >= 2;
20933 if gm_nontrans_models && !gm_nontrans {
20934 GM_NONTRANS_SMALL_SIDE_HITS.with(|c| c.set(c.get() + 1));
20935 }
20936 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
20937 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
20938 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
20939 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
20940 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
20941 // the write extent below, so recompute the size bound from
20942 // `side` here (the block's own size, what libaom's `bsize`
20943 // is).
20944 let is_global_mv0 = is_globalmv
20945 && side >= 8
20946 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1;
20947 let is_global_mv1 = is_globalmv
20948 && side >= 8
20949 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1;
20950 // libaom `av1_init_warp_params` + `allow_warp`'s
20951 // `global_warp_allowed` branch, run once per reference for a
20952 // compound block exactly as for a single-ref one (reconinter.c
20953 // `build_inter_predictors_8x8_and_bigger` loops over `ref` and
20954 // calls `av1_init_warp_params` inside the loop) -- WARPED_CAUSAL
20955 // never reaches here (spec 5.11.27 / libaom `read_motion_mode`:
20956 // `has_second_ref` returns SIMPLE_TRANSLATION), so the local-warp
20957 // arm of `allow_warp` is dead on this path and only the global
20958 // one applies. `force_integer_mv` short-circuits
20959 // `av1_init_warp_params` before `allow_warp`.
20960 let compound_warp = |ref_frame: i8, eligible: bool| {
20961 if eligible
20962 && !force_integer_mv
20963 && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid
20964 {
20965 crate::warp::global_warp_params(
20966 global_motion[(ref_frame - LAST_FRAME) as usize].params,
20967 )
20968 } else {
20969 None
20970 }
20971 };
20972 let warp0 = compound_warp(ref0, is_global_mv0);
20973 let warp1 = compound_warp(ref1, is_global_mv1);
20974 if warp0.is_some() || warp1.is_some() {
20975 COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1));
20976 }
20977 // spec `get_ref_filter_type`: matches when EITHER of the
20978 // neighbour's two references equals this block's own ref0 --
20979 // `above_ref1`/`left_ref1` is the neighbour's real second
20980 // reference (`record_compound_ctx`) when it was itself a
20981 // compound block; checking `above_ref`/`left_ref` alone drops a
20982 // real filter match down to the "no neighbour" sentinel
20983 // whenever the shared reference sits in the neighbour's SECOND
20984 // slot (lane-av1idx r2).
20985 let above_filter_ctx = if neighbours.above_ref[cmi] == ref0
20986 || neighbours.above_ref1[cmi] == Some(ref0)
20987 {
20988 neighbours.above_filter[cmi]
20989 } else {
20990 [3, 3]
20991 };
20992 let left_filter_ctx = if neighbours.left_ref[rmi] == ref0
20993 || neighbours.left_ref1[rmi] == Some(ref0)
20994 {
20995 neighbours.left_filter[rmi]
20996 } else {
20997 [3, 3]
20998 };
20999 globalmv_for_lf = is_globalmv;
21000 ref_frame_for_lf = ref0;
21001 mode_for_tx = 0;
21002 uv_predict_mode = DC_PRED;
21003 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
21004 // `neighbours`) must be stamped with the block's true footprint
21005 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
21006 // NEXT strip's own rows/cols before it decodes, corrupting
21007 // every later mvstack scan that reads this cell back.
21008 for dr in 0..bh4 {
21009 for dc in 0..bw4 {
21010 grid.set(
21011 mi_row + dr,
21012 mi_col + dc,
21013 MiInfo {
21014 is_inter: true,
21015 ref_frame: ref0,
21016 ref_frame1: Some(ref1),
21017 mv1: Some(mv1),
21018 mv: mv0,
21019 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
21020 size: bw4,
21021 size_h: bh4,
21022 // libaom `is_global_mv_block`: per-ref-slot, mode
21023 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
21024 // own gm model > TRANSLATION (IDENTITY excluded
21025 // too -- the two-predicate trap, distinct from
21026 // `gm_nontrans` above which allows IDENTITY).
21027 is_global_mv0,
21028 is_global_mv1,
21029 },
21030 );
21031 }
21032 }
21033 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
21034 // masked compound / distance-weighted compound are actually
21035 // enabled for this stream -- `is_any_masked_compound_used_here`
21036 // is `true` for every block size this decoder ever reaches
21037 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
21038 // there), so the gate reduces to the sequence header bit; kept
21039 // as an explicit call so a future smaller block size is not
21040 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
21041 let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side);
21042 let comp_group_idx = if !skip_mode
21043 && enable_masked_compound
21044 && is_any_masked_compound_used_here(write_w, write_h)
21045 {
21046 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
21047 } else {
21048 0
21049 };
21050 if crate::envflags::env_flag!("EC_TRACE_MODE") {
21051 eprintln!(
21052 "EC_CGI mi_row={rmi} mi_col={cmi} ctx={group_ctx} val={comp_group_idx} rng={}",
21053 dec.debug_state().0
21054 );
21055 }
21056 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
21057 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
21058 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
21059 // when `comp_group_idx == 1`.
21060 let mut diffwtd_mask_type: Option<u8> = None;
21061 let mut wedge_mask: Option<&'static [u8]> = None;
21062 if comp_group_idx == 1 {
21063 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
21064 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
21065 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
21066 // `av1_wedge_params_lookup`) is true for every square bsize
21067 // this leaf reaches (8x8/16x16/32x32 all have
21068 // `wedge_types > 0`), so `compound_type` always reads a real
21069 // symbol here -- no alphabet collapse to worry about at this
21070 // block-size family.
21071 // lane-mcomp64 r1: `av1_is_wedge_used` is false at 64x64
21072 // (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`),
21073 // so libaom's `read_compound_type` (decodemv.c 1634-1656)
21074 // writes NO `compound_type` symbol there and INFERS
21075 // `COMPOUND_DIFFWTD` -- only the 1-bit `mask_type` literal
21076 // follows. `None` here is exactly that inferred arm.
21077 // lane-inter16ab r3: the row is this block's TRUE
21078 // `BLOCK_SIZES_ALL` index, not the enclosing square `side`'s
21079 // -- a 16x8 strip reads `compound_type_cdf[BLOCK_16X8]`.
21080 let wedge_bsize =
21081 bsize_all_index(write_w, write_h).filter(|_| wedge_used_bsize(write_w, write_h));
21082 let compound_type = match wedge_bsize {
21083 Some(b) => dec.symbol(&mut cdfs.compound_type[b]),
21084 None => 1,
21085 };
21086 if let Some(wedge_bsize) = wedge_bsize.filter(|_| compound_type == 0) {
21087 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
21088 // verified vs independent C dump (wedge.rs).
21089 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
21090 let wedge_sign = dec.literal(1);
21091 WEDGE_HITS.with(|c| c.set(c.get() + 1));
21092 if let Some(k) = rect_wedge_slot(write_w, write_h) {
21093 RECT_WEDGE_HITS.with(|c| {
21094 let mut a = c.get();
21095 a[k] += 1;
21096 c.set(a);
21097 });
21098 }
21099 // lane-inter16ab r5: the codebook row is this block's TRUE
21100 // footprint (`av1_wedge_params_lookup[bsize]`: hgtw for
21101 // h>w, hltw for h<w, plus that bsize's own signflip row).
21102 // Masks are padded to stride `max(bw,bh) == side`, so the
21103 // square blend below indexes them unchanged and the
21104 // padding never reaches the frame (only `write_w x
21105 // write_h` is written out).
21106 wedge_mask = Some(
21107 crate::wedge::wedge_masks()
21108 .codebook(write_w, write_h)
21109 .mask(wedge_sign as usize, wedge_index as usize),
21110 );
21111 } else {
21112 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
21113 let mask_type = dec.literal(1);
21114 diffwtd_mask_type = Some(mask_type as u8);
21115 if wedge_bsize.is_none() {
21116 DIFFWTD_INFERRED_HITS.with(|c| c.set(c.get() + 1));
21117 }
21118 }
21119 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
21120 if write_w != write_h {
21121 RECT_MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
21122 }
21123 }
21124 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
21125 // called this a `predict_compound_intermediate`/`combine_compound`
21126 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
21127 // unmasking and running the real gates
21128 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
21129 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
21130 // shows the plain-average blend is bit-exact *most of the time*
21131 // -- `combine_compound`'s two-shift-in-one round2 was proven
21132 // algebraically identical to libaom's separate
21133 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
21134 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
21135 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
21136 // the common case a lag-in-frames GOP's hidden altref frames
21137 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
21138 // for several consecutive frames.
21139 //
21140 // The real defect a live gate run isolated (seed 49,
21141 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
21142 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
21143 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
21144 // byte; decode-order frame 2 -- same shape, same zero MV, only
21145 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
21146 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
21147 // Every later frame up through decode-order 9 also mismatches,
21148 // *including* frame 8, whose four blocks are back to
21149 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
21150 // math is wrong" (that block's own math is proven exact) in
21151 // favour of "the picture sitting in some DPB slot is already
21152 // wrong by the time frame 2 reads it, and the corruption
21153 // propagates through refresh_frame_flags into every later
21154 // reference regardless of which named ref a later block picks".
21155 // Frames 10 through 18 (once the GOP's lineage stops tracing
21156 // back through the bad slot) are bit-exact again. This points at
21157 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
21158 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
21159 // indexing feeding `dist_wtd_comp_weight_assign`) around
21160 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
21161 // mc.rs. Not isolated further within lane-av1blend's budget --
21162 // refuse by name rather than ship a blend that is right only
21163 // sometimes. Ceiling: r13/r14's MC plumbing above this line
21164 // stays -- only the plain-average reconstruct is masked off
21165 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
21166 // per decode-order frame (which slot each `Frame` OBU refreshes,
21167 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
21168 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
21169 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
21170 // frame 2.
21171 //
21172 // r2 (fresh fixture, seed 45, same recipe -- the original r1
21173 // fixture is gitignored and could not be regenerated byte-exact):
21174 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
21175 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
21176 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
21177 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
21178 // is forced 0 on every non-key `show_existing_frame`) turned up
21179 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
21180 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
21181 // isolated a *different, smaller* shape than r1's: decode-order
21182 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
21183 // compound block) is the first to diverge from ffmpeg (worst
21184 // delta 1, luma only, clustered at 32-pixel block edges) even
21185 // though BOTH its compound inputs -- the key frame and
21186 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
21187 // itself proven bit-exact: it is later re-shown via
21188 // `show_existing_frame` and matches ffmpeg exactly) -- are
21189 // independently pixel-exact, and the blend arithmetic is the
21190 // same proven-exact formula. That rules out "wrong slot"/"stale
21191 // picture" for this fixture: the inputs are right, so the defect
21192 // is in decode-order frame 3's *own* per-block decode (entropy
21193 // desync from compound-CDF adaptation carried across a slot, or
21194 // the compound mode/MV read itself) -- not in `ref_slots`/
21195 // `refresh_frame_flags`. Not isolated further within budget.
21196 // Upgrade: bisect decode-order frame 3's tile decode against a
21197 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
21198 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
21199 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
21200 // -- the pre-deblock dump frame-index alignment between this
21201 // crate and that aomdec build is NOT 1:1 on this fixture (23
21202 // dumps here vs 24 there), so calibrate that first.
21203 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
21204 // against an instrumented aomdec build (frame-index alignment
21205 // recalibrated via content-hash matching rather than the raw
21206 // dump count -- the keyframe never calls a pre-deblock dump at
21207 // all, since only `decode_inter_frame_tile` does, which is the
21208 // whole "23 vs 24" gap, not a real bug).
21209 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
21210 // seed 45) is still the first divergence: PRE-deblock differs
21211 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
21212 // luma pixels, clustered where its two compound inputs' pixel
21213 // values disagree by more than a couple of levels -- both
21214 // inputs (the keyframe and decode-order frame 2's own picture)
21215 // are independently proven bit-exact (pre- and post-deblock)
21216 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
21217 // matches this decoder's block loop exactly for every block in
21218 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
21219 // every mismatching pixel against `key`/`bwd` (both known-exact)
21220 // picks out `w0=9, w1=7` for the majority (525/846) with zero
21221 // matches for the plain average this decoder actually emits or
21222 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
21223 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
21224 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
21225 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
21226 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
21227 // decoder's own `dist_wtd_comp_weight_assign` was independently
21228 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
21229 // by hand for these distances and gives the same `(9, 7)`).
21230 // `get_comp_index_context` was checked line-for-line against
21231 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
21232 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
21233 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
21234 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
21235 // `default_compound_idx_cdfs` value-for-value; the read is
21236 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
21237 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
21238 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
21239 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
21240 // either -- some blocks in this frame plausibly decode a
21241 // genuinely different (correct, context-dependent) compound_idx
21242 // than block (0,0)'s own -- so this is not simply "always wrong
21243 // the same way": table/context/gate are all individually
21244 // verified correct, yet the decoded VALUE at this specific
21245 // symbol is wrong at least once in this frame. Not isolated
21246 // further within budget. Upgrade: instrument `dec.symbol`'s own
21247 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
21248 // trace fields) immediately before and after the `compound_idx`
21249 // read specifically, not just the surrounding mode/mv/skip
21250 // trace which does match -- the desync (if any) is local to
21251 // this one read, not a wider stream desync.
21252 //
21253 // r5 (this round): the `resolve_interp_filter` call used to sit
21254 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
21255 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
21256 // `read_compound_type`, not before, so that was a genuine
21257 // ordering bug for a Switchable-filter frame (moved below, past
21258 // the `compound_ctx = Some(...)` line). It does NOT explain this
21259 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
21260 // header carries a *fixed* interpolation filter
21261 // (`interp_fixed = Some(Regular)`, confirmed live via a
21262 // one-off dump), so `resolve_interp_filter` never read a symbol
21263 // in either position -- zero bits moved, decoded values
21264 // unchanged before and after the reorder. Kept anyway: it is a
21265 // real spec-order fix for the next Switchable-filter compound
21266 // stream, independently correct regardless of this fixture.
21267 //
21268 // Also ruled out this round: comparing this crate's own
21269 // `SymbolDecoder::debug_bitpos()` against aomdec's
21270 // `aom_reader_tell()` at the block boundary is NOT a valid
21271 // desync probe -- they are different quantities (raw consumed
21272 // input bits vs. an entropy-cost estimate that advances without
21273 // a literal byte fetch), so equal/unequal bitpos proves nothing
21274 // either way. Do not repeat that comparison; instead trace
21275 // `range`/`value` (this crate) against libaom's own internal
21276 // `dif`/`rng` (needs new instrumentation in both) immediately
21277 // after each read *upstream* of this one in the same block:
21278 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
21279 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
21280 // and the DRL loop. All of those independently decoded the SAME
21281 // values this crate and aomdec both show (ref0=1, ref1=5, mode
21282 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
21283 // miscomputation can still decode the identical symbol value off
21284 // a slightly different CDF, narrowing `range` by a different
21285 // amount than aomdec without changing the decoded value itself,
21286 // and only surface as a wrong decode a few reads later exactly
21287 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
21288 // table were independently re-verified again this round and are
21289 // still correct; the four candidates above were not re-audited
21290 // this round. Refusing here (rather than shipping a value-exact-
21291 // most-of-the-time blend) until one of them is found wrong.
21292 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
21293 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
21294 // comp_bwdref* context reads -- kept, real fix). Unmasking on
21295 // that fix alone and running the wide gate sweep (many seeds,
21296 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
21297 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
21298 // cq-level=45) still mismatches roughly half the time, at
21299 // different frames each run for the SAME seed -- aomenc's own
21300 // cpu-used=0 RD search is run-to-run nondeterministic (noted
21301 // above), so this is a second, still-unfound compound_idx defect,
21302 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
21303 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
21304 // either) already flagged more than one bug here. Re-masking:
21305 // do not ship a blend that is right only sometimes.
21306 // lane-av1idx r1: fixed one real bug this round
21307 // (`switchable_interp_ctx` never folded in libaom's
21308 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
21309 // interp_filter context -- kept). Pinned
21310 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
21311 // gate) still mismatches after that fix (decode-order frame 8
21312 // first, small deltas, worst 1-2, propagating through later
21313 // frames via DPB reference) -- a second, still-unfound bug.
21314 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
21315 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
21316 // for the next round's starting point.
21317 // lane-maskcomp r2: `compound_idx` is only read when
21318 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
21319 // (wedge/diffwtd) block never also carries a distance-weighted
21320 // split. This gate was missing before r2 (dead code: the masked
21321 // path always refused earlier, so it never executed with
21322 // `comp_group_idx == 1` in practice).
21323 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
21324 && !skip_mode
21325 && enable_jnt_comp
21326 {
21327 let idx_ctx = get_comp_index_context(
21328 neighbours,
21329 (rmi, cmi),
21330 side,
21331 order_hint_bits,
21332 order_hint,
21333 ref_order_hints[(ref0 - LAST_FRAME) as usize],
21334 ref_order_hints[(ref1 - LAST_FRAME) as usize],
21335 );
21336 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
21337 if crate::envflags::env_flag!("EC_TRACE_MODE") {
21338 eprintln!(
21339 "EC_CIDX mi_row={rmi} mi_col={cmi} ctx={idx_ctx} val={idx} rng={}",
21340 dec.debug_state().0
21341 );
21342 }
21343 if idx == 1 {
21344 (8, 8, 1u8)
21345 } else {
21346 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
21347 order_hint_bits,
21348 order_hint,
21349 ref_order_hints[(ref0 - LAST_FRAME) as usize],
21350 ref_order_hints[(ref1 - LAST_FRAME) as usize],
21351 );
21352 (fwd, bck, 0u8)
21353 }
21354 } else {
21355 (8, 8, 1u8)
21356 };
21357 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
21358 if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") {
21359 eprintln!(
21360 "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={}",
21361 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
21362 );
21363 }
21364
21365 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
21366 // comes AFTER `read_compound_type` (the `comp_group_idx`/
21367 // `compound_idx` reads just above), not before -- moved here
21368 // (lane-av1blend r5) from its old position ahead of those reads,
21369 // which stole their bits for a Switchable-filter compound block
21370 // and desynced every symbol read after it in the tile.
21371 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
21372 // filter is derived (Regular), never read -- same
21373 // conditional-read contract as the WARPED_CAUSAL suppression on
21374 // the single-ref path below.
21375 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
21376 dec,
21377 cdfs,
21378 interp_fixed,
21379 enable_dual_filter,
21380 gm_nontrans || skip_mode,
21381 above_filter_ctx,
21382 left_filter_ctx,
21383 true,
21384 );
21385 block_filter = resolved_filter;
21386
21387 // lane-scaledref r1: each compound tap scales INDEPENDENTLY off
21388 // its own stored reference's luma width (spec 7.11.3.3 derives
21389 // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds
21390 // one `scale_factors` per `ref_frame`), so the two taps can carry
21391 // different ratios in the same block. `REF_NO_SCALE` reduces
21392 // `predict_compound_intermediate`'s walk to the ordinary
21393 // stride-1 one, so the unscaled case is unchanged.
21394 let scale0 = mc::scale_factor(py0.width, frame_width);
21395 let scale1 = mc::scale_factor(py1.width, frame_width);
21396 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
21397 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
21398 }
21399 // lane-scaledref r2: the MIXED case -- one tap scaled, the other
21400 // not -- is the one an all-frames-scaled recipe never produces,
21401 // and the one a single shared scale factor would get wrong.
21402 if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) {
21403 MIXED_SCALE_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
21404 }
21405
21406 let mut inter0_y = vec![0i32; side * side];
21407 mc::predict_compound_intermediate_kern(
21408 &py0.data,
21409 py0.width,
21410 py0.true_width,
21411 py0.true_height,
21412 mv_to_q4(px, mv0.1, true),
21413 mv_to_q4(py, mv0.0, true),
21414 scale0,
21415 side,
21416 side,
21417 write_w,
21418 write_h,
21419 h_filter,
21420 v_filter,
21421 &mut inter0_y,
21422 );
21423 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
21424 // translational tap (libaom `av1_warp_plane` with
21425 // `conv_params->is_compound`); the blend below is unchanged.
21426 if let Some(wp) = warp0.as_ref().filter(|_| warp_plane_allowed(write_w, write_h)) {
21427 crate::warp::warp_affine_compound(
21428 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
21429 py0.width as i32, &mut inter0_y, px as i32, py as i32, side as i32,
21430 side as i32, side as i32, 0, 0,
21431 );
21432 }
21433 let mut inter1_y = vec![0i32; side * side];
21434 mc::predict_compound_intermediate_kern(
21435 &py1.data,
21436 py1.width,
21437 py1.true_width,
21438 py1.true_height,
21439 mv_to_q4(px, mv1.1, true),
21440 mv_to_q4(py, mv1.0, true),
21441 scale1,
21442 side,
21443 side,
21444 write_w,
21445 write_h,
21446 h_filter,
21447 v_filter,
21448 &mut inter1_y,
21449 );
21450 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
21451 // translational tap (libaom `av1_warp_plane` with
21452 // `conv_params->is_compound`); the blend below is unchanged.
21453 if let Some(wp) = warp1.as_ref().filter(|_| warp_plane_allowed(write_w, write_h)) {
21454 crate::warp::warp_affine_compound(
21455 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
21456 py1.width as i32, &mut inter1_y, px as i32, py as i32, side as i32,
21457 side as i32, side as i32, 0, 0,
21458 );
21459 }
21460 let mut pred_y = vec![0u16; side * side];
21461 let mut diffwtd_mask_y = Vec::new();
21462 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
21463 // the wedge codebook lookup (comp_group_idx==1's two mutually
21464 // exclusive branches) -- same [`mc::blend_masked_compound`] call
21465 // either way, only the mask source differs.
21466 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
21467 diffwtd_mask_y = vec![0u8; side * side];
21468 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
21469 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
21470 Some(diffwtd_mask_y.as_slice())
21471 } else {
21472 wedge_mask
21473 };
21474 if let Some(mask_y) = mask_y {
21475 mc::blend_masked_compound(
21476 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
21477 );
21478 } else {
21479 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
21480 }
21481
21482 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
21483 mc::predict_compound_intermediate_kern(
21484 &pu0.data,
21485 pu0.width,
21486 pu0.true_width,
21487 pu0.true_height,
21488 mv_to_q4(cpx, mv0.1, false),
21489 mv_to_q4(cpy, mv0.0, false),
21490 scale0,
21491 chroma_side,
21492 chroma_side,
21493 write_chroma_w,
21494 write_chroma_h,
21495 h_filter,
21496 v_filter,
21497 &mut inter0_u,
21498 );
21499 // `av1_init_warp_params` bails when the PLANE's block is
21500 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
21501 // block of an 8x8 luma block stays translational.
21502 if let Some(wp) = &warp0 {
21503 if warp_plane_allowed(write_chroma_w, write_chroma_h) {
21504 crate::warp::warp_affine_compound(
21505 wp, &pu0.data, pu0.true_width as i32, pu0.true_height as i32,
21506 pu0.width as i32, &mut inter0_u, cpx as i32, cpy as i32,
21507 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
21508 );
21509 }
21510 }
21511 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
21512 mc::predict_compound_intermediate_kern(
21513 &pu1.data,
21514 pu1.width,
21515 pu1.true_width,
21516 pu1.true_height,
21517 mv_to_q4(cpx, mv1.1, false),
21518 mv_to_q4(cpy, mv1.0, false),
21519 scale1,
21520 chroma_side,
21521 chroma_side,
21522 write_chroma_w,
21523 write_chroma_h,
21524 h_filter,
21525 v_filter,
21526 &mut inter1_u,
21527 );
21528 // `av1_init_warp_params` bails when the PLANE's block is
21529 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
21530 // block of an 8x8 luma block stays translational.
21531 if let Some(wp) = &warp1 {
21532 if warp_plane_allowed(write_chroma_w, write_chroma_h) {
21533 crate::warp::warp_affine_compound(
21534 wp, &pu1.data, pu1.true_width as i32, pu1.true_height as i32,
21535 pu1.width as i32, &mut inter1_u, cpx as i32, cpy as i32,
21536 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
21537 );
21538 }
21539 }
21540 let mut pred_u = vec![0u16; chroma_side * chroma_side];
21541 if let Some(mask_y) = mask_y {
21542 mc::blend_masked_compound(
21543 &inter0_u,
21544 &inter1_u,
21545 mask_y,
21546 side,
21547 chroma_side,
21548 chroma_side,
21549 true,
21550 &mut pred_u,
21551 );
21552 } else {
21553 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
21554 }
21555
21556 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
21557 mc::predict_compound_intermediate_kern(
21558 &pv0.data,
21559 pv0.width,
21560 pv0.true_width,
21561 pv0.true_height,
21562 mv_to_q4(cpx, mv0.1, false),
21563 mv_to_q4(cpy, mv0.0, false),
21564 scale0,
21565 chroma_side,
21566 chroma_side,
21567 write_chroma_w,
21568 write_chroma_h,
21569 h_filter,
21570 v_filter,
21571 &mut inter0_v,
21572 );
21573 // `av1_init_warp_params` bails when the PLANE's block is
21574 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
21575 // block of an 8x8 luma block stays translational.
21576 if let Some(wp) = &warp0 {
21577 if warp_plane_allowed(write_chroma_w, write_chroma_h) {
21578 crate::warp::warp_affine_compound(
21579 wp, &pv0.data, pv0.true_width as i32, pv0.true_height as i32,
21580 pv0.width as i32, &mut inter0_v, cpx as i32, cpy as i32,
21581 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
21582 );
21583 }
21584 }
21585 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
21586 mc::predict_compound_intermediate_kern(
21587 &pv1.data,
21588 pv1.width,
21589 pv1.true_width,
21590 pv1.true_height,
21591 mv_to_q4(cpx, mv1.1, false),
21592 mv_to_q4(cpy, mv1.0, false),
21593 scale1,
21594 chroma_side,
21595 chroma_side,
21596 write_chroma_w,
21597 write_chroma_h,
21598 h_filter,
21599 v_filter,
21600 &mut inter1_v,
21601 );
21602 // `av1_init_warp_params` bails when the PLANE's block is
21603 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
21604 // block of an 8x8 luma block stays translational.
21605 if let Some(wp) = &warp1 {
21606 if warp_plane_allowed(write_chroma_w, write_chroma_h) {
21607 crate::warp::warp_affine_compound(
21608 wp, &pv1.data, pv1.true_width as i32, pv1.true_height as i32,
21609 pv1.width as i32, &mut inter1_v, cpx as i32, cpy as i32,
21610 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
21611 );
21612 }
21613 }
21614 let mut pred_v = vec![0u16; chroma_side * chroma_side];
21615 if let Some(mask_y) = mask_y {
21616 mc::blend_masked_compound(
21617 &inter0_v,
21618 &inter1_v,
21619 mask_y,
21620 side,
21621 chroma_side,
21622 chroma_side,
21623 true,
21624 &mut pred_v,
21625 );
21626 } else {
21627 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
21628 }
21629
21630 // lane-inter4 r2: a rectangular strip's transform tree starts from
21631 // its own rect `max_txsize_rect_lookup` entry, not a square one.
21632 let rect_tu = (write_w, write_h) != (side, side);
21633 vartx_leaves = if rect_tu {
21634 read_block_tx_size_rect(
21635 dec,
21636 cdfs,
21637 neighbours,
21638 at_mi,
21639 (write_w, write_h),
21640 (mi_cols as usize, mi_rows as usize),
21641 skip,
21642 )?
21643 } else {
21644 read_block_tx_size(
21645 dec,
21646 cdfs,
21647 neighbours,
21648 at_mi,
21649 side,
21650 (mi_cols as usize, mi_rows as usize),
21651 true,
21652 skip,
21653 )?
21654 .1
21655 };
21656 if skip {
21657 y.reconstruct_mc_rect(
21658 px,
21659 py,
21660 side,
21661 write_w,
21662 write_h,
21663 &pred_y,
21664 &vec![0i32; side * side],
21665 );
21666 u.reconstruct_mc_rect(
21667 cpx,
21668 cpy,
21669 chroma_side,
21670 write_chroma_w,
21671 write_chroma_h,
21672 &pred_u,
21673 &vec![0i32; chroma_side * chroma_side],
21674 );
21675 v.reconstruct_mc_rect(
21676 cpx,
21677 cpy,
21678 chroma_side,
21679 write_chroma_w,
21680 write_chroma_h,
21681 &pred_v,
21682 &vec![0i32; chroma_side * chroma_side],
21683 );
21684 luma_grid = vec![0i32; side * side];
21685 u_grid = vec![0i32; chroma_side * chroma_side];
21686 v_grid = vec![0i32; chroma_side * chroma_side];
21687 } else {
21688 // lane-inter4 r2: a rect strip's coefficient context spans its
21689 // OWN width above and height left -- reading `side` cells both
21690 // ways indexes past the tile's last mi row for a bottom strip.
21691 let around = if rect_tu {
21692 neighbours.around_mi_rect(at_mi, write_w, write_h)
21693 } else {
21694 neighbours.around_mi(at, side)
21695 };
21696 let luma_tx_type;
21697 // lane-sb128c r1: a 128x128 inter block's four chroma units
21698 // are read INSIDE the luma leaf loop (one per 64x64 mu chunk);
21699 // these collect them for the block-level neighbour write-back.
21700 let mut u_units = vec![0i32; chroma_side * chroma_side];
21701 let mut v_units = vec![0i32; chroma_side * chroma_side];
21702 if let Some(leaves) = vartx_leaves.clone() {
21703 // spec 5.11.17's transform tree, leaf by leaf in the order
21704 // `read_var_tx_size` coded it: each unit reads its own
21705 // coefficients against the neighbour magnitudes the
21706 // earlier units already wrote, and reconstructs over its
21707 // own slice of the block's motion-compensated predictor.
21708 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
21709 let mut first_tx_type = TxType::DctDct;
21710 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
21711 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
21712 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
21713 let (tu_grid, tu_tx_type) = if tw == th {
21714 let tx_px = tw;
21715 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
21716 for rr in 0..tx_px {
21717 let start = (row * MI + rr) * side + col * MI;
21718 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
21719 }
21720 let scan = default_scan(tx_px.min(32));
21721 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
21722 read_inter_plane(
21723 dec,
21724 cdfs,
21725 inter_txbset_for(tx_px, reduced),
21726 &scan,
21727 0,
21728 neighbours.around_mi(tu_mi, tx_px)[0],
21729 mode_for_tx,
21730 y,
21731 tu_px,
21732 tu_py,
21733 tx_px,
21734 base_q_idx,
21735 &tu_pred,
21736 None,
21737 Some(tu_skip_ctx),
21738 )?
21739 } else {
21740 // lane-r14 r3: a 1:4 strip's `sub_tx_size_map`
21741 // sub-transform is RECTANGULAR (TX_64X16 ->
21742 // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is
21743 // read with the rect coefficient machinery, at its
21744 // own `txb_skip_ctx`/neighbour spans -- the unit is
21745 // smaller than its block, so `get_txb_ctx_general`'s
21746 // neighbour table applies, not the lone-TU 0.
21747 vartx_rect_leaf_hit(tw, th);
21748 let tu_skip_ctx =
21749 neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
21750 let start = row * MI * side + col * MI;
21751 read_inter_plane_rect(
21752 dec,
21753 cdfs,
21754 rect_inter_luma_set(tw, th)?,
21755 (tw, th),
21756 side,
21757 0,
21758 neighbours.around_mi_rect(tu_mi, tw, th)[0],
21759 mode_for_tx,
21760 y,
21761 tu_px,
21762 tu_py,
21763 &pred_y[start..],
21764 None,
21765 Some(tu_skip_ctx),
21766 )?
21767 };
21768 if idx == 0 {
21769 first_tx_type = tu_tx_type;
21770 }
21771 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
21772 // lane-sb128c r1: libaom's `decode_token_recon_block`
21773 // walks 64x64 "mu" chunks (`mu_blocks_wide/high =
21774 // mi_size_wide[BLOCK_64X64]`) and codes EVERY PLANE of
21775 // a chunk before the next one, so a 128x128 block
21776 // interleaves Y,U,V per quadrant -- the same order the
21777 // intra 128 path reads (lane-sb128b r3, measured
21778 // against aomdec's `EC_TRACE_COEFF`). Below 128 a block
21779 // is a single chunk and this never fires.
21780 if side > 64 {
21781 let chunk = (row / 16, col / 16);
21782 let done = idx + 1 == leaves.len()
21783 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
21784 if done {
21785 let (cr, cc) = chunk;
21786 // `av1_get_max_uv_txsize(BLOCK_128X128)` =
21787 // `av1_get_adjusted_tx_size(TX_64X64)` =
21788 // TX_32X32: one 32x32 chroma unit per chunk.
21789 let cu_tx = 32usize;
21790 let luma_span = cu_tx * 2;
21791 let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16);
21792 let cu_around = neighbours.around_mi(cu_mi, luma_span);
21793 let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx);
21794 let cu_scan = default_scan(cu_tx);
21795 for plane_idx in 1..3 {
21796 let (src, buf) = if plane_idx == 1 {
21797 (&pred_u, &mut *u)
21798 } else {
21799 (&pred_v, &mut *v)
21800 };
21801 let mut cu_pred = Vec::with_capacity(cu_tx * cu_tx);
21802 for rr in 0..cu_tx {
21803 let start =
21804 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
21805 cu_pred.extend_from_slice(&src[start..start + cu_tx]);
21806 }
21807 let cu_grid = read_inter_plane(
21808 dec,
21809 cdfs,
21810 chroma_set,
21811 &cu_scan,
21812 plane_idx,
21813 cu_around[plane_idx],
21814 mode_for_tx,
21815 buf,
21816 cu_x,
21817 cu_y,
21818 cu_tx,
21819 base_q_idx,
21820 &cu_pred,
21821 Some(first_tx_type),
21822 Some(3),
21823 )?
21824 .0;
21825 // Immediately, so the NEXT chunk's unit
21826 // reads this one's coefficient context.
21827 neighbours.record_mi_chroma(
21828 cu_mi, luma_span, luma_span, plane_idx, &cu_grid,
21829 );
21830 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
21831 mu_chroma = true;
21832 let dst = if plane_idx == 1 {
21833 &mut u_units
21834 } else {
21835 &mut v_units
21836 };
21837 for rr in 0..cu_tx {
21838 let start =
21839 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
21840 dst[start..start + cu_tx]
21841 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
21842 }
21843 }
21844 }
21845 }
21846 }
21847 // `av1_get_tx_type`'s chroma lookup scales the chroma
21848 // position back to luma, so an inter block's chroma
21849 // inherits the *first* (top-left) luma unit's coded type.
21850 luma_tx_type = first_tx_type;
21851 luma_grid = vec![0i32; side * side];
21852 } else if rect_tu {
21853 // The whole-block rectangular transform unit
21854 // (`txfm_partition` said 0 at depth 0).
21855 let (grid, tx_type) = read_inter_plane_rect(
21856 dec,
21857 cdfs,
21858 rect_inter_luma_set(write_w, write_h)?,
21859 (write_w, write_h),
21860 side,
21861 0,
21862 around[0],
21863 mode_for_tx,
21864 y,
21865 px,
21866 py,
21867 &pred_y,
21868 None,
21869 None,
21870 )?;
21871 luma_tx_type = tx_type;
21872 luma_grid = embed_rect_grid(&grid, write_w, write_h, side);
21873 } else {
21874 (luma_grid, luma_tx_type) = read_inter_plane(
21875 dec,
21876 cdfs,
21877 luma_set_inter,
21878 scan_luma,
21879 0,
21880 around[0],
21881 mode_for_tx,
21882 y,
21883 px,
21884 py,
21885 side,
21886 base_q_idx,
21887 &pred_y,
21888 None,
21889 None,
21890 )?;
21891 }
21892 if side > 64 {
21893 // Already read inside the mu-chunk loop above -- at the 128
21894 // root a rect (128x64/64x128) block's chroma is per mu
21895 // chunk too, so this test comes BEFORE the `rect_tu` one.
21896 u_grid = std::mem::take(&mut u_units);
21897 v_grid = std::mem::take(&mut v_units);
21898 } else if rect_tu {
21899 // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a
21900 // 2:1 strip is the strip's own rect chroma size (16x8 /
21901 // 8x16), one unit for the whole block, and it codes no
21902 // `tx_type` symbol -- it inherits the luma unit's.
21903 let (uw, uh) = (write_chroma_w, write_chroma_h);
21904 u_grid = embed_rect_grid(
21905 &read_inter_plane_rect(
21906 dec,
21907 cdfs,
21908 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
21909 (uw, uh),
21910 chroma_side,
21911 1,
21912 around[1],
21913 mode_for_tx,
21914 u,
21915 cpx,
21916 cpy,
21917 &pred_u,
21918 Some(luma_tx_type),
21919 None,
21920 )?
21921 .0,
21922 uw,
21923 uh,
21924 chroma_side,
21925 );
21926 v_grid = embed_rect_grid(
21927 &read_inter_plane_rect(
21928 dec,
21929 cdfs,
21930 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
21931 (uw, uh),
21932 chroma_side,
21933 2,
21934 around[2],
21935 mode_for_tx,
21936 v,
21937 cpx,
21938 cpy,
21939 &pred_v,
21940 Some(luma_tx_type),
21941 None,
21942 )?
21943 .0,
21944 uw,
21945 uh,
21946 chroma_side,
21947 );
21948 } else {
21949 u_grid = read_inter_plane(
21950 dec,
21951 cdfs,
21952 chroma_set,
21953 scan_chroma,
21954 1,
21955 around[1],
21956 mode_for_tx,
21957 u,
21958 cpx,
21959 cpy,
21960 chroma_side,
21961 base_q_idx,
21962 &pred_u,
21963 Some(luma_tx_type),
21964 None,
21965 )?
21966 .0;
21967 v_grid = read_inter_plane(
21968 dec,
21969 cdfs,
21970 chroma_set,
21971 scan_chroma,
21972 2,
21973 around[2],
21974 mode_for_tx,
21975 v,
21976 cpx,
21977 cpy,
21978 chroma_side,
21979 base_q_idx,
21980 &pred_v,
21981 Some(luma_tx_type),
21982 None,
21983 )?
21984 .0;
21985 }
21986 }
21987 } else {
21988 let ref_frame =
21989 read_single_ref(
21990 dec,
21991 cdfs,
21992 neighbours.above_ref[cmi],
21993 neighbours.above_ref1[cmi],
21994 neighbours.left_ref[rmi],
21995 neighbours.left_ref1[rmi],
21996 );
21997 ref_frame_for_lf = ref_frame;
21998 if crate::envflags::env_flag!("EC_AV1_TELL") {
21999 let (mi_row, mi_col) = (rmi, cmi);
22000 eprintln!(
22001 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
22002 dec.debug_bitpos(), dec.debug_state().0
22003 );
22004 }
22005 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
22006 // stacked defects (lf_level ref/mode-delta forwarding, the
22007 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
22008 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
22009 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
22010 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
22011 // widens this from GOLDEN alone to every reference `read_single_ref`
22012 // can name.
22013 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
22014 (ref_y, ref_u, ref_v)
22015 } else {
22016 match other_refs[ref_frame as usize] {
22017 Some((ry, ru, rv)) => (ry, ru, rv),
22018 None => {
22019 return Err(unsupported(
22020 "a reference frame selected with no picture at this frame's own \
22021 ref_frame_idx slot for it",
22022 ));
22023 }
22024 }
22025 };
22026
22027 let (mi_row, mi_col) = (rmi, cmi);
22028 // lane-rect r2: the mv stack must be queried with the block's
22029 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
22030 // xd->width/xd->height, not a square guess) -- `write_w`/
22031 // `write_h` already name the true HORZ/VERT/HORZ_B strip
22032 // footprint (r1's plumbing), so derive bw4/bh4 from those
22033 // instead of the old `side`-square (HORZ_B-only) heuristic.
22034 let bw4 = write_w / 4;
22035 let bh4 = write_h / 4;
22036 // spec 7.10.2.8: only reached when the frame header set
22037 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
22038 // otherwise) -- `cur_offset_0` is this query block's own resolved
22039 // `ref_frame`'s distance from the current frame (spec 7.9.3),
22040 // recomputed per block since different blocks pick different refs.
22041 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
22042 field: t.field,
22043 cur_offset_0: crate::motion_field::get_relative_dist(
22044 t.order_hint_bits,
22045 t.order_hint,
22046 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
22047 ),
22048 allow_high_precision_mv,
22049 });
22050 let gm_table = build_gm_mv_table(
22051 global_motion,
22052 mi_row,
22053 mi_col,
22054 bw4,
22055 bh4,
22056 allow_high_precision_mv,
22057 force_integer_mv,
22058 );
22059 let stack = find_mv_stack_with_sign_bias(
22060 grid,
22061 mi_row,
22062 mi_col,
22063 bw4,
22064 bh4,
22065 ref_frame,
22066 mi_cols as usize,
22067 mi_rows as usize,
22068 sign_bias_table,
22069 &gm_table,
22070 tpl,
22071 );
22072 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
22073 let mut is_globalmv = false;
22074 // lane-interbis r1: which single-ref mode this block resolved to,
22075 // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for
22076 // the `EC_MODE_VAL` value ladder below.
22077 let mut dbg_mode = 16u32;
22078 let (mv, is_new_mv) = if !not_new {
22079 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
22080 // read at most two `drl_mode` bits, one per stack entry past the
22081 // first, stopping at the first `0`. The chosen index selects
22082 // which stack entry `read_mv`'s base predictor comes from
22083 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
22084 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
22085 let mut idx = 0usize;
22086 while idx < 2 && stack.entries.len() > idx + 1 {
22087 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
22088 break;
22089 }
22090 idx += 1;
22091 }
22092 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
22093 (
22094 read_mv(
22095 dec,
22096 &mut cdfs.mv_comp,
22097 &mut cdfs.mv_joint,
22098 base_mv,
22099 allow_high_precision_mv,
22100 force_integer_mv,
22101 ),
22102 true,
22103 )
22104 } else {
22105 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
22106 is_globalmv = !not_zero;
22107 let mv = if !not_zero {
22108 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
22109 // computed at this block's own position in `gm_table`.
22110 dbg_mode = 15;
22111 gm_table[(ref_frame - LAST_FRAME) as usize]
22112 } else {
22113 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
22114 dbg_mode = if nearest { 13 } else { 14 };
22115 if nearest {
22116 stack.nearest_mv
22117 } else {
22118 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
22119 // at 1): read at most two more `drl_mode` bits, one per stack
22120 // entry past the second, stopping at the first `0`.
22121 // `drl_ctx[idx]` is the context between `entries[idx]` and
22122 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
22123 // exactly the pair this index is choosing between.
22124 let mut idx = 1usize;
22125 while idx < 3 && stack.entries.len() > idx + 1 {
22126 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
22127 break;
22128 }
22129 idx += 1;
22130 }
22131 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
22132 }
22133 };
22134 (mv, false)
22135 };
22136 if crate::envflags::env_flag!("EC_TRACE_MODE") {
22137 for (i, e) in stack.entries.iter().enumerate() {
22138 eprintln!(
22139 "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}",
22140 e.mv.0, e.mv.1, e.weight
22141 );
22142 }
22143 eprintln!(
22144 "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={dbg_mode} ref0={ref_frame} ref1=-1 mv0=({},{}) stack={} rng={}",
22145 mv.0,
22146 mv.1,
22147 stack.entries.len(),
22148 dec.debug_state().0
22149 );
22150 }
22151 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
22152 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
22153 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
22154 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
22155 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
22156 // TRANSLATION -- IDENTITY counts here -- gating the interp
22157 // filter suppress below). Do NOT unify these.
22158 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
22159 let min_bw_bh4 = bw4.min(bh4);
22160 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
22161 let gm_nontrans =
22162 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
22163 if crate::envflags::env_flag!("EC_AV1_TELL") {
22164 eprintln!(
22165 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
22166 dec.debug_bitpos(), dec.debug_state().0
22167 );
22168 }
22169 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
22170 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
22171 // right after `assign_mv` and before `read_motion_mode` below --
22172 // libaom's own sequential order. `is_interintra_allowed_bsize`
22173 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
22174 // single-ref path: `is_interintra_allowed_ref` always holds here
22175 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
22176 // `is_interintra_allowed_mode` always holds (every mode this
22177 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
22178 // `SINGLE_INTER_MODE_START..END` by construction).
22179 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
22180 let mut interintra_mode: Option<u8> = None;
22181 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
22182 // lane-inter4 r1: `is_interintra_allowed_bsize` is
22183 // `BLOCK_8X8..=BLOCK_32X32` in libaom's enum ORDER, which excludes
22184 // every 1:4 shape (BLOCK_8X32 = 18, BLOCK_32X8 = 19) even though
22185 // both dimensions are in range -- reading this symbol on a 1:4
22186 // strip is a symbol the reference never wrote.
22187 let interintra_shape =
22188 write_w.max(write_h) <= 32 && write_w.max(write_h) / write_w.min(write_h) <= 2;
22189 if enable_interintra_compound
22190 && !skip_mode
22191 && (side == 16 || side == 32)
22192 && interintra_shape
22193 {
22194 // lane-inter4 r3: `size_group_lookup` reads the block's
22195 // TRUE footprint -- a 16x8 strip is group 1, a 32x16 strip
22196 // group 2, not their square `side`'s 2/3.
22197 let bsize_group = size_group_wh(write_w, write_h);
22198 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
22199 if interintra {
22200 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
22201 // then -- gated on block size ALONE, never the
22202 // `enable_interintra_wedge` seq bit -- the wedge flag
22203 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
22204 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
22205 // lane-inter16ab r3 (same class as the compound
22206 // `compound_type` row below): the row is the block's TRUE
22207 // `BLOCK_SIZES_ALL` index -- a 16x8 / 32x16 interintra
22208 // strip is BLOCK_16X8 / BLOCK_32X16, not its square
22209 // `side`'s BLOCK_16X16 / BLOCK_32X32.
22210 let wedge_bsize = bsize_all_index(write_w, write_h)
22211 .expect("interintra shape is a BLOCK_SIZES_ALL size");
22212 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
22213 if wedge {
22214 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
22215 // ADAPTING CDF symbol over the same `wedge_bsize` row;
22216 // NO sign symbol follows -- libaom fixes
22217 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
22218 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
22219 WII_HITS.with(|c| c.set(c.get() + 1));
22220 if let Some(k) = rect_wedge_slot(write_w, write_h) {
22221 RECT_WII_HITS.with(|c| {
22222 let mut a = c.get();
22223 a[k] += 1;
22224 c.set(a);
22225 });
22226 }
22227 // lane-inter16ab r5: true-footprint codebook row,
22228 // mask padded to stride `max(bw,bh) == side` -- see
22229 // the compound site's own comment.
22230 wedge_mask = Some((
22231 crate::wedge::wedge_masks()
22232 .codebook(write_w, write_h)
22233 .mask(0, wedge_index as usize),
22234 side,
22235 ));
22236 } else {
22237 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
22238 }
22239 interintra_mode = Some(ii);
22240 }
22241 }
22242 if crate::envflags::env_flag!("EC_AV1_TELL") {
22243 eprintln!(
22244 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
22245 dec.debug_bitpos(), dec.debug_state().0
22246 );
22247 }
22248 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
22249 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
22250 // placed right after MV assignment and before the switchable
22251 // interp filter read below (`read_mb_interp_filter`, decodemv.c
22252 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
22253 // (`reconinter.h`) reduces, for every block this single-ref path
22254 // reaches, to "does an inter neighbour border the above row or
22255 // left column": `is_motion_variation_allowed_bsize` always holds
22256 // (`side` is never below 16px on this path), `ref_frame[1] !=
22257 // INTRA_FRAME` always holds (no interintra reader here),
22258 // `is_motion_variation_allowed_compound` always holds (this is
22259 // the single-ref branch), and `is_global_mv_block` never
22260 // triggers (this decoder's global motion is always `IDENTITY`,
22261 // so its warp `type` is never `> TRANSLATION`). A stream with
22262 // `allow_warped_motion=1` is refused right at an eligible block
22263 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
22264 // not ported, so this decoder cannot tell a real
22265 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
22266 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
22267 // the header allows warp -- reading the wrong alphabet desyncs
22268 // the tile.
22269 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
22270 // fails libaom's `is_motion_variation_allowed_compound`: the
22271 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
22272 let motion_mode_eligible = switchable_motion_mode
22273 && !skip_mode
22274 // `is_motion_variation_allowed_bsize` (blockd.h:1455):
22275 // min(bw, bh) >= 8, false for a 16x4 / 4x16 strip.
22276 && write_w.min(write_h) >= 8
22277 && interintra_mode.is_none()
22278 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
22279 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
22280 .is_empty())
22281 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
22282 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
22283 // mv reads no motion_mode/obmc symbol at all -- implicit
22284 // SIMPLE_TRANSLATION.
22285 && !(is_global_mv_block && !force_integer_mv);
22286 // lane-t900 r9: the eligibility terms themselves, on the same rung
22287 // as aomdec's `EC_ISTEP2 name=motion_mode` -- an eligibility
22288 // mismatch is otherwise invisible (a skipped symbol prints
22289 // nothing).
22290 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
22291 eprintln!(
22292 "EC_MM mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={} \
22293 ab={} lf={} sw={} skipmode={} ii={} gmb={} rng={}",
22294 motion_mode_eligible as u8,
22295 overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).len(),
22296 overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1).len(),
22297 switchable_motion_mode as u8,
22298 skip_mode as u8,
22299 interintra_mode.is_some() as u8,
22300 is_global_mv_block as u8,
22301 dec.debug_state().0,
22302 );
22303 }
22304 let mut obmc_selected = false;
22305 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
22306 // *and* the local warp estimate is valid (`!wm_params.invalid`,
22307 // `av1_find_projection`) -- an invalid estimate falls back to
22308 // this block's own translational mv, same as any other block
22309 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
22310 // fallback here since this decoder's global motion is always
22311 // IDENTITY).
22312 let mut warp_params: Option<crate::warp::WarpParams> = None;
22313 // Tracks the SYMBOL value, not projection validity: libaom's
22314 // `av1_is_interp_needed` suppresses the interp-filter read for
22315 // `motion_mode == WARPED_CAUSAL` even when the projection later
22316 // falls back to translation. Its third suppressor,
22317 // `is_nontrans_global_motion`, matches our unconditional
22318 // `is_globalmv` only because this decoder codes global motion as
22319 // IDENTITY (non-TRANSLATION) and never reads switchable filters
22320 // below 8x8 -- porting TRANSLATION global motion must add the
22321 // wmtype check here.
22322 let mut warped_selected = false;
22323 if motion_mode_eligible {
22324 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
22325 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
22326 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
22327 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
22328 // strip motion_mode read diverged on the square row.
22329 // lane-inter4 r1: every rect shape this decoder can now
22330 // reach reads its OWN libaom bsize row (the packed order is
22331 // documented on `cdf::MOTION_MODE`); a wrong row is a wrong
22332 // interval narrowing, not a wrong value (class
22333 // wrong-alphabet-same-value).
22334 let bsize_idx = match (write_w, write_h) {
22335 // lane-sb128c r5: the 128 root's own rows come FIRST --
22336 // the square arm below maps 128 to row 4 (BLOCK_16X32).
22337 (64, 128) => 14,
22338 (128, 64) => 15,
22339 (128, 128) => 16,
22340 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
22341 (16, 32) => 4,
22342 (32, 16) => 5,
22343 (32, 64) => 6,
22344 (64, 32) => 7,
22345 (8, 32) => 8,
22346 (32, 8) => 9,
22347 (16, 64) => 10,
22348 (64, 16) => 11,
22349 // lane-inter4 r3: the 16x16-level rect inter leaves.
22350 (8, 16) => 12,
22351 (16, 8) => 13,
22352 _ => {
22353 return Err(unsupported(
22354 "a motion_mode symbol for a block shape with no CDF row here",
22355 ));
22356 }
22357 };
22358 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
22359 // instead of the 2-symbol `obmc_cdf` exactly when
22360 // `num_proj_ref >= 1` under `allow_warped_motion`.
22361 // lane-scaledref r2 + lane-fimv r1: libaom
22362 // `motion_mode_allowed` (`blockd.h:1484`) requires BOTH
22363 // `!av1_is_scaled(block_ref_scale_factors[0])` and
22364 // `!xd->cur_frame_force_integer_mv` for WARPED_CAUSAL --
22365 // under a scaled reference (superres) OR on a frame whose
22366 // header set `force_integer_mv` (screen content) the block
22367 // reads the 2-symbol `obmc_cdf`, never the 3-symbol
22368 // `motion_mode_cdf`. Reading the wrong alphabet here narrows
22369 // the arithmetic coder by the wrong amount and predicts the
22370 // rest of the tile off a diverged state: silently wrong
22371 // pixels, not a desync error. `force_integer_mv` is the
22372 // per-frame value (spec 5.9.2: coded per frame only when
22373 // `seq_force_integer_mv == SELECT_INTEGER_MV`, threaded from
22374 // `FrameHeader::force_integer_mv`).
22375 // libaom `av1_is_scaled` is `x_scale_fp != REF_NO_SCALE ||
22376 // y_scale_fp != REF_NO_SCALE`; the y half is unreachable here
22377 // because a reference whose height differs from this frame's
22378 // true size is refused before any tile decodes ("a reference
22379 // picture whose height does not match this frame's own true
22380 // size", ~14681). Whoever lifts that refusal adds the y term.
22381 let ref_is_scaled =
22382 mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE;
22383 let proj_ok = num_proj_ref(
22384 grid,
22385 mi_row,
22386 mi_col,
22387 bw4,
22388 bh4,
22389 mi_cols as usize,
22390 mi_rows as usize,
22391 ref_frame,
22392 ) >= 1;
22393 let warp_eligible =
22394 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
22395 if allow_warped_motion && proj_ok && ref_is_scaled {
22396 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1));
22397 }
22398 if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv {
22399 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
22400 }
22401 if warp_eligible {
22402 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
22403 match mode {
22404 0 => {}
22405 1 => {
22406 obmc_selected = true;
22407 OBMC_HITS.with(|c| c.set(c.get() + 1));
22408 }
22409 _ => {
22410 warped_selected = true;
22411 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
22412 let mut samples = find_samples(
22413 grid,
22414 mi_row,
22415 mi_col,
22416 bw4,
22417 bh4,
22418 mi_cols as usize,
22419 mi_rows as usize,
22420 ref_frame,
22421 );
22422 if crate::envflags::env_flag!("EC_WARP_DEBUG") {
22423 eprintln!(
22424 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
22425 samples.len()
22426 );
22427 for (i, s) in samples.iter().enumerate() {
22428 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
22429 }
22430 }
22431 if samples.len() > 1 {
22432 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
22433 }
22434 warp_params = crate::warp::find_projection(
22435 &samples,
22436 // lane-rect r2: the block's TRUE dims -- a
22437 // 32x16 strip's model center is not a
22438 // 32x32's (aom av1_find_projection bw/bh).
22439 write_w as i32,
22440 write_h as i32,
22441 mv.1,
22442 mv.0,
22443 mi_row as i32,
22444 mi_col as i32,
22445 );
22446 if crate::envflags::env_flag!("EC_WARP_DEBUG") {
22447 eprintln!(
22448 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
22449 samples.len(), mv.0, mv.1, warp_params
22450 );
22451 for (i, s) in samples.iter().enumerate() {
22452 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
22453 }
22454 }
22455 }
22456 }
22457 } else {
22458 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
22459 if obmc_selected {
22460 OBMC_HITS.with(|c| c.set(c.get() + 1));
22461 }
22462 }
22463 // lane-t900 r9: which ALPHABET this block read (3-symbol
22464 // motion_mode vs 2-symbol obmc) and the range after -- the
22465 // two give the same value with a different narrowing (class
22466 // wrong-alphabet-same-value).
22467 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
22468 eprintln!(
22469 "EC_MM2 mi_row={mi_row} mi_col={mi_col} row={bsize_idx} warp_elig={} \
22470 scaled={} fimv={} obmc={} warped={} rng={}",
22471 warp_eligible as u8,
22472 ref_is_scaled as u8,
22473 force_integer_mv as u8,
22474 obmc_selected as u8,
22475 warped_selected as u8,
22476 dec.debug_state().0,
22477 );
22478 }
22479 }
22480 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
22481 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
22482 // libaom's `av1_init_warp_params` runs for every inter
22483 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
22484 // reachable when `warp_params` is still `None` here: a block
22485 // that read (and got) local `WARPED_CAUSAL` above already has
22486 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
22487 // checks FIRST and short-circuits on -- the global branch is an
22488 // `else if`, never layered on top. `is_global_mv_block` already
22489 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
22490 // >=8px both dims, matching `av1_init_warp_params`'s
22491 // `block_height < 8 || block_width < 8` early return) and, via
22492 // `motion_mode_eligible`'s own suppression above, the
22493 // `force_integer_mv` case never reads a motion_mode symbol at
22494 // all -- checked again here directly since this branch fires
22495 // independent of `motion_mode_eligible`.
22496 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
22497 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
22498 warp_params = crate::warp::global_warp_params(gm_ref.params);
22499 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
22500 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
22501 }
22502 }
22503 if crate::envflags::env_flag!("EC_AV1_TELL") {
22504 eprintln!(
22505 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
22506 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
22507 );
22508 }
22509 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
22510 // this block's switchable_interp context when that neighbour coded
22511 // the SAME reference frame this block is about to read -- a
22512 // different-ref neighbour reads as "no neighbour" ([3, 3], the
22513 // sentinel `Neighbours::new` already seeds unset slots with),
22514 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
22515 // block next to a LAST_FRAME one inherits that neighbour's filter
22516 // choice into its own context, corrupting the symbol it reads.
22517 // lane-av1idx r2: also match on the neighbour's SECOND reference
22518 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
22519 // see the 16x16 leaf's own comment above for the spec citation.
22520 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
22521 || neighbours.above_ref1[cmi] == Some(ref_frame)
22522 {
22523 neighbours.above_filter[cmi]
22524 } else {
22525 [3, 3]
22526 };
22527 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
22528 || neighbours.left_ref1[rmi] == Some(ref_frame)
22529 {
22530 neighbours.left_filter[rmi]
22531 } else {
22532 [3, 3]
22533 };
22534 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
22535 dec,
22536 cdfs,
22537 interp_fixed,
22538 enable_dual_filter,
22539 gm_nontrans || warped_selected,
22540 above_filter_ctx,
22541 left_filter_ctx,
22542 false,
22543 );
22544 block_filter = resolved_filter;
22545 globalmv_for_lf = is_globalmv;
22546 if crate::envflags::env_flag!("EC_AV1_TELL") {
22547 eprintln!(
22548 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
22549 dec.debug_bitpos(), dec.debug_state().0
22550 );
22551 }
22552 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22553 eprintln!(
22554 "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={}",
22555 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()
22556 );
22557 }
22558 // lane-rect r2: see the compound path's matching comment above --
22559 // `grid` must be stamped with the block's true bh4/bw4 span, not
22560 // a square `bw4`x`bw4` guess.
22561 for dr in 0..bh4 {
22562 for dc in 0..bw4 {
22563 grid.set(
22564 mi_row + dr,
22565 mi_col + dc,
22566 MiInfo {
22567 is_inter: true,
22568 ref_frame,
22569 // An interintra block records ref_frame[1] ==
22570 // INTRA_FRAME (0): warp-sample gathering
22571 // (libaom av1_findSamples, mvref_common.c:1155)
22572 // requires ref_frame[1] == NONE_FRAME, so such a
22573 // neighbour must not donate samples or count in
22574 // num_proj_ref.
22575 ref_frame1: interintra_mode.map(|_| 0),
22576 mv1: None,
22577 mv,
22578 is_new_mv,
22579 size: bw4,
22580 size_h: bh4,
22581 is_global_mv0: is_global_mv_block,
22582 is_global_mv1: false,
22583 },
22584 );
22585 }
22586 }
22587 mode_for_tx = 0;
22588 uv_predict_mode = DC_PRED;
22589
22590 // lane-superres r9: spec 7.11.3.3's x_scale_fp comes from LUMA
22591 // widths only (r8's derivation) and applies unchanged to the
22592 // chroma calls below (their x_q4 is already in the chroma
22593 // plane's own pixel units). `mc::predict_scaled` has no warp/OBMC
22594 // /interintra counterpart -- those three combinations are refused
22595 // by name instead of silently sampling a scaled reference wrong
22596 // (warp_params/obmc_selected/interintra_mode are all resolved by
22597 // this point, every symbol for this block already read).
22598 let luma_scale = mc::scale_factor(py_ref.width, frame_width);
22599 if luma_scale != mc::REF_NO_SCALE {
22600 // lane-scaledref r1: libaom `allow_warp`
22601 // (av1/common/reconinter.c:41) suppresses BOTH local and
22602 // global warp under a scaled reference and predicts
22603 // translationally instead -- that fallback is implemented
22604 // below, but the one real aomenc stream this round found
22605 // that reaches it (`--enable-warped-motion=1`,
22606 // `--superres-denominator=16`, seed 47) still mismatches
22607 // ffmpeg at frame 2 luma, so the case stays refused by name
22608 // until it has a green gate rather than shipping wrong
22609 // pixels behind a lifted refusal.
22610 if warp_params.is_some() {
22611 SCALED_WARP_FALLBACK_HITS.with(|c| c.set(c.get() + 1));
22612 return Err(unsupported(
22613 "warp prediction with a scaled reference (superres, unimplemented)",
22614 ));
22615 }
22616 if obmc_selected {
22617 SCALED_OBMC_HITS.with(|c| c.set(c.get() + 1));
22618 }
22619 if interintra_mode.is_some() {
22620 SCALED_INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
22621 }
22622 }
22623
22624 // lane-inter16ab r2: `is_sub8x8_inter`'s neighbour walk reads the
22625 // PREVIOUS strip's `mv`/`ref_frame`/`interp_filters`
22626 // (reconinter_template.inc:75-82); record them for the next 1:4
22627 // strip, which is the only reader.
22628 INTER_LAST_MC.with(|c| c.set(Some((ref_frame, mv, h_filter, v_filter))));
22629 let mut pred_y = vec![0u16; side * side];
22630 let mut pred_u = vec![0u16; chroma_side * chroma_side];
22631 let mut pred_v = vec![0u16; chroma_side * chroma_side];
22632 if luma_scale == mc::REF_NO_SCALE {
22633 mc::predict_with_filters_kern(
22634 &py_ref.data,
22635 py_ref.width,
22636 py_ref.true_width,
22637 py_ref.true_height,
22638 mv_to_q4(px, mv.1, true),
22639 mv_to_q4(py, mv.0, true),
22640 side,
22641 side,
22642 write_w,
22643 write_h,
22644 h_filter,
22645 v_filter,
22646 &mut pred_y,
22647 );
22648 mc::predict_with_filters_kern(
22649 &pu_ref.data,
22650 pu_ref.width,
22651 pu_ref.true_width,
22652 pu_ref.true_height,
22653 mv_to_q4(cpx, mv.1, false),
22654 mv_to_q4(cpy, mv.0, false),
22655 chroma_side,
22656 chroma_side,
22657 write_chroma_w,
22658 write_chroma_h,
22659 h_filter,
22660 v_filter,
22661 &mut pred_u,
22662 );
22663 mc::predict_with_filters_kern(
22664 &pv_ref.data,
22665 pv_ref.width,
22666 pv_ref.true_width,
22667 pv_ref.true_height,
22668 mv_to_q4(cpx, mv.1, false),
22669 mv_to_q4(cpy, mv.0, false),
22670 chroma_side,
22671 chroma_side,
22672 write_chroma_w,
22673 write_chroma_h,
22674 h_filter,
22675 v_filter,
22676 &mut pred_v,
22677 );
22678 } else {
22679 mc::predict_scaled_kern(
22680 &py_ref.data,
22681 py_ref.width,
22682 py_ref.true_width,
22683 py_ref.true_height,
22684 mv_to_q4(px, mv.1, true),
22685 mv_to_q4(py, mv.0, true),
22686 luma_scale,
22687 side,
22688 side,
22689 write_w,
22690 write_h,
22691 h_filter,
22692 v_filter,
22693 &mut pred_y,
22694 );
22695 mc::predict_scaled_kern(
22696 &pu_ref.data,
22697 pu_ref.width,
22698 pu_ref.true_width,
22699 pu_ref.true_height,
22700 mv_to_q4(cpx, mv.1, false),
22701 mv_to_q4(cpy, mv.0, false),
22702 luma_scale,
22703 chroma_side,
22704 chroma_side,
22705 write_chroma_w,
22706 write_chroma_h,
22707 h_filter,
22708 v_filter,
22709 &mut pred_u,
22710 );
22711 mc::predict_scaled_kern(
22712 &pv_ref.data,
22713 pv_ref.width,
22714 pv_ref.true_width,
22715 pv_ref.true_height,
22716 mv_to_q4(cpx, mv.1, false),
22717 mv_to_q4(cpy, mv.0, false),
22718 luma_scale,
22719 chroma_side,
22720 chroma_side,
22721 write_chroma_w,
22722 write_chroma_h,
22723 h_filter,
22724 v_filter,
22725 &mut pred_v,
22726 );
22727 }
22728
22729 // lane-scaledref r1: libaom `allow_warp` (av1/common/reconinter.c:41)
22730 // opens with `if (av1_is_scaled(sf)) return 0;` -- BOTH local
22731 // (`wm_params`) and global warp fall back to the translational
22732 // prediction above when the reference is scaled, even though the
22733 // motion_mode symbol was still read and warp_params still
22734 // resolved. Suppress the warp, keep every symbol read.
22735 if let Some(params) = warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE) {
22736 // `av1_init_warp_params` is per PLANE: the luma plane's
22737 // own block is `write_w`x`write_h` (a PARTITION_HORZ/VERT
22738 // strip is not `side`x`side`), so a strip under 8 px in
22739 // either direction keeps the translational prediction too.
22740 if warp_plane_allowed(write_w, write_h) {
22741 crate::warp::warp_affine(
22742 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
22743 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
22744 side as i32, side as i32, 0, 0,
22745 );
22746 }
22747 // libaom `av1_init_warp_params` (reconinter.c): warp is
22748 // per PLANE and bails out at `block_width < 8 ||
22749 // block_height < 8`, so a plane whose own block is under
22750 // 8x8 keeps the translational prediction built above --
22751 // in 420 that is every chroma plane whose own width or
22752 // height is under 8 -- `write_chroma_w`/`write_chroma_h`,
22753 // NOT the square `chroma_side` (lane-t900 r5: an 8x16 luma
22754 // block has `chroma_side == 8` but a 4x8 chroma block, so
22755 // the square side warped chroma libaom predicts
22756 // translationally; lane-gmaffine r4 for the 8x8 leaf).
22757 if warp_plane_allowed(write_chroma_w, write_chroma_h) {
22758 crate::warp::warp_affine(
22759 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
22760 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
22761 chroma_side as i32, chroma_side as i32, 1, 1,
22762 );
22763 crate::warp::warp_affine(
22764 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
22765 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
22766 chroma_side as i32, chroma_side as i32, 1, 1,
22767 );
22768 }
22769 }
22770
22771 if obmc_selected {
22772 obmc_blend(
22773 grid,
22774 neighbours,
22775 mi_row,
22776 mi_col,
22777 bw4,
22778 bh4,
22779 mi_rows as usize,
22780 mi_cols as usize,
22781 side,
22782 write_w,
22783 write_h,
22784 chroma_side,
22785 px,
22786 py,
22787 cpx,
22788 cpy,
22789 ref_y,
22790 ref_u,
22791 ref_v,
22792 other_refs,
22793 interp_fixed,
22794 frame_width,
22795 &mut pred_y,
22796 &mut pred_u,
22797 &mut pred_v,
22798 )?;
22799 }
22800
22801 // Mutually exclusive with warp/OBMC (motion_mode is not read for
22802 // an interintra block): blend the intra predictor over the MC
22803 // result, all planes (reconinter.c av1_build_interintra_predictor
22804 // plane loop).
22805 if let Some(ii) = interintra_mode {
22806 if write_w != write_h {
22807 INTERINTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
22808 }
22809 interintra_blend(y, px, py, write_w, write_h, side, ii, wedge_mask, &mut pred_y);
22810 interintra_blend(
22811 u, cpx, cpy, write_chroma_w, write_chroma_h, chroma_side, ii, wedge_mask,
22812 &mut pred_u,
22813 );
22814 interintra_blend(
22815 v, cpx, cpy, write_chroma_w, write_chroma_h, chroma_side, ii, wedge_mask,
22816 &mut pred_v,
22817 );
22818 }
22819
22820 // lane-inter16ab r2: libaom `build_inter_predictors_sub8x8`
22821 // (reconinter_template.inc:87-160). A 4:2:0 chroma block under a
22822 // 16x4 (4x16) luma pair covers TWO luma blocks, so it is built in
22823 // `b4_w x b4_h` = 8x2 (2x8) pieces, each from its own strip's
22824 // mv/ref/filters. The bottom (right) piece is this strip's own mv
22825 // over its own rows, which the whole-block prediction above
22826 // already wrote there (MC is position-invariant for a fixed mv),
22827 // so only the FIRST piece has to be rebuilt -- and only when
22828 // `is_sub8x8_inter` holds, i.e. the previous strip was itself a
22829 // single-reference inter block (`prev`), else libaom falls
22830 // through to the ordinary whole-block predictor.
22831 if let Some(s) = strip_chroma.filter(|s| s.has_chroma)
22832 && let Some((prev_ref, prev_mv, prev_h, prev_v)) = s.prev
22833 && luma_scale == mc::REF_NO_SCALE
22834 {
22835 let (piece_w, piece_h) = if s.horz { (8usize, 2usize) } else { (2usize, 8usize) };
22836 let (_, prev_u, prev_v_plane) = ref_planes(prev_ref, ref_y, ref_u, ref_v, other_refs)?;
22837 for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] {
22838 let mut piece = vec![0u16; piece_w * piece_h];
22839 mc::predict_with_filters(
22840 &src.data,
22841 src.width,
22842 src.true_width,
22843 src.true_height,
22844 mv_to_q4(cpx, prev_mv.1, false),
22845 mv_to_q4(cpy, prev_mv.0, false),
22846 piece_w,
22847 piece_h,
22848 prev_h,
22849 prev_v,
22850 &mut piece,
22851 );
22852 for row in 0..piece_h {
22853 dst[row * chroma_side..row * chroma_side + piece_w]
22854 .copy_from_slice(&piece[row * piece_w..(row + 1) * piece_w]);
22855 }
22856 }
22857 INTER16_SUB8_PIECE_HITS.with(|c| c.set(c.get() + 1));
22858 }
22859
22860 // lane-inter4 r2: a rectangular strip's transform tree starts from
22861 // its own rect `max_txsize_rect_lookup` entry, not a square one.
22862 let rect_tu = (write_w, write_h) != (side, side);
22863 vartx_leaves = if rect_tu {
22864 read_block_tx_size_rect(
22865 dec,
22866 cdfs,
22867 neighbours,
22868 at_mi,
22869 (write_w, write_h),
22870 (mi_cols as usize, mi_rows as usize),
22871 skip,
22872 )?
22873 } else {
22874 read_block_tx_size(
22875 dec,
22876 cdfs,
22877 neighbours,
22878 at_mi,
22879 side,
22880 (mi_cols as usize, mi_rows as usize),
22881 true,
22882 skip,
22883 )?
22884 .1
22885 };
22886 if skip {
22887 y.reconstruct_mc_rect(
22888 px,
22889 py,
22890 side,
22891 write_w,
22892 write_h,
22893 &pred_y,
22894 &vec![0i32; side * side],
22895 );
22896 if has_chroma {
22897 u.reconstruct_mc_rect(
22898 cpx,
22899 cpy,
22900 chroma_side,
22901 write_chroma_w,
22902 write_chroma_h,
22903 &pred_u,
22904 &vec![0i32; chroma_side * chroma_side],
22905 );
22906 v.reconstruct_mc_rect(
22907 cpx,
22908 cpy,
22909 chroma_side,
22910 write_chroma_w,
22911 write_chroma_h,
22912 &pred_v,
22913 &vec![0i32; chroma_side * chroma_side],
22914 );
22915 }
22916 luma_grid = vec![0i32; side * side];
22917 u_grid = vec![0i32; chroma_side * chroma_side];
22918 v_grid = vec![0i32; chroma_side * chroma_side];
22919 } else {
22920 // lane-inter4 r2: a rect strip's coefficient context spans its
22921 // OWN width above and height left -- reading `side` cells both
22922 // ways indexes past the tile's last mi row for a bottom strip.
22923 let around = if rect_tu {
22924 neighbours.around_mi_rect(at_mi, write_w, write_h)
22925 } else {
22926 neighbours.around_mi(at, side)
22927 };
22928 // lane-inter16ab r2: the pair's chroma transform sits at the
22929 // EVEN strip's mi origin and spans both strips, so its
22930 // above/left coefficient context is the pair's, not this
22931 // strip's row.
22932 let around_c = match strip_chroma {
22933 Some(s) if s.has_chroma => neighbours.around_mi_rect(
22934 s.pair_mi,
22935 if s.horz { 16 } else { 8 },
22936 if s.horz { 8 } else { 16 },
22937 ),
22938 _ => around,
22939 };
22940 let luma_tx_type;
22941 // lane-sb128c r1: a 128x128 inter block's four chroma units
22942 // are read INSIDE the luma leaf loop (one per 64x64 mu chunk);
22943 // these collect them for the block-level neighbour write-back.
22944 let mut u_units = vec![0i32; chroma_side * chroma_side];
22945 let mut v_units = vec![0i32; chroma_side * chroma_side];
22946 if let Some(leaves) = vartx_leaves.clone() {
22947 // spec 5.11.17's transform tree, leaf by leaf in the order
22948 // `read_var_tx_size` coded it: each unit reads its own
22949 // coefficients against the neighbour magnitudes the
22950 // earlier units already wrote, and reconstructs over its
22951 // own slice of the block's motion-compensated predictor.
22952 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
22953 let mut first_tx_type = TxType::DctDct;
22954 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
22955 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
22956 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
22957 let (tu_grid, tu_tx_type) = if tw == th {
22958 let tx_px = tw;
22959 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
22960 for rr in 0..tx_px {
22961 let start = (row * MI + rr) * side + col * MI;
22962 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
22963 }
22964 let scan = default_scan(tx_px.min(32));
22965 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
22966 read_inter_plane(
22967 dec,
22968 cdfs,
22969 inter_txbset_for(tx_px, reduced),
22970 &scan,
22971 0,
22972 neighbours.around_mi(tu_mi, tx_px)[0],
22973 mode_for_tx,
22974 y,
22975 tu_px,
22976 tu_py,
22977 tx_px,
22978 base_q_idx,
22979 &tu_pred,
22980 None,
22981 Some(tu_skip_ctx),
22982 )?
22983 } else {
22984 // lane-r14 r3: a 1:4 strip's `sub_tx_size_map`
22985 // sub-transform is RECTANGULAR (TX_64X16 ->
22986 // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is
22987 // read with the rect coefficient machinery, at its
22988 // own `txb_skip_ctx`/neighbour spans -- the unit is
22989 // smaller than its block, so `get_txb_ctx_general`'s
22990 // neighbour table applies, not the lone-TU 0.
22991 vartx_rect_leaf_hit(tw, th);
22992 let tu_skip_ctx =
22993 neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
22994 let start = row * MI * side + col * MI;
22995 read_inter_plane_rect(
22996 dec,
22997 cdfs,
22998 rect_inter_luma_set(tw, th)?,
22999 (tw, th),
23000 side,
23001 0,
23002 neighbours.around_mi_rect(tu_mi, tw, th)[0],
23003 mode_for_tx,
23004 y,
23005 tu_px,
23006 tu_py,
23007 &pred_y[start..],
23008 None,
23009 Some(tu_skip_ctx),
23010 )?
23011 };
23012 if idx == 0 {
23013 first_tx_type = tu_tx_type;
23014 }
23015 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
23016 // lane-sb128c r1: libaom's `decode_token_recon_block`
23017 // walks 64x64 "mu" chunks (`mu_blocks_wide/high =
23018 // mi_size_wide[BLOCK_64X64]`) and codes EVERY PLANE of
23019 // a chunk before the next one, so a 128x128 block
23020 // interleaves Y,U,V per quadrant -- the same order the
23021 // intra 128 path reads (lane-sb128b r3, measured
23022 // against aomdec's `EC_TRACE_COEFF`). Below 128 a block
23023 // is a single chunk and this never fires.
23024 if side > 64 {
23025 let chunk = (row / 16, col / 16);
23026 let done = idx + 1 == leaves.len()
23027 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
23028 if done {
23029 let (cr, cc) = chunk;
23030 // `av1_get_max_uv_txsize(BLOCK_128X128)` =
23031 // `av1_get_adjusted_tx_size(TX_64X64)` =
23032 // TX_32X32: one 32x32 chroma unit per chunk.
23033 let cu_tx = 32usize;
23034 let luma_span = cu_tx * 2;
23035 let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16);
23036 let cu_around = neighbours.around_mi(cu_mi, luma_span);
23037 let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx);
23038 let cu_scan = default_scan(cu_tx);
23039 for plane_idx in 1..3 {
23040 let (src, buf) = if plane_idx == 1 {
23041 (&pred_u, &mut *u)
23042 } else {
23043 (&pred_v, &mut *v)
23044 };
23045 let mut cu_pred = Vec::with_capacity(cu_tx * cu_tx);
23046 for rr in 0..cu_tx {
23047 let start =
23048 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
23049 cu_pred.extend_from_slice(&src[start..start + cu_tx]);
23050 }
23051 let cu_grid = read_inter_plane(
23052 dec,
23053 cdfs,
23054 chroma_set,
23055 &cu_scan,
23056 plane_idx,
23057 cu_around[plane_idx],
23058 mode_for_tx,
23059 buf,
23060 cu_x,
23061 cu_y,
23062 cu_tx,
23063 base_q_idx,
23064 &cu_pred,
23065 Some(first_tx_type),
23066 Some(3),
23067 )?
23068 .0;
23069 // Immediately, so the NEXT chunk's unit
23070 // reads this one's coefficient context.
23071

Showing the first 1 MiB of this file. View raw.